The Wayback Machine - https://web.archive.org/web/20250108150133/https://www.geeksforgeeks.org/inheritance-in-c/
Open In App

Inheritance in C++

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the class.

Syntax of Inheritance in C++

class  derived_class_name : access-specifier  base_class_name
{
// body ....
};

where,

  • class: keyword to create a new class
  • derived_class_name: name of the new class, which will inherit the base class
  • access-specifier: Specifies the access mode which can be either of private, public or protected. If neither is specified, private is taken as default.
  • base-class-name: name of the base class.

Note: A derived class doesn’t inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.

Example:

class ABC : private XYZ {...}             //  private derivation
class ABC : public XYZ {...}              // public derivation
class ABC : protected XYZ {...}       // protected derivation
class ABC: XYZ {...}                          // private derivation by default

To better understand inheritance and other OOP principles, enroll in our Complete C++ Course, which breaks down inheritance, polymorphism, and encapsulation in C++.

Examples of Inheritance in C++

The following programs demonstrate how to implement inheritance in our C++ programs.

Example 1: Program to Demonstrate the Simple Inheritance of a Class

CPP
// C++ program to demonstrate how to inherit a class
#include <iostream>
using namespace std;

// Base class that is to be inherited
class Parent {
public:
    // base class members
    int id_p;
    void printID_p()
    {
        cout << "Base ID: " << id_p << endl;
    }
};

// Sub class or derived publicly inheriting from Base
// Class(Parent)
class Child : public Parent {
public:
    // derived class members
    int id_c;
    void printID_c()
    {
        cout << "Child ID: " << id_c << endl;
    }
};

// main function
int main()
{
    // creating a child class object
    Child obj1;

    // An object of class child has all data members
    // and member functions of class parent
    // so we try accessing the parents method and data from
    // the child class object.
    obj1.id_p = 7;
    obj1.printID_p();

    // finally accessing the child class methods and data
    // too
    obj1.id_c = 91;
    obj1.printID_c();

    return 0;
}

Output
Base ID: 7
Child ID: 91

In the above program, the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public data members of the class ‘Parent’ will also be inherited by the class ‘Child’.

Example 2: Access the Inherited Members of the Base Class in Derived Class

C++
// C++ program to illustrate how to access the inherited
// members of the base class in derived class
#include <iostream>
using namespace std;

// Base class
class Base {
public:
    // data member
    int publicVar;

    // member method
    void display()
    {
        cout << "Value of publicVar: " << publicVar;
    }
};

// Derived class
class Derived : public Base {
public:
    // Function to display inherited member
    void displayMember()
    {
        // accessing public base class member method
        display();
    }

    // Function to modify inherited member
    void modifyMember(int pub)
    {
        // Directly modifying public member
        publicVar = pub;
    }
};

int main()
{
    // Create an object of Derived class
    Derived obj;

    // Display the initial values of inherited member
    obj.modifyMember(10);

    // Display the modified values of inherited member
    obj.displayMember();

    return 0;
}

Output
Value of publicVar: 10

In the above example, we have accessed the public members of the base class in the derived class but we cannot access all the base class members directly in the derived class. It depends on the mode of inheritance and the access specifier in the base class.

Modes of Inheritance in C++

Mode of inheritance controls the access level of the inherited members of the base class in the derived class. In C++, there are 3 modes of inheritance:

  • Public Mode
  • Protected Mode
  • Private Mode

Public Inheritance Mode

If we derive a subclass from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in the derived class.

Example:

class ABC : public XYZ {...}              //  public derivation

Protected Inheritance Mode

If we derive a subclass from a Protected base class. Then both public members and protected members of the base class will become protected in the derived class.

Example:

class ABC : protected XYZ {...}       //  protected derivation

Private Inheritance Mode

If we derive a subclass from a Private base class. Then both public members and protected members of the base class will become private in the derived class. They can only be accessed by the member functions of the derived class.

Private mode is the default mode that is applied when we don’t specify any mode.

Example:

class ABC : private XYZ {...}             //  private derivation
class ABC: XYZ {...}                          // private derivation by default

Note: The private members in the base class cannot be directly accessed in the derived class, while protected and public members can be directly accessed. To access or update the private members of the base class in derived class, we have to use the corresponding getter and setter functions of the base class or declare the derived class as friend class.

