C++ Inheritance


Inheritance is one of the most powerful concepts in object-oriented programming.


Inheritance is the process of creating a derived(new) class from an existing base class.


The existing class is known as the base class and the new class is referred to as the derived class.

The Advantage of inheritance are:

  • It is reusability of the code.
  • It is helping to increase the reliability of the code.
  • It helps to add some enhancement to the base class.
c++ inheritance

Syntax:

class derived_class_name:  base_class_name
{
	 // body of the derived class.  
};

Access Specifiers

Specifiers Within Same class In Derived Class Outside of the class
Private Yes No No
Protected Yes Yes No
Public Yes Yes Yes


Type of inheritance

  • Single inheritance
  • Multiple inheritance
  • Hierarchical inheritance
  • Multilevel inheritance
  • Hybrid inheritance

Single inheritance

The process of creating a derived class from an existing base class is called single inheritance.

Example:

#include <iostream> 
using namespace std;  
class A // base class
{  
    public:  
        int i=10,j=5;  
};  
class B: public A // derived class
{  
    public:  
        void show(){
        cout << "Addition Of Two Number is: "<< i+j << endl; 
        }
   };       
int main() {  
    B b;
    b.show();
    return 0;  
}

Notepad
When an object of the derived class is created, the base class constructor is executed before the derived class constructor. Destructor are executed in reverse order.




OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.