How do I diagnose and fix 'undefined reference to vtable' in C++?

When you encounter the error 'undefined reference to vtable' in C++, it usually indicates that there is an issue with the implementation of virtual functions or the constructor/destructor of a class that involves virtual methods. This failure often arises when the definitions of virtual functions are missing or incorrectly specified.

Common Causes

  • Missing implementation of virtual functions.
  • Forward declarations without corresponding implementations.
  • Static members or methods declared but not defined.
  • Incorrectly associated header and implementation files.

How to Fix the Issue

To resolve the 'undefined reference to vtable' issue, follow these steps:

  1. Ensure that all virtual functions have been implemented.
  2. Check if your class's destructor is defined if it's declared virtual.
  3. Confirm that any forward declarations have corresponding definitions.
  4. Verify the compilation and linking of implementation files.

Example

class Base {
public:
    virtual void show() = 0; // Pure virtual function
};

class Derived : public Base {
public:
    void show() { // Implementation of pure virtual function
        std::cout << "Derived class implementation";
    }
};

// Ensure to include implementations for all declared members

undefined reference vtable C++ virtual functions linker error class implementation pure virtual functions debugging C++