Pac
Pac

Reputation: 167

Am I suppose to use virtual destructor=default to properly handle classes with virtual functions?

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

Upvotes: 4

Views: 110

Answers (1)

Bathsheba
Bathsheba

Reputation: 234715

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.

Upvotes: 5

Related Questions