What is Inheritance in C++ with Examples

What is Inheritance in C++?

Inheritance is the mechanism that permits new classes to be created out from the existing classes by extending and refining its capabilities.

In simple words, Inheritance is the ability to create a new class by making use of the existing class. It helps in reducing the development time.

It allows new classes to acquire the properties of an existing class. It helps in reusing the code and the programmer need not to write the same code again and again for different classes.

They just need to make use of inheritance property. Existing classes are called base classes or parent classes or super classes while the new classes are called derived classes or child classes or subclasses.

Inheritance defines an "is-a" relationship among classes.

Example: From a class mammal, a number of classes can be derived such as humans, cats, dogs, cows, buffalo, etc. All have the distinct characteristics of a mammal.

In addition, each has its own particular characteristics. It can be said that buffalo is-a mammal. Here's a basic example to illustrate inheritance in C++:

#include <iostream>
using namespace std;

// Base class
class Shape {
public:
    // Member function to calculate area
    virtual float area() const = 0; // Pure virtual function
};

// Derived class Rectangle inheriting from Shape
class Rectangle : public Shape {
private:
    float length;
    float width;

public:
    // Constructor
    Rectangle(float l, float w) : length(l), width(w) {}

    // Overriding area() method
    float area() const override {
        return length * width;
    }
};

// Derived class Circle inheriting from Shape
class Circle : public Shape {
private:
    float radius;

public:
    // Constructor
    Circle(float r) : radius(r) {}

    // Overriding area() method
    float area() const override {
        return 3.14f * radius * radius;
    }
};

int main() {
    Rectangle rect(5, 3);
    Circle circle(2.5);

    cout << "Area of rectangle: " << rect.area() << endl;
    cout << "Area of circle: " << circle.area() << endl;

    return 0;
}

In this example:

Shape is the base class with a pure virtual function area(). Rectangle and Circle are derived classes inheriting from Shape. Both Rectangle and Circle override the area() method to provide their own implementation. The main() function demonstrates how objects of derived classes can be instantiated and used.


Types of Inheritance

1. Single Inheritance

2. Multiple Inheritance

3. Multilevel Inheritance

4. Hierarchical Inheritance

5. Hybrid Inheritance


Single Inheritance

When a subclass is derived from a single-parent class is called single inheritance. Here's an example to illustrate single inheritance:

#include <iostream>
using namespace std;

// Base class
class Animal {
public:
    void eat() {
        cout << "Animal is eating." << endl;
    }

    void sleep() {
        cout << "Animal is sleeping." << endl;
    }
};

// Derived class
class Dog : public Animal {
public:
    void bark() {
        cout << "Dog is barking." << endl;
    }
};

int main() {
    Dog myDog;
    myDog.eat();    // Accessing base class method
    myDog.sleep();  // Accessing base class method
    myDog.bark();   // Accessing derived class method

    return 0;
}

In this example:

Animal is the base class with eat() and sleep() methods. Dog is the derived class that inherits from Animal. The Dog class has an additional method bark(). Inside the main() function, an object of the Dog class is created and methods from both the base class (Animal) and the derived class (Dog) are accessed using that object.


Multiple Inheritance

When a subclass is derived from more than one base class is called multiple inheritance. The relation of one child with two parents is shown in multiple inheritance.

#include <iostream>
using namespace std;

// Base class 1
class Shape {
public:
    virtual void draw() {
        cout << "Drawing shape..." << endl;
    }
};

// Base class 2
class Color {
public:
    virtual void fill() {
        cout << "Filling color..." << endl;
    }
};

// Derived class inheriting from both Shape and Color
class Rectangle : public Shape, public Color {
public:
    void draw() override {
        cout << "Drawing rectangle..." << endl;
    }

    void fill() override {
        cout << "Filling color for rectangle..." << endl;
    }
};

int main() {
    Rectangle rect;
    rect.draw();  // Accessing draw() method from Shape
    rect.fill();  // Accessing fill() method from Color

    return 0;
}

In this example:

Shape and Color are two base classes. Rectangle is the derived class that inherits from both Shape and Color. Both Shape and Color have their own methods, draw() and fill() respectively. The Rectangle class overrides both draw() and fill() methods to provide its own implementations. Inside the main() function, an object of the Rectangle class is created, and methods from both base classes (Shape and Color) are accessed using that object.


