C++ Inheritance


What is Inheritance in C++?

Inheritance is one of the most important features of Object-Oriented Programming (OOP) in C++. It allows a class to inherit properties and behaviors (data members and member functions) from another class. The main purpose of inheritance is to promote code reusability and establish a relationship between classes.

The class that is inherited from is called the base class (or parent class), and the class that inherits from it is called the derived class (or child class).

For example, if you have a Person class with general details like name and age, and a Student class that adds specific details like roll number and marks, the Student class can inherit from Person to reuse its attributes.

Syntax of Inheritance

class BaseClass {
    // properties and methods
};

class DerivedClass : access_specifier BaseClass {
    // additional properties and methods
};

Here, access_specifier defines how the members of the base class are inherited. It can be:

  • public

  • protected

  • private

Example of Basic Inheritance

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

    void displayPerson() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
    }
};

class Student : public Person {
public:
    int rollNo;

    void displayStudent() {
        cout << "Roll Number: " << rollNo << endl;
    }
};

int main() {
    Student s1;
    s1.name = "Ananya";
    s1.age = 20;
    s1.rollNo = 101;
    s1.displayPerson();
    s1.displayStudent();
    return 0;
}

Explanation

  • The class Student inherits all the public members of Person.

  • It can directly access name and age because they are public members of the base class.

  • The Student class also adds its own member rollNo.

Types of Inheritance in C++

C++ supports several types of inheritance to suit different program designs.

1. Single Inheritance

A derived class inherits from a single base class.

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

2. Multiple Inheritance

A derived class inherits from more than one base class.

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

3. Multilevel Inheritance

A class is derived from another derived class.

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

4. Hierarchical Inheritance

Multiple classes are derived from a single base class.

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

5. Hybrid Inheritance

Combination of more than one type of inheritance, such as multiple and multilevel inheritance.

Access Specifiers in Inheritance

Access specifiers control how base class members are accessible in derived classes.

Base Class Member Public Inheritance Protected Inheritance Private Inheritance
Public Members Public Protected Private
Protected Members Protected Protected Private
Private Members Not Inherited Not Inherited Not Inherited

Example

#include <iostream>
using namespace std;

class Base {
protected:
    int x;
};

class Derived : public Base {
public:
    void setData(int a) {
        x = a;
    }

    void showData() {
        cout << "Value of x: " << x << endl;
    }
};

int main() {
    Derived d1;
    d1.setData(10);
    d1.showData();
    return 0;
}

Here, x is a protected member in the base class, so it can be accessed inside the derived class but not directly in main().

Constructor and Inheritance

Constructors of the base class are not inherited but are called automatically when an object of the derived class is created. The base class constructor executes first, followed by the derived class constructor.

#include <iostream>
using namespace std;

class Base {
public:
    Base() {
        cout << "Base constructor called" << endl;
    }
};

class Derived : public Base {
public:
    Derived() {
        cout << "Derived constructor called" << endl;
    }
};

int main() {
    Derived obj;
    return 0;
}

Output:

Base constructor called
Derived constructor called

Function Overriding in Inheritance

Function overriding allows the derived class to provide a specific implementation of a function that is already defined in the base class.

#include <iostream>
using namespace std;

class Animal {
public:
    void sound() {
        cout << "Animal makes a sound" << endl;
    }
};

class Dog : public Animal {
public:
    void sound() {
        cout << "Dog barks" << endl;
    }
};

int main() {
    Dog d;
    d.sound();
    return 0;
}

The function sound() in Dog overrides the one in Animal.

The "protected" Keyword in Inheritance

Protected members of a base class are accessible inside the derived class but not outside of it. This allows a class to expose limited functionality to its subclasses without making it completely public.

The super Concept (Base Class Reference)

C++ uses the scope resolution operator (::) to call a function from the base class that has been overridden in the derived class.

#include <iostream>
using namespace std;

class Parent {
public:
    void show() {
        cout << "Parent class function" << endl;
    }
};

class Child : public Parent {
public:
    void show() {
        cout << "Child class function" << endl;
    }

    void display() {
        Parent::show(); // Access base class method
    }
};

int main() {
    Child c;
    c.display();
    return 0;
}

Advantages of Inheritance

  1. Code Reusability: Avoids duplication by reusing existing class code.

  2. Extensibility: Easy to add or modify features without rewriting code.

  3. Maintainability: Simplifies debugging and future updates.

  4. Hierarchical Organization: Models real-world relationships naturally.

  5. Polymorphism Support: Enables runtime behavior changes in derived classes.

Summary of the Tutorial

Inheritance in C++ allows one class to acquire the properties and behaviors of another class. It simplifies programming by reusing existing code and promoting relationships between classes. Different types of inheritance (single, multiple, multilevel, hierarchical, and hybrid) give flexibility in program design. Understanding inheritance is crucial for mastering C++ OOP concepts, as it connects directly with encapsulation, polymorphism, and abstraction.


Practice Questions

  1. Write a C++ program to create a base class Person with data members name and age, and a derived class Student that adds rollNo and marks. Display all details.

  2. Create a base class Vehicle with a method displayType(). Derive classes Car and Bike from it and override the method to show their specific types.

  3. Write a C++ program that demonstrates multilevel inheritance with classes Animal, Mammal, and Dog.

  4. Create a class Shape with a function area(). Derive classes Circle and Rectangle and calculate area based on user input.

  5. Write a program to show how constructors are called in inheritance when an object of the derived class is created.

  6. Define two base classes Teacher and Researcher. Derive a class Professor that inherits from both and display all details (multiple inheritance).

  7. Write a program to demonstrate hierarchical inheritance using a base class Account and derived classes Savings and Current.

  8. Create a base class Parent with a function show(). Derive a class Child that overrides this function. Use scope resolution (Parent::show()) to call the base version.

  9. Write a program where a base class Employee has a protected member salary. A derived class Manager modifies and displays the salary.

  10. Implement a hybrid inheritance example combining both multiple and multilevel inheritance using your own class hierarchy.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top