How it works...

The way override works is very simple; in a virtual function declaration or definition, it ensures that the function is actually overriding a base class function, otherwise, the compiler will trigger an error.

It should be noted that both override and final keywords are special identifiers having a meaning only in a member function declaration or definition. They are not reserved keywords and can still be used elsewhere in a program as user-defined identifiers.

Using the override special identifier helps the compiler to detect situations when a virtual method does not override another one like shown in the following example:

    class Base 
{
public:
virtual void foo() {}
virtual void bar() {}
};

class Derived1 : public Base
{
public:
void foo() override {}
// for readability use the virtual keyword

virtual void bar(char const c) override {}
// error, no Base::bar(char const)
};

The other special identifier, final, is used in a member function declaration or definition to indicate that the function is virtual and cannot be overridden in a derived class. If a derived class attempts to override the virtual function, the compiler triggers an error:

    class Derived2 : public Derived1 
{
virtual void foo() final {}
};

class Derived3 : public Derived2
{
virtual void foo() override {} // error
};

The final specifier can also be used in a class declaration to indicate that it cannot be derived:

    class Derived4 final : public Derived1 
{
virtual void foo() override {}
};

class Derived5 : public Derived4 // error
{
};

Since both override and final have this special meaning when used in the defined context and are not in fact reserved keywords, you can still use them anywhere elsewhere in the C++ code. This ensured that existing code written before C++11 did not break because of the use of these names for identifiers:

    class foo 
{
int final = 0;
void override() {}
};
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset