Override and final Identifiers in C++ 11

  • Override identifier in C++

Function overriding is redefinition of base class function in its derived class with same signature i.e return type and parameters.
But there may be situations when a programmer makes a mistake while overriding that function. So, to keep track of such an error, C++11 has come up with the keyword override. It will make the compiler to check the base class to see if there is a virtual function with this exact signature. And if there is not, the compiler will show an error.

In short, override serves two purposes:

  1. It shows the reader of the code that “this is a virtual method, that is overriding a virtual method of the base class.”
  2. The compiler also knows that it’s an override, so it can “check” that you are not altering/adding new methods that you think are overrides.

Example:

class base
{
  public:
    virtual int foo(float x) = 0; 
};


class derived: public base
{
   public:
     int foo(float x) override { ... } // OK
}

class derived2: public base
{
   public:
     int foo(int x) override { ... } // ERROR because argument type is different
     float foo(int x) override { ... } // ERROR because return type is different
};

class derived3: public base
{
   public:
     float foo(int x) override { ... } // ERROR because return type is different
};
  • Final identifier in C++

Final identifiers serves two purpose:

  1. To prevent for override the base class virtual function in derived class.
class base
{
public:
	virtual int func() final
	{
		return 1;
	}
};

class derived : public base
{
public:
	int func()  // ERROR 'base::func': function declared as 'final' cannot be overridden by 'derived::func'
	{
		return 0;
	}
};

2. To prevent inheritance of ‘class’ by derived class. If a class is marked as final then it becomes non inheritable and it cannot be used as base class

class base final
{
public:
	virtual int func()
	{
		return 1;
	}
};

class derived : public base  //ERROR 'derived': cannot inherit from 'base' as it has been declared as 'final'
{
public:
	int func()
	{
		return 0;
	}
};

Note that override and final are not language keywords. They are technically identifiers for declarator attributes.

  • 23
    Shares

One Reply to “Override and final Identifiers in C++ 11”

Comments are closed.