The C++11 FDIS it 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. [ 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 };
What if B::f
would not have been marked virtual? Is the program ill-formed, then? Or is override
then to be ignored`. I can not find any handling of this case in the std text.
Update 1/2 (merged) I forwarded a request to the C++ Editors to look into things. Thanks Johannes to pointing that out to me.
But by realizing this I found, that the intention of the "override" contextual keyword can not be met: if a typo in the function name or the wrong argument type does make the function itself non-virtual, then the standard's text never applies -- and "override" is rendered useless.
The best possible solution may be
By default, methods are non-virtual, and they cannot be overridden. Virtual modifiers cannot be used with static, abstract, private, and override modifiers.
You can override any method of a class, the question is really how to access the non-virtual method, or should I have made the method virtual in the first place. With a virtual method, you always access the overridden method regardless of the class variable used to reference it.
C++ has a rule about overridden functions: they don't have to be explicitly declared as virtual . Consider your example without override : double getAge(int id); .
Overriding a function that is not a member function of the class. If the function is not a member function of the class, we cannot access that function with the help of class objects. Note: Only the functions that the derived class inherited from the base class can be overridden.
What if
B::f
would not have been marked virtual? Is the program ill-formed, then?
Yes, it is. Because in order to override something, that something has to be virtual. Otherwise it's not overriding, it's hiding. So, the positive answer follows from the quote in your question.
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