In this video, we'll learn about the c++11 final specifier.
We can use the final specifier in two contexts.
At the class level,
the final specifier prevents a class from being derived from or subclassed.
Sometimes frameworks have final classes that can't be subclassed.
In some cases, this is done for better compiler optimization.
Other times, it may be done to ensure that objects are copied safely without slicing.
When used at the method or function level,
the final specifier prevents the method from being overridden in derived classes.
This can also be done for better compiler optimization.
The syntax for using the final specifier at the class level is pretty simple.
We simply add the final specifier after the class name when we declare it.
In the first example, my class cannot be derived from.
And in the second example, derived cannot be derived from.
If you try to drive a class from these classes, the compiler will generate a compiler error.
Now let's see the final specifier in the context of a virtual function.
In this case, we have a simple class hierarchy with three classes: a b and c.
The base class a declares the function do something as virtual.
Class b is derived from a and it overrides do something
but it also marks it as final.
So do something can no longer be overridden further down in the hierarchy.
Notice that if class c tries to override do something, the compiler generates an error.