C++ Undefined Reference to vtable and inheritance

走远了吗. 提交于 2019-11-26 09:39:21

问题


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.


回答1:


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.




回答2:


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;
};



回答3:


Make sure to delete any "*.gch" files if none of the other responses help you.



来源:https://stackoverflow.com/questions/9406580/c-undefined-reference-to-vtable-and-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!