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.
It does, yes.
In this example, yes it is.
Once something has been marked
virtual, all overriding descendants of that something are alsovirtual, whether they state it explicitly or not.So, if a method is
virtual, all derived methods that override it are alsovirtual. If a destructor isvirtual, all derived destructors are alsovirtual.