开发者

Strange error message when a class method is missing [duplicate]

开发者 https://www.devze.com 2023-04-08 11:20 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::
This question already has answers here: Closed 11 years ago.

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 开发者_如何学Goobvious when you are experienced, but for a beginner like me it's not!

Thanks for your help.


vtable is created for the class that contains virtual function and for the classes derived from it.It means in your program vtable will be created for BaseClass and DerivedClass.Each of these vtables would contain the address of virtual function void func().Now note that DerivedClass doesn't contain the definition of void func(),hence its vtable contains the address of BaseClass's void func() function.That's why the compiler is giving error undefined reference to vtable for DerivedClass.


It seems your compiler didn't generate a vtable for the DerivedClass. A vtable is basically a table that contains function pointers for every virtual function. By storing a pointer to the class's vtable (usually called vptr) for every object the correct virtual function to call can be determined at runtime. Although it is an implementation detail of the specific compiler, this is the usual way to implement virtual functions, which are bound at runtime and can therefore not be called like normal functions.

My first guess would be that the compiler didn't generate a vtable for DerivedClass because it doesn't define any virtual functions so it uses the BaseClass's vtable. Although that's a bit strange, it is the only idea I can come up with. But I'm not that well-versed in compiler architecture and maybe somebody has a better solution.

0

精彩评论

暂无评论...
验证码 换一张
取 消