Should there be a definition for Base dtor?

后端 未结 3 1771
半阙折子戏
半阙折子戏 2021-01-23 16:42

Compiler is giving link error and require to provide definition for Base pure virtual destructor.

class Base
{
public:
    virtual ~Base() = 0;
};

class Derived         


        
相关标签:
3条回答
  • 2021-01-23 16:59

    Yes. There's a non-virtual call of Base::~Base, implicitly from Derived::~Derived. Therefore the compiler is right to complain that Base::~Base must be defined, even if empty.

    0 讨论(0)
  • 2021-01-23 17:10

    Since Derived inherits Base, destroying a Derived object will first call Derived::~Derived and then Base::~Base (the compiler does this for you - whether you like it or not).

    Hence, you have to provide an implementation for Base::~Base. Note that this isn't particularly strange. A pure virtual function can have an implementation. 'pure virtual' only means that the class cannot be instantiated.

    0 讨论(0)
  • 2021-01-23 17:14

    Just provide an empty implementation for it (outside the class definition):

    Base::~Base() { }
    

    Being pure-virtual just means that you must override the member function in any concrete derived class; it doesn't mean that it cannot have a body. In the case of the destructor, you must supply a body, wether the destructor is pure-virtual or not, since it is invoked by the compiler when you destroy the object.

    Just to be clear, you must provide an implementation. Whether it is empty or not is up to you. This is because the compiler generates code that calls the destructor whenever you try to destroy an instance of Base. You could declare a normal virtual Base:

    virtual ~Base();
    

    And never define it. This would be fine as long as you never destroy an instance of Base (questionable conduct, but it would work). However, in your case, Base has a Derived type, which calls the Base class's destructor in its own destructor. That's where your linker error is coming from.

    0 讨论(0)
提交回复
热议问题