Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 // ?;
like image 980
towi Avatar asked Apr 03 '11 14:04

towi


People also ask

Can I override a non-virtual function?

You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.

Can we override virtual method?

A virtual method is first created in a base class and then it is overridden in the derived class. A virtual method can be created in the base class by using the “virtual” keyword and the same method can be overridden in the derived class by using the “override” keyword.

Can we override virtual method in C++?

Virtual, final and override in C++ C++11 added two keywords that allow to better express your intentions with what you want to do with virtual functions: override and final . They allow to express your intentions both to fellow humans reading your code as well as to the compiler.

Can we override private virtual function?

A private virtual function can be overridden by derived classes, but can only be called from within the base class.


1 Answers

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.

like image 168
Johannes Schaub - litb Avatar answered Nov 15 '22 07:11

Johannes Schaub - litb