Alberto
Alberto

Reputation: 12949

Virtual propagation on destructor

I know that virtual propagates to the derived class method and it's optional to put as keyword on the method declaration on the derived class, and i know that i MUST mark as virtual the destructor of the base class, in order to have polymorphic destruction, but what i want to know is if the default destructor of the derived class, inherit the virtual from the virtual destructor of the base class, and so i have to explicit write it on the derived class.

Example:

class A{
public:
    virtual ~A() override = default;
}
class B: public A{
public:
    // have i to write this or it's already what the compiler get as default?
    virtual ~B() override = default;
}

Upvotes: 0

Views: 185

Answers (2)

Pete Becker
Pete Becker

Reputation: 76448

The destructor for a derived class, despite having a different name from the destructor of the base class, overrides the base class destructor. Just like any other override, it’s virtual if the one it overrides is virtual.

Upvotes: 2

rustyx
rustyx

Reputation: 85481

Yes once a member function (destructor included) is marked as virtual in the base class, it remains virtual in all derived classes.

You can omit the keyword virtual in ~B() declaration, and even omit ~B() entirely, if it's empty.

Upvotes: 0

Related Questions