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:
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?
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 (eg const
mismatch).
Destructors are a special case in the sense that that they override a parent virtual destructor, even if they have different names.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.