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 Class | Inheritance Type | Derived Class Access |
|---|---|---|
| public | public | public |
| protected | public | protected |
| private | public | Not accessible |
| public | protected | protected |
| protected | protected | protected |
| private | protected | Not accessible |
Constructor and Destructor in Inheritance
Order of Execution:
- Base class constructor
- Derived class constructor
- Derived class destructor
- 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:
virtualkeyword enables polymorphismoverridekeyword (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
- ✅ Use public inheritance for "is-a" relationships
- ✅ Make destructors virtual in base classes
- ✅ Use override keyword (C++11) for clarity
- ✅ Prefer composition over inheritance when appropriate
- ✅ Use abstract classes to define interfaces
- ✅ Avoid deep inheritance hierarchies (keep it shallow)
- ✅ Use virtual inheritance to solve diamond problem
- ✅ 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
Practice with Programs
Reinforce your learning with hands-on practice programs
Related Program Topics
Recommended Programs
Hello World
BeginnerWrite your first C++ program and see why each of its four lines matters: #include, using namespace std, main, cout, and return 0. Made for day-one students.
Display Your Name
BeginnerStore your name in a C++ string variable and print it with cout and endl. Covers #include <string>, chaining <<, and how a string differs from a char array.
User Input
BeginnerRead a name and an age from the keyboard with cin in C++. See why cin >> stops at the first space, when to use getline, and how a bad number breaks the stream.
Array Max & Min
BeginnerFind the largest and smallest values in a C++ array in one pass, starting from INT_MIN and INT_MAX. Traces 10 5 20 15 8 and shows why starting at 0 fails.
Array Average
BeginnerCompute the average of n numbers stored in a C++ array, adding them up as they are read. Covers double for the sum, setprecision(2), and the n = 0 trap.