0
votes

Yes I have seen a lots of posts about using the keywords virtual and override for destructors in C++. I also think I understand the usage:

  • if a base class has a virtual destructor and a derived class overrides it, if the signatures are different, the program will not compile due to override.

However I am wondering - or I have seen it also several times in someones code, that it is used like this:

class Base
{
   public:
          ~Base();
};

class Derived : public Base
{
   public:
         ~Derived() override;
};

Does this override on a destructor of a non-virtual function in the base class actually has any impact on the program / compiling or anything? Or is it just used wrongly in that case?

1
That will not compile.Mansoor
GCC: error: 'Derived::~Derived()' marked 'override', but does not overrideEvg
What will not compile? And why, because over "override"?malajedala
@malajedala yes, you don't have to repeat the "virtual" keyword in derived classes, although I would recommend doing so (to avoid exactly the kind of confusion you just had).Cedric

1 Answers

2
votes

You code doesn't compile because Base::~Base is not virtual.

Oh ok, maybe I have overseen this: if the Base class derives from another class, say SuperBase class - which has a virtual destructor, then the destructor of Base would be virtual without using the keyword right?

Correct. If a method is virtual in a base class, then the method in the child class with the same name and same signature will also be implicitly virtual. virtual keyword can be omitted.

A good practice is to always use the keyword override on a method intended to override. This has two big advantages: it makes it clear to a human reader that the method is virtual and overrides and it avoid some bugs where the method is indented to override, but it silently doesn't (e.g. const mismatch).

Destructors are a special case in the sense that that they override a parent virtual destructor, even if they have different names.