softwarelover
softwarelover

Reputation: 1019

Can a base destructor really be overridden by a derived destructor in C++?

All over the web, as well as in Bjarne Stroustrup's C++ book, I see statements like, "If a base destructor is declared virtual then it is overridden by a derived class's destructor."

But, why is it called overriding? Isn't it slightly different than the "usual" way of overriding functions? By usual, I mean a typical virtual function in a derived class, sharing the same method signature as that in the base. In that usual case, either the base version or the derived version is ignored depending on the actual object pointed to by a pointer.... Let's not get into details of how overriding works in the usual sense.

But in cases of destructors, the base destructor WILL eventually be called, no matter what. Also, its name is different. Why is it then called overriding?

Upvotes: 0

Views: 106

Answers (1)

R Sahu
R Sahu

Reputation: 206707

Why is it then called overriding?

Because it overrides the destructor of the base class.

Consider this:

struct Foo
{
   ~Foo() {}
};

struct Bar : Foo
{
   ~Bar() {} // This does not override ~Foo.
};

Foo* fptr = new Bar;
delete fptr;  // ~Foo() is called.

~Bar() will be called if the pointer is Bar*.

Bar* bptr = new Bar;
delete bptr;  // ~Bar() is called.

However, if you change Foo to:

struct Foo
{
   virtrual ~Foo() {}
};

struct Bar : Foo
{
   ~Bar() {} // This overrides ~Foo.
};

then use

Foo* fptr = new Bar;
delete fptr;  // ~Bar() is called.
              // ~Bar() overrides ~Foo().

Upvotes: 2

Related Questions