Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to add final keyword to the virtual function in a class that has no base class (is not derived)

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.

like image 624
Eduard Rostomyan Avatar asked May 24 '17 08:05

Eduard Rostomyan


People also ask

Do we need virtual keyword in derived class?

No, the virtual keyword on derived classes' virtual function overrides is not required.

What are the rules to be considered for virtual function?

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.

What is a virtual base class why it is important to make a class virtual?

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 .

When should I use virtual keyword?

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.


2 Answers

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.

like image 155
Some programmer dude Avatar answered Oct 05 '22 19:10

Some programmer dude


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.

like image 23
Karl Nicoll Avatar answered Oct 05 '22 19:10

Karl Nicoll