C++ Undefined Reference to vtable and inheritance

前端 未结 3 783
死守一世寂寞
死守一世寂寞 2020-11-29 04:56

File A.h

#ifndef A_H_
#define A_H_

class A {
public:
    virtual ~A();
    virtual void doWork();
};

#endif

File Child.h

         


        
相关标签:
3条回答
  • 2020-11-29 05:34

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

    0 讨论(0)
  • 2020-11-29 05:39

    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.

    0 讨论(0)
  • 2020-11-29 05:59

    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;
    };
    
    0 讨论(0)
提交回复
热议问题