Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

C++ Programming

Inheritance and Polymorphism

Mastering inheritance and polymorphism concepts and implementation.

On this page

Inheritance and Polymorphism

Inheritance and polymorphism are core OOP concepts that enable code reuse and flexible design. They're essential for building scalable, maintainable C++ applications.

What is Inheritance?

Inheritance allows a class (derived/child class) to inherit properties and behaviors from another class (base/parent class). This promotes code reuse and establishes an "is-a" relationship.

Key Benefits:

  • Code Reuse: Don't repeat code from base class
  • Hierarchical Organization: Model real-world relationships
  • Extensibility: Add new features without modifying base class
  • Polymorphism: Use derived classes through base class pointers

Inheritance Syntax

Basic Structure:

1class BaseClass {
2    // Base class members
3};
4 
5class DerivedClass : access-specifier BaseClass {
6    // Derived class members
7};

Access Specifiers:

  • public: Public and protected members remain accessible
  • protected: Public members become protected
  • private: Public and protected members become private

Most Common: Use public inheritance.

Simple Inheritance Example

1class Animal {
2protected:
3    string name;
4    
5public:
6    Animal(string n) : name(n) {}
7    
8    void eat() {
9        cout << name << " is eating" << endl;
10    }
11    
12    void sleep() {
13        cout << name << " is sleeping" << endl;
14    }
15};
16 
17class Dog : public Animal {
18public:
19    Dog(string n) : Animal(n) {}
20    
21    void bark() {
22        cout << name << " is barking" << endl;
23    }
24};
25 
26int main() {
27    Dog dog("Buddy");
28    dog.eat();    // Inherited from Animal
29    dog.sleep();  // Inherited from Animal
30    dog.bark();   // Dog's own method
31    return 0;
32}

Sample Output

is eating
 is sleeping
 is barking

Access Levels in Inheritance

Base ClassInheritance TypeDerived Class Access
publicpublicpublic
protectedpublicprotected
privatepublicNot accessible
publicprotectedprotected
protectedprotectedprotected
privateprotectedNot accessible

Constructor and Destructor in Inheritance

Order of Execution:

  1. Base class constructor
  2. Derived class constructor
  3. Derived class destructor
  4. Base class destructor

Example:

1class Base {
2public:
3    Base() { cout << "Base constructor" << endl; }
4    ~Base() { cout << "Base destructor" << endl; }
5};
6 
7class Derived : public Base {
8public:
9    Derived() { cout << "Derived constructor" << endl; }
10    ~Derived() { cout << "Derived destructor" << endl; }
11};

Sample Output

Base constructor
Base destructor
Derived constructor
Derived destructor

Types of Inheritance

1. Single Inheritance

One base class, one derived class:

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

2. Multiple Inheritance

Derived class inherits from multiple base classes:

1class A { };
2class B { };
3class C : public A, public B { };

Note: Can lead to ambiguity issues (diamond problem).

3. Multilevel Inheritance

Chain of inheritance:

1class A { };
2class B : public A { };
3class C : public B { };

4. Hierarchical Inheritance

Multiple derived classes from one base:

1class A { };
2class B : public A { };
3class C : public A { };

Function Overriding

Derived class redefines base class function:

1class Animal {
2public:
3    void makeSound() {
4        cout << "Animal makes a sound" << endl;
5    }
6};
7 
8class Dog : public Animal {
9public:
10    void makeSound() {  // Override
11        cout << "Dog barks" << endl;
12    }
13};

Sample Output

Animal makes a sound
Dog barks

Note: Without virtual functions, this is function hiding, not true polymorphism.

Virtual Functions

Enable runtime polymorphism (late binding):

1class Animal {
2public:
3    virtual void makeSound() {  // Virtual function
4        cout << "Animal makes a sound" << endl;
5    }
6};
7 
8class Dog : public Animal {
9public:
10    void makeSound() override {  // Override virtual function
11        cout << "Dog barks" << endl;
12    }
13};

Sample Output

Animal makes a sound
Dog barks

Key Points:

  • virtual keyword enables polymorphism
  • override keyword (C++11) ensures correct overriding
  • Function called based on object type, not pointer type

Polymorphism Example

1Animal* animal1 = new Dog("Buddy");
2animal1->makeSound();  // Calls Dog::makeSound() - polymorphism!

