Karen Baghdasaryan
Karen Baghdasaryan

Reputation: 2271

Is the destructor of a derived class virtual by-default if the base class destructor is virtual?

I was recently reading about virtual functions and virtual destructors, and the following question aroused.

For instance, I have the following inheritance chain.

class Base
{
public:
    virtual ~Base() // note: virtual
    {
        std::cout << "Calling ~Base()\n";
    }
};
 
class Derived: public Base
{
 
public:
 
    ~Derived() 
    {
        std::cout << "Calling ~Derived()\n";
    }
};

I read that virtual functions of the base class are implicitly virtual by-default in the derived classes. So, I thought that the same would apply to the destructors.

I would like to know, if the destructor of the derived class is virtual by-default. If not, I would be delighted if you provided some explanation.

Upvotes: 2

Views: 236

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595702

I thought that the same would apply to the destructors

It does, yes.

I would like to know, if the destructor of the derived class is virtual by-default

In this example, yes it is.

Once something has been marked virtual, all overriding descendants of that something are also virtual, whether they state it explicitly or not.

So, if a method is virtual, all derived methods that override it are also virtual. If a destructor is virtual, all derived destructors are also virtual.

Upvotes: 5

Related Questions