Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of a final virtual function?

Wikipedia has the following example on the C++11 final modifier:

struct Base2 {     virtual void f() final; };  struct Derived2 : Base2 {     void f(); // ill-formed because the virtual function Base2::f has been marked final }; 

I don't understand the point of introducing a virtual function and immediately marking it as final. Is this simply a bad example, or is there more to it?

like image 323
fredoverflow Avatar asked Jul 28 '12 20:07

fredoverflow


People also ask

What is the point of virtual functions?

A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.

Can a virtual function be final?

final specifier (since C++11) Specifies that a virtual function cannot be overridden in a derived class or that a class cannot be derived from.

Why did pure virtual function need?

A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it. It is declared by assigning 0 in the declaration. An abstract class is a class in C++ which have at least one pure virtual function.

Does final improve performance C++?

Marking your classes or member functions as final can improve the performance of your code by giving the compiler more opportunities to resolve virtual calls at compile time.


1 Answers

Typically final will not be used on the base class' definition of a virtual function. final will be used by a derived class that overrides the function in order to prevent further derived types from further overriding the function. Since the overriding function must be virtual normally it would mean that anyone could override that function in a further derived type. final allows one to specify a function which overrides another but which cannot be overridden itself.

For example if you're designing a class hierarchy and need to override a function, but you do not want to allow users of the class hierarchy to do the same, then your might mark the functions as final in your derived classes.

like image 130
bames53 Avatar answered Sep 22 '22 14:09

bames53