简体   繁体   中英

How to override non-virtual functions?

The very new syntax of override allows to let the compiler to report an error, if one does not really override a virtual function N3206 .

class Base {
    virtual void vfunc();
    void afunc();
};

The following cases will be an error in class Derived : public Base , as mentioned in the Std examples:

  • void vfunk() override; // err: typo
  • void vfunc(int) override; // err: argument
  • void vfunc() const override; // err: cv

But what if the base method is not virtual ?

  • void afunk() override; // ?
  • void afunc(int) override; // ?
  • void afunc() const override // ?;

The spec draft (n3242) says

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.

Since the function declarations you show are not virtual, you also run afoul of

A virt-specifier-seq shall contain at most one of each virt-specifier. The virt-specifiers override and final shall only appear in the declaration of a virtual member function.

Note that a function that has the same name and parameter list (including constness) as a base function, but that is not virtual does not override that base function. It is instead said to hide the base function.

Designating that a function hides a base function by putting new instead of override after the function's declaration was part of the C++0x draft, but will not be part of C++0x as there were problems with finding syntax spots for non-function members for putting new at, in time. Consequently, it was voted out for C++0x.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM