undefined reference to vtable
undefined reference to vtable in C++ means the C++ linker could not find the virtual method table (vtable) for a polymorphic class because one or more non-pure virtual methods declared in the class was never implemented.
How do I fix undefined reference to vtable?
To fix undefined reference to vtable in C++, locate the line causing the error and check the values right before it runs. Most occurrences happen because of declaring a virtual destructor without an implementation body. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.
What does undefined reference to vtable mean?
When a C++ class declares virtual functions, the compiler generates a virtual method table (vtable). In GCC and Clang, the vtable is emitted in the object file where the first non-inline non-pure virtual member function is defined. If that function is not defined, the linker fails with 'undefined reference to vtable'.
Why does undefined reference to vtable happen?
1. Declaring a virtual destructor without an implementation body
A virtual destructor must always have an implementation body, even if it is empty.
Breaks
class Base {
public:
virtual ~Base(); // declared but never defined in .cpp!
};Works
class Base {
public:
virtual ~Base() = default;
};2. Forgetting to define a virtual method declared in the class header
Declaring 'virtual void execute();' without providing 'void Base::execute() {}' in a .cpp file causes the linker to omit the vtable.
Breaks
class Widget {
virtual void render();
};Works
class Widget {
virtual void render() = 0; // if abstract
// or provide: virtual void render() {}
};How to find it in your own code
Ensure all declared virtual methods are defined in their corresponding source file or inlined with '= default' or '{}'. If the method is intended to be pure abstract, append '= 0'. Always give virtual destructors an implementation body.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.