Search code examples
c++c++11overridingvirtual-destructor

Override identifier after destructor in C++11


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?


Solution

  • 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.