Possible Duplicate:
GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'
I have been banging my head against a wall for a long time because of a strange ld error.
So I reproduced it in a small test case to understand the issue.
I declared a class and I derived another one in a header file:
class BaseClass {
public:
BaseClass(){};
virtual void func(){};
};
class DerivedClass: public BaseClass {
public:
DerivedClass();
void func();
};
Then I defined the constructor but forgot to define func (voluntary here, but that actually what I did with a silly copy/paste…):
DerivedClass::DerivedClass(){
cout << "Derived constructor" << endl;
}
//void DerivedClass::func(){
// cout << "Derived func" << endl;
//}
Then I get:
undefined reference to `vtable for DerivedClass’
Edit: And the message points the declaration of the consctructor!
If I uncomment the definition of func, then I have no error. So my question:
Why does the linker didn’t tell me that the definition of func is missing?
The solution might be obvious when you are experienced, but for a beginner like me it’s not!
Thanks for your help.
vtableis created for the class that contains virtual function and for the classes derived from it.It means in your programvtablewill be created forBaseClassandDerivedClass.Each of thesevtableswould contain the address of virtual functionvoid func().Now note thatDerivedClassdoesn’t contain the definition ofvoid func(),hence itsvtablecontains the address ofBaseClass‘svoid func()function.That’s why the compiler is giving errorundefined reference to vtable for DerivedClass.