File A.h
#ifndef A_H_ #define A_H_ class A { public: virtual ~A(); virtual void doWork(); }; #endif
File Child.h
#ifndef CHILD_H_ #define CHILD_H_ #include "A.h" class Child: public A { private: int x,y; public: Child(); ~Child(); void doWork(); }; #endif
And Child.cpp
#include "Child.h" Child::Child(){ x = 5; } Child::~Child(){...} void Child::doWork(){...};
The compiler says that there is a undefined reference to vtable for A
. I have tried lots of different things and yet none have worked.
My objective is for class A
to be an Interface, and to seperate implementation code from headers.
When linker says "undefined reference to vtable for IBase" it basically means that Derived has vtable reference to IBase but it can't find any compiled object code of IBase to look up to. So the bottom line is that class IBase has declarations without implementations.
V-tables (or virtual tables) are how most C++ implementations do polymorphism. For each concrete implementation of a class, there is a table of function pointers to all the virtual methods. A pointer to this table (called the virtual table) exists as a data member in all the objects.
You can fix undefined reference in C++ by investigating the linker error messages and then providing the missing definition for the given symbols. Note that not all linker errors are undefined references, and the same programmer error does not cause all undefined reference errors.
When we compile these files separately, the first file gives “undefined reference” for the print function, while the second file gives “undefined reference” for the main function. The way to resolve this error is to compile both the files simultaneously (For example, by using g++).
Why the error & how to resolve it?
You need to provide definitions for all virtual functions in class A
. Only pure virtual functions are allowed to have no definitions.
i.e: In class A
both the methods:
virtual ~A(); virtual void doWork();
should be defined(should have a body)
e.g.:
A.cpp
void A::doWork() { } A::~A() { }
Caveat:
If you want your class A
to act as an interface(a.k.a Abstract class in C++) then you should make the method pure virtual.
virtual void doWork() = 0;
Good Read:
What does it mean that the "virtual table" is an unresolved external?
When building C++, the linker says my constructors, destructors or virtual tables are undefined.
My objective is for A to be an Interface, and to seperate implementation code from headers.
In that case, make the member function as pure virtual in class A.
class A { // ... virtual void doWork() = 0; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With