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 // ?;
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.
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.
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.
A private virtual function can be overridden by derived classes, but can only be called from within the base class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With