I am reading an awesome awesome C++11 tutorial and the author provides this example while explaining the final
keyword:
struct B { virtual void f() const final; // do not override virtual void g(); }; struct D : B { void f() const; // error: D::f attempts to override final B::f void g(); // OK };
So does it make sense using here the final
keyword? In my opinion you can just avoid using the virtual
keyword here and prevent f()
from being overridden.
No, the virtual keyword on derived classes' virtual function overrides is not required.
Rules for Virtual FunctionsVirtual functions cannot be static. A virtual function can be a friend function of another class. Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism.
Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances” of a given class appearing in an inheritance hierarchy when using multiple inheritances. Need for Virtual Base Classes: Consider the situation where we have one class A .
The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class. The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into a derived class.
If you don't mark the function as virtual
and final
then the child-class can still implement the function and hide the base-class function.
By making the function virtual
and final
the child-class can not override or hide the function.
Yes! In the example you provide, the final
keyword prevents any derived classes from overriding f()
as you correctly say. If the function is non-virtual, D:f()
is allowed to hide the base class version of the function:
struct B { void f() const; // do not override virtual void g(); }; struct D : B { void f() const; // OK! void g(); // OK };
By making f()
a virtual
and final
function, any attempt at overriding or hiding causes a compile error.
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