The below table summarizes the above three modes and shows the access specifier of the members of the base class in the subclass when derived in public, protected and private modes:

Mode-of-inheritance

Examples of Modes of Inheritance

Example 1: Program to show different kinds of Inheritance Modes and their Member Access Levels

CPP
// C++ program to show that a derived class
// doesn’t inherit access to private data members.
// However, it does inherit a full parent object.
class A {
public:
    int x;

protected:
    int y;

private:
    int z;
};

class B : public A {
    // x is public
    // y is protected
    // z is not accessible from B
};

class C : protected A {
    // x is protected
    // y is protected
    // z is not accessible from C
};

class D : private A // 'private' is default for classes
{
    // x is private
    // y is private
    // z is not accessible from D
};

Example 2: Program to Access the Private Members of the Base Class in Derived Class

C++
// C++ program to illustrate how to access the private data
// members of the base class in derived class using public
// getter methods of base class
#include <iostream>
using namespace std;

// Base class
class Base {
private:
    int privateVar;

public:
    // Constructor to initialize privateVar
    Base(int val): privateVar(val){}

    // Public getter function to get the value of privateVar
    int getPrivateVar() const { return privateVar; }

    // Public setter function to set the value of privateVar
    void setPrivateVar(int val) { privateVar = val; }
};

// Derived class
class Derived : public Base {
public:
    // Constructor to initialize the base class
    Derived(int val) : Base(val){}

    // Function to display the private member of the base
    // class
    void displayPrivateVar()
    {
        // Accessing privateVar using the public member
        // function of the base class
        cout << "Value of privateVar in Base class: "
             << getPrivateVar() << endl;
    }

    // Function to modify the private member of the base
    // class
    void modifyPrivateVar(int val)
    {
        // Modifying privateVar using the public member
        // function of the base class
        setPrivateVar(val);
    }
};

int main()
{
    // Create an object of Derived class
    Derived obj(10);

    // Display the initial value of privateVar
    obj.displayPrivateVar();

    // Modify the value of privateVar
    obj.modifyPrivateVar(20);

    // Display the modified value of privateVar
    obj.displayPrivateVar();

    return 0;
}

Output
Value of privateVar in Base class: 10
Value of privateVar in Base class: 20

The above program shows the method in which the private members of the base class remain encapsulated and are only accessible through controlled public or protected member functions.

We can also access the private members of the base class by declaring the derived class as friend class in the base class.

C++
// C++ program to illustrate how to access the private
// members of the base class by declaring the derived class
// as friend class in the base class
#include <iostream>
using namespace std;

// Forward declaration of the Derived class
class Derived;

// Base class
class Base {
private:
    int privateVar;

public:
    // Constructor to initialize privateVar
    Base(int val)
        : privateVar(val)
    {
    }

    // Declare Derived class as a friend
    friend class Derived;
};

// Derived class
class Derived {
public:
    // Function to display the private member of the base
    // class
    void displayPrivateVar(Base& obj)
    {
        // Accessing privateVar directly since Derived is a
        // friend of Base
        cout << "Value of privateVar in Base class: "
             << obj.privateVar << endl;
    }

    // Function to modify the private member of the base
    // class
    void modifyPrivateVar(Base& obj, int val)
    {
        // Modifying privateVar directly since Derived is a
        // friend of Base
        obj.privateVar = val;
    }
};

int main()
{
    // Create an object of Base class
    Base baseObj(10);

    // Create an object of Derived class
    Derived derivedObj;

    // Display the initial value of privateVar
    derivedObj.displayPrivateVar(baseObj);

    // Modify the value of privateVar
    derivedObj.modifyPrivateVar(baseObj, 20);

    // Display the modified value of privateVar
    derivedObj.displayPrivateVar(baseObj);

    return 0;
}

Output
Value of privateVar in Base class: 10
Value of privateVar in Base class: 20

To know more about access modes in a C++ class, refer to the article – Access Modifiers in C++

Types Of Inheritance in C++

The inheritance can be classified on the basis of the relationship between the derived class and the base class. In C++, we have 5 types of inheritances:

  1. Single inheritance
  2. Multilevel inheritance
  3. Multiple inheritance
  4. Hierarchical inheritance
  5. Hybrid inheritance

