c++ undefined reference to vtable

I Just encountered the same problem, but my problem was that I had not written the destructor code in my .cpp file.

class.h:

class MyClass {
public:
    MyClass();
    virtual ~MyClass();
};

class.cpp:

MyClass::MyClass() {}

It just gave me the vtable error message, and implementing the (empty) destructor solved the problem.

[Edit] Thus, the corrected class file looks like this:

MyClass::MyClass() {}
MyClass::~MyClass() {}

That error also happens if you forget the = 0 for pure virtual functions

Error:

class Base {
    public:
        virtual void f();
};

class Derived : public Base {
    public:
        virtual void f() {}
};

int main() {
    Derived d;
    Base *b = &d;
    (void)b;
}

No error:

class Base {
    public:
        virtual void f() = 0;
};

This is because without the = 0, C++ does not know that it is a pure virtual function, treats it as a declaration, expecting a later definition.

Tested on g++ 5.2.1.

Tested as of GCC 11.2.0, the error message changed to:

undefined reference to `typeinfo for Base'

command:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp

You're not including the Sum.o object file on your compile&link line (second g++ use).

Tags:

C++

G++