Override identifier after destructor in C++11

2020-05-12 04:34发布

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?

2条回答
Bombasti
2楼-- · 2020-05-12 05:10

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
    {}
};
查看更多
趁早两清
3楼-- · 2020-05-12 05:27

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.

查看更多
登录 后发表回答