1. Single Inheritance

In single inheritance, a class is allowed to inherit from only one class. i.e. one base class is inherited by one derived class only.

Syntax

class subclass_name : access_mode base_class
{
// body of subclass
};

Example:

single-inheritance-in-cpp

Single Inheritance

class A
{
... .. ...
};
class B: public A
{
... .. ...
};

Implementation:

CPP
// C++ program to demonstrate how to implement the Single
// inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
    Vehicle() { cout << "This is a Vehicle\n"; }
};

// sub class derived from a single base classes
class Car : public Vehicle {
public:
    Car() { cout << "This Vehicle is Car\n"; }
};

// main function
int main()
{
    // Creating object of sub class will
    // invoke the constructor of base classes
    Car obj;
    return 0;
}

Output
This is a Vehicle
This Vehicle is Car

2. Multiple Inheritance

Multiple Inheritance is a feature of C++ where a class can inherit from more than one class. i.e one subclass is inherited from more than one base class.

Syntax

class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
// body of subclass
};

Here, the number of base classes will be separated by a comma (‘, ‘) and the access mode for every base class must be specified and can be different.

Example:

multiple-inheritance-in-cpp

Multiple Inheritance in C++

class B
{
... .. ...
};
class C
{
... .. ...
};
class A: public B, public C
{
... ... ...
};

Implementation:

CPP
// C++ program to illustrate the multiple inheritance
#include <iostream>
using namespace std;

// first base class
class Vehicle {
public:
    Vehicle() { cout << "This is a Vehicle\n"; }
};

// second base class
class FourWheeler {
public:
    FourWheeler() { cout << "This is a 4 Wheeler\n"; }
};

// sub class derived from two base classes
class Car : public Vehicle, public FourWheeler {
  public:
    Car() { cout << "This 4 Wheeler Vehical is a Car\n"; }
};

// main function
int main()
{
    // Creating object of sub class will
    // invoke the constructor of base classes.
    Car obj;
    return 0;
}

Output
This is a Vehicle
This is a 4 Wheeler
This 4 Wheeler Vehical is a Car

MUST READ – Multiple Inheritance in C++

3. Multilevel Inheritance

In this type of inheritance, a derived class is created from another derived class and that derived class can be derived from a base class or any other derived class. There can be any number of levels.

Syntax

class derived_class1: access_specifier base_class
{
... .. ...
}
class derived_class2: access_specifier derived_class1
{
... .. ...
}
.....

Example:

multilevel-inheritance-in-cpp

Multilevel Inheritance in C++

class C
{
... .. ...
};
class B : public C
{
... .. ...
};
class A: public B
{
... ... ...
};

Implementation

CPP
// C++ program to implement Multilevel Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
    Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub_class derived from class vehicle
class fourWheeler : public Vehicle {
public:
    fourWheeler() { cout << "4 Wheeler Vehicles\n"; }
};

// sub class derived from the derived base class fourWheeler
class Car : public fourWheeler {
public:
    Car() { cout << "This 4 Wheeler Vehical is a Car\n"; }
};

// main function
int main()
{
    // Creating object of sub class will
    // invoke the constructor of base classes.
    Car obj;
    return 0;
}

Output
This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehical is a Car

MUST READ – Multilevel Inheritance in C++

4. Hierarchical Inheritance

In this type of inheritance, more than one subclass is inherited from a single base class. i.e. more than one derived class is created from a single base class.

Syntax

class derived_class1: access_specifier base_class
{
... .. ...
}
class derived_class2: access_specifier base_class
{
... .. ...
}

Example:

hierarchical-inheritance-in-cpp

Hierarchical Inheritance in C++

class A 
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}

Implementation

CPP
// C++ program to implement Hierarchical Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
    Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub class
class Car : public Vehicle {
public:
    Car() { cout << "This Vehicle is Car\n"; }
};

// second sub class
class Bus : public Vehicle {
public:
    Bus() { cout << "This Vehicle is Bus\n"; }
};

// main function
int main()
{
    // Creating object of sub class will
    // invoke the constructor of base class.
    Car obj1;
    Bus obj2;
    return 0;
}

Output
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus

MUST READ – C++ Hierarchical Inheritance