Multi-level Inheritance

When a subclass is derived from a superclass and superclass is derived from another superclass and so on is called multi-level inheritance.

It shows the relation of Grand Parent to Parent and the relation of Parent to Child. Basically, the relation of Grandparents to parent to child is shown in multi-level inheritance.

#include <iostream>
using namespace std;

// Base class
class Animal {
public:
    void eat() {
        cout << "Animal is eating." << endl;
    }

    void sleep() {
        cout << "Animal is sleeping." << endl;
    }
};

// Derived class 1
class Dog : public Animal {
public:
    void bark() {
        cout << "Dog is barking." << endl;
    }
};

// Derived class 2
class Bulldog : public Dog {
public:
    void guard() {
        cout << "Bulldog is guarding." << endl;
    }
};

int main() {
    Bulldog myBulldog;
    myBulldog.eat();    // Accessing method from Animal
    myBulldog.sleep();  // Accessing method from Animal
    myBulldog.bark();   // Accessing method from Dog
    myBulldog.guard();  // Accessing method from Bulldog

    return 0;
}

In this example:

Animal is the base class with eat() and sleep() methods. Dog is the derived class that inherits from Animal and adds a method bark(). Bulldog is further derived from Dog and adds a method guard(). Each derived class inherits all the properties and behaviors of its immediate parent class. Inside the main() function, an object of the Bulldog class is created, and methods from all three classes (Animal, Dog, and Bulldog) are accessed using that object.


Hierarchical Inheritance

The tree structure like inheritance is called hierarchical inheritance. The relation of multiple children with one parent is shown in hierarchical inheritance.

#include <iostream>
using namespace std;

// Base class
class Shape {
public:
    virtual void draw() {
        cout << "Drawing shape..." << endl;
    }
};

// Derived class 1
class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing circle..." << endl;
    }
};

// Derived class 2
class Rectangle : public Shape {
public:
    void draw() override {
        cout << "Drawing rectangle..." << endl;
    }
};

int main() {
    Circle circle;
    Rectangle rectangle;

    circle.draw();     // Accessing draw() method from Circle
    rectangle.draw();  // Accessing draw() method from Rectangle

    return 0;
}

In this example:

Shape is the base class with a draw() method. Both Circle and Rectangle are derived classes that inherit from Shape. Each derived class overrides the draw() method to provide its own implementation specific to the shape it represents. Inside the main() function, objects of both the Circle and Rectangle classes are created, and their respective draw() methods are called. Despite having different implementations of the draw() method, both Circle and Rectangle share the common interface provided by the Shape base class.


Hybrid Inheritance

Hybrid inheritance in C++ is a combination of different types of inheritance, such as single, multiple, multilevel, or hierarchical inheritance. It allows a class to inherit properties and behaviors from multiple base classes through various inheritance paths. The combination of multiple and multi-level inheritance is called hybrid inheritance.

#include <iostream>
using namespace std;

// Base class 1
class Animal {
public:
    void eat() {
        cout << "Animal is eating." << endl;
    }

    void sleep() {
        cout << "Animal is sleeping." << endl;
    }
};

// Base class 2
class Pet {
public:
    void play() {
        cout << "Pet is playing." << endl;
    }
};

// Derived class 1 inheriting from Animal
class Dog : public Animal {
public:
    void bark() {
        cout << "Dog is barking." << endl;
    }
};

// Derived class 2 inheriting from Animal and Pet
class Cat : public Animal, public Pet {
public:
    void meow() {
        cout << "Cat is meowing." << endl;
    }
};

int main() {
    Dog myDog;
    myDog.eat();    // Accessing method from Animal
    myDog.sleep();  // Accessing method from Animal
    myDog.bark();   // Accessing method from Dog

    Cat myCat;
    myCat.eat();    // Accessing method from Animal
    myCat.sleep();  // Accessing method from Animal
    myCat.play();   // Accessing method from Pet
    myCat.meow();   // Accessing method from Cat

    return 0;
}

In this example:

Animal and Pet are two base classes with their own methods. Dog is a derived class that inherits from Animal. Cat is a derived class that inherits from both Animal and Pet. Both Dog and Cat classes add their own specific methods (bark() and meow() respectively). Inside the main() function, objects of both Dog and Cat classes are created, and methods from all relevant base and derived classes are accessed using these objects.

Previous
Next Post »