Inheritance and Polymorphism in C++
1 Understanding Inheritance
Inheritance allows a class (derived class) to inherit properties and methods from another
class (base class). This promotes code reuse and establishes a hierarchical relationship
between classes.
For example, a Vehicle class can be a base class for a Car class:
class Vehicle {
public :
string brand ;
void start () {
cout << brand << " ␣ is ␣ starting . " << endl ;
}
};
class Car : public Vehicle {
public :
int doors ;
void display () {
cout << brand << " ␣ has ␣ " << doors << " ␣ doors . " << endl ;
}
};
2 Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common
base class. This is achieved through virtual functions in C++:
class Vehicle {
public :
virtual void start () {
cout << " Vehicle ␣ is ␣ starting . " << endl ;
}
};
class Car : public Vehicle {
public :
void start () override {
cout << " Car ␣ is ␣ starting ␣ with ␣ a ␣ roar ! " << endl ;
}
};
1
int main () {
Vehicle * v = new Car ();
v - > start (); // Output : Car is starting with a roar !
delete v ;
return 0;
}
3 Types of Inheritance
• Single Inheritance: One class inherits from one base class.
• Multiple Inheritance: A class inherits from multiple base classes.
• Multilevel Inheritance: A class is derived from a class that is itself derived.
4 Example: Shape Hierarchy
Consider a shape hierarchy with a base class Shape and derived class Circle:
class Shape {
public :
virtual double area () { return 0.0; }
};
class Circle : public Shape {
double radius ;
public :
Circle ( double r ) : radius ( r ) {}
double area () override {
return 3.14159 * radius * radius ;
}
};
int main () {
Shape * s = new Circle (5.0);
cout << " Area : ␣ " << s - > area () << endl ; // Output : Area : 78.53975
delete s ;
return 0;
}
5 Key Takeaways
• Inheritance enables code reuse and hierarchy.
• Polymorphism allows flexibility in method calls.
• Virtual functions are key to runtime polymorphism in C++.