5. Hybrid Inheritance

Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance will create hybrid inheritance in C++

There is no particular syntax of hybrid inheritance. We can just combine two of the above inheritance types.

Example:

Below image shows one of the combinations of hierarchical and multiple inheritances:

Hybrid-inheritance-in-cpp

Hybrid Inheritance in C++

class F
{
... .. ...
}
class G
{
... .. ...
}
class B : public F
{
... .. ...
}
class E : public F, public G
{
... .. ...
}
class A : public B {
... .. ...
}
class C : public B {
... .. ...
}

Implementation:

CPP
// C++ program to illustrate the implementation of Hybrid Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
    Vehicle() { cout << "This is a Vehicle\n"; }
};

// base class
class Fare {
public:
    Fare() { cout << "Fare of Vehicle\n"; }
};

// first sub class
class Car : public Vehicle {
  public:
  Car() { cout << "This Vehical is a Car\n"; }
};

// second sub class
class Bus : public Vehicle, public Fare {
  public:
  Bus() { cout << "This Vehicle is a Bus with Fare\n"; }
};

// main function
int main()
{
    // Creating object of sub class will
    // invoke the constructor of base class.
    Bus obj2;
    return 0;
}

Output
This is a Vehicle
Fare of Vehicle
This Vehicle is a Bus with Fare

A Special Case of Hybrid Inheritance: Multipath Inheritance

In multipath inheritance, a class is derived from two base classes and these two base classes in turn are derived from one common base class. An ambiguity can arise in this type of inheritance in the most derived class. This problem is also called diamond problem due to the diamond shape formed in the UML inheritance diagram.

MUST READ – Hybrid Inheritance in C++

Constructors and Destructors in Inheritance

Constructors and Destructors are generally defined by the programmer and if not, the compiler automatically creates them so they are present in every class in C++. Now, the question arises what happens to the constructor and destructor when a class is inherited by another class.

In C++ inheritance, the constructors and destructors are not inherited by the derived class, but we can call the constructor of the base class in derived class.

  • The constructors will be called by the complier in the order in which they are inherited. It means that base class constructors will be called first, then derived class constructors will be called.
  • The destructors will be called in reverse order in which the compiler is declared.
  • We can also call the constructors and destructors manually in the derived class.

Example

C++
// C++ program to show the order of constructor call
// in single inheritance

#include <iostream>
using namespace std;

// base class
class Parent {
public:
    // base class constructor
    Parent() { cout << "Inside base class" << endl; }
};

// sub class
class Child : public Parent {
public:
    // sub class constructor
    Child() { cout << "Inside sub class" << endl; }
};

// main function
int main()
{

    // creating object of sub class
    Child obj;

    return 0;
}

Output
Inside base class
Inside sub class

MUST READ – Order of Constructor/ Destructor Call in C++

Polymorphism in Inheritance

In Inheritance, we can redefine the base class member function in the derived class. This type of inheritance is called Function Overriding. Generally, in other programming languages, function overriding is runtime polymorphism but in C++, we can do it at both runtime and complile time. For runtime polymorphism, we have to use the virtual functions.

Example

C++
// C++ program to demonstrate compile time function
// overriding

#include <iostream>
using namespace std;

class Parent {
public:
    void GeeksforGeeks_Print()
    {
        cout << "Base Function" << endl;
    }
};

class Child : public Parent {
public:
    void GeeksforGeeks_Print()
    {
        cout << "Derived Function" << endl;
    }
};

int main()
{
    Child Child_Derived;
    Child_Derived.GeeksforGeeks_Print();
    return 0;
}

Output
Derived Function

MUST READ – Function Overriding in C++

Frequently Asked Questions on C++ Inheritance

Can the derived class inherit static members?

Yes, a derived class can inherit static members (such as static variables or static functions) from the base class. However, these members are shared across all instances of the derived class.

What are a base class and a derived class?

A base class (also called a superclass) is an existing class from which other classes inherit properties and methods. A derived class (also called a subclass) is a new class created by inheriting from the base class.

What are the rules for calling a base class constructor in a derived class?

The base class constructor can be explicitly called in the initializer list of the derived class constructor. If not specified, the default constructor of the base class is called automatically. If the base class does not have a default constructor, the derived class must explicitly call one of the base class’s constructors.




Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg