Using final with Inheritance in C++

Hello Everyone!

In this tutorial, we will learn about the concept of the final keyword and also how to use the final keyword with Inheritance in C++.

The final specifier with Inheritance

The final keyword can be used at the time of declaring variables or methods. When we use the final keyword it means it can’t be modified or overridden in the future. The final keyword is not just limited to a  variable or a method, it can be also used in a parameter or classes as well.

Declaring a final variable:

final int variable_name = 10;

Declaring a final method:

class Base{
    
   public:

    public final void finalMethod(){

        cout<<"Base";

    }

};


Inheritance:

The ability of a class to derive features, characteristic and properties from another class is called Inheritance.

The most important feature of Oops can be called as the concept of Inheritance.

There are two types of class in Inheritance which are:

Super Class: The parent class whose properties are inherited by the child class.

Sub Class: The child class, which inherits the properties from its parent class.

 

syntax of inheritance:

class child_class_name : access_mode parent_class_name
{
  //body of child_class;
};

 

Below is the code example which shows that once you have used the final keyword then it can’t be overridden or modified later.

#include<iostream>
using namespace std;
class Base final{
  
     void func(){
     	cout<<"parent";
     }
};
class Derived : public Base{
  void func(){
    cout<<"Child";
  }
};
int main(){
  Derived obj;
  obj.func();
}
Output:

9 7 C:\Users\D_E_C_O_N_E\Desktop\c++cheatsheet\using final with inheritance.cpp [Error] cannot derive from 'final' base 'Base' in derived type 'Derived'

As you can see in the output section that it displays error:

  [Error] cannot derive from 'final' base 'Base' in derived type 'Derived'

which clearly explains that the final variable, methods or classes can’t be overridden.

I hope I have made my explanation regarding the same quite easy and clear.

let me know in the comment section if you still got anythings to clear the doubt.

 

You may also read :

 

Thank You and Have a great day ahead!

Leave a Reply

Your email address will not be published. Required fields are marked *