Unimplemented Pure Virtual Method?

吃可爱长大的小学妹 提交于 2020-05-23 10:37:07

问题


Here is the problem: I keep getting the unimplemented pure virtual method error when trying to compile. I have implemented all of the pure virtual methods in the abstract base class. Any ideas?

here is the abstract base class:

class record{
public:
    virtual int getID()=0;
    virtual record *clone(); 
};

and the implementation:

class sdata: public record{
public:
    sdata(std::string s = ""){data=s; ID=atoi(data.substr(0,8).c_str());}
    virtual int getID(){return ID;}
private:
    std::string data;
    int ID;
};

sorry, here is the complete error message:

Unimplemented pure virtual method 'getID' in 'record'

Perhaps this bit of code is causing the error then:

int hashTable::hash(record *x) {
   return floor(m * (x->getID() * A - floor(x->getID() * A)));
}

回答1:


Without seeing the code causing the error, it's difficult to know exactly what's going on. If this is a compile-time error, I don't see anything here that would cause it.

However, if you're seeing a runtime error, the two most common causes of this that I can think of are:

(1) Calling the member function from within the base class's constructor or destructor (even indirectly).

(2) The derived class calling the base class's version of the function without it being implemented.

An example showing both of these errors would be:

struct Base {
    Base()
    {
        call_foo(); // Oops, indirectly calls Base::foo() (Scenario 1)
    }
    void call_foo() const {
        foo();
    }
protected:
    virtual void foo() const = 0;
};

struct Derived : Base { protected: virtual void foo() const { Base::foo(); // Oops, unimplemented virtual base function (Scenario 2) } };

int main() { Derived().call_foo(); }

== UPDATE: Possible compile-time error ==

I observe in your example code that record has a non-pure-virtual clone() member function returning a record *. Since record is abstract, you can't create a record directly (only its concrete subclasses). This suggests that your clone() member function should probably also be pure virtual; if it tries to (for example) return new record(), you will get an error that your base class has pure virtual functions.




回答2:


It sounds like you have not implemented all the functions from the abstract base class. If a function in your base has the signature:

    void SomeFuction() const;

And you implement the following in your derived class:

    void SomeFuction();

Then you have have not implemented the function because you omitted the const. GCC should tell you what you did not implement.

Related: if you had a concrete implementation of the base, you would have hidden its name in the derived class. To find functions you are [accidentally] hiding, use -Woverloaded-virtual.



来源:https://stackoverflow.com/questions/15777056/unimplemented-pure-virtual-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!