Pure Virtual Functions

Functions with no implementation in base class:

1class Animal {
2public:
3    virtual void makeSound() = 0;  // Pure virtual
4};

Effects:

  • Makes class abstract (cannot instantiate)
  • Derived classes MUST implement it
  • Creates interface contract

Abstract Classes

Classes with at least one pure virtual function:

1class Shape {
2public:
3    virtual double getArea() = 0;  // Pure virtual
4    virtual double getPerimeter() = 0;  // Pure virtual
5};
6 
7// Cannot do: Shape s;  // Error: abstract class

Virtual Destructors

Critical Rule: Always make base class destructor virtual!

1class Base {
2public:
3    virtual ~Base() {  // Virtual destructor
4        cout << "Base destructor" << endl;
5    }
6};
7 
8class Derived : public Base {
9public:
10    ~Derived() {
11        cout << "Derived destructor" << endl;
12    }
13};

Sample Output

Base destructor
Derived destructor

Why? Ensures proper cleanup when deleting through base pointer.

Virtual Function Table (vtable)

How polymorphism works internally:

  • Each class with virtual functions has a vtable
  • Contains pointers to virtual functions
  • Object stores pointer to vtable
  • Runtime lookup determines which function to call

Function Hiding vs Overriding

Function Hiding (without virtual):

1Base* ptr = new Derived();
2ptr->function();  // Calls Base::function()

Function Overriding (with virtual):

1Base* ptr = new Derived();
2ptr->function();  // Calls Derived::function()

Multiple Inheritance Issues

Diamond Problem

1class A { };
2class B : public A { };
3class C : public A { };
4class D : public B, public C { };  // Two copies of A!

Solution: Virtual Inheritance

1class A { };
2class B : virtual public A { };
3class C : virtual public A { };
4class D : public B, public C { };  // One copy of A

Best Practices

  1. ✅ Use public inheritance for "is-a" relationships
  2. ✅ Make destructors virtual in base classes
  3. ✅ Use override keyword (C++11) for clarity
  4. ✅ Prefer composition over inheritance when appropriate
  5. ✅ Use abstract classes to define interfaces
  6. ✅ Avoid deep inheritance hierarchies (keep it shallow)
  7. ✅ Use virtual inheritance to solve diamond problem
  8. ✅ Document inheritance relationships clearly

Common Mistakes

  • ❌ Forgetting virtual destructor in base class
  • ❌ Using inheritance for "has-a" relationships (use composition)
  • ❌ Deep inheritance hierarchies (hard to maintain)
  • ❌ Not understanding virtual function overhead
  • ❌ Diamond problem without virtual inheritance
  • ❌ Hiding instead of overriding (missing virtual)

Next Module

In Module 10, we'll learn about STL (Standard Template Library) - powerful containers, algorithms, and iterators that make C++ programming efficient!

Hands-on Examples

Basic Inheritance

#include <iostream>
#include <string>
using namespace std;

class Animal {
protected:
    string name;
    int age;
    
public:
    Animal(string n, int a) : name(n), age(a) {
        cout << "Animal constructor" << endl;
    }
    
    void eat() {
        cout << name << " is eating" << endl;
    }
    
    void sleep() {
        cout << name << " is sleeping" << endl;
    }
    
    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

class Dog : public Animal {
private:
    string breed;
    
public:
    Dog(string n, int a, string b) : Animal(n, a), breed(b) {
        cout << "Dog constructor" << endl;
    }
    
    void bark() {
        cout << name << " is barking" << endl;
    }
    
    void display() {
        Animal::display();  // Call base class method
        cout << "Breed: " << breed << endl;
    }
};

int main() {
    Dog dog("Buddy", 3, "Golden Retriever");
    
    dog.eat();     // Inherited from Animal
    dog.sleep();   // Inherited from Animal
    dog.bark();    // Dog's own method
    dog.display(); // Dog's overridden method
    
    return 0;
}

Inheritance allows Dog to inherit members from Animal. Protected members are accessible in derived class. Derived class can add new members and override base class methods. Base constructor called before derived constructor.

Sample Output

Animal constructor
Dog constructor
Buddy is eating
Buddy is sleeping
Buddy is barking
Name: Buddy, Age: 3
Breed: Golden Retriever