4

I forgotten my C++. From memory if I have virtual functions I should have a virtual destructor. So I wrote the below. However I get a linker error about B destructor (but not A).

Is the correct solution virtual ~A()=default? It seems to work but I feel like I'm missing something

$ clang++ a.cpp
/usr/bin/ld: /tmp/a-a25aa3.o: in function `B::~B()':
a.cpp:(.text._ZN1BD2Ev[_ZN1BD2Ev]+0x14): undefined reference to `A::~A()'

Source:

class A {
public:
    virtual int test()=0; 
    virtual ~A()=0;
};
class B : public A {
public:
    virtual int BTest()=0;
};

class C : public B {
public:
    int test() override { return 1; }
        int BTest() override { return 2; }
    ~C() override {}    
};

int main() {
    C c;
    c.test();
}
Pac
  • 167
  • 4
  • Destructors need to be defined whether they are `virtual`, non-`virtual`, or pure `virtual` except in (relatively rare) cases in which no instance of the class, nor of any derived class, is instantiated. The reason is that destruction of an instance of a derived class calls the base class destructors. That is true whether the class has other `virtual` functions or not. – Peter Sep 28 '20 at 21:47

1 Answers1

5

Although a pure virtual destructor

virtual ~A() = 0;

is legal standard C++, you'd need to write a function body for this as destructors are not overridden. (If you don't then the linker will fail as you observe.)

Since C++11 the simplest way of making your class polymorphic is to make the default destructor virtual, which you do with

virtual ~A() = default;

So yes, the solution you propose is the correct one.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Do destructors don't overload eachother? I guess it makes sense why this is the solution. Accepted – Pac Sep 28 '20 at 21:28
  • @Pac Not by default, no. You have to make them `virtual` explicitely. Also that's important for _pure virtual_ interfaces: The only real function they need is a virtual destructor. – πάντα ῥεῖ Sep 28 '20 at 21:30