Override identifier after destructor in C++11

C++C++11OverridingVirtual Destructor

C++ Problem Overview


Does the override identifier after virtual destructor declaration have any special meaning?

class Base
{
public:
    virtual ~Base()
    {}
    
    virtual int Method() const
    {}
};

class Derived : public Base
{
public:
    virtual ~Derived() override
    {}
    
    virtual int Method() override // error: marked override, but does not override - missing const
    {}
};

Using override identifier on virtual method is useful as check: compiler will report error when the Base virtual method is actualy not overriden.

Does override on virtual destructor has any meaning/function too?

C++ Solutions


Solution 1 - C++

Yes. If the base destructor is not virtual then the override marking will cause the program to not compile:

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

class Derived : public Base
{
public:
    virtual ~Derived() override //error: '~Derived' marked 'override' but does
                                //        not override any member functions
    {}
};

Solution 2 - C++

It is not override that has special meaning, but the destructor itself:

10.3 Virtual Functions

> 6/Even though destructors are not inherited, a destructor in a derived > class overrides a base class destructor declared virtual; see 12.4 and > 12.5.

If you take this in conjunction with the previous clause:

> 5/If a virtual function is marked with the virt-specifier override and > does not override a member function of a base class, the program is > ill-formed. [ Example:

> struct B { > virtual void f(int); > };

> struct D : B > { > void f(long) override; // error: wrong signature overriding B::f > void f(int) override; // OK > };

> —end example ]

you can see that if a destructor is marked override but the base class does not have a virtual destructor, the program is ill-formed.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEnterTheNameHere BohemianView Question on Stackoverflow
Solution 1 - C++MankarseView Answer on Stackoverflow
Solution 2 - C++John DiblingView Answer on Stackoverflow