[C++] OOPs - Inheritance
What is Inheritance in C++?
"Hey, suppose we have a general concept called 'Vehicle'. Now, can a Car be considered a type of Vehicle?"
"Yeah! A car is definitely a vehicle."
Exactly!
Similarly, a bike or a bus are also types of vehicles, right?
So we notice something important here — many specific things (like Car, Bike, Bus) share some common features from a general idea (Vehicle).
But they also have their own special features.
This sharing of common features, while keeping special features separate, is what we want to achieve in programming too.
Now, how do we do this in C++?
Before answering, let’s build the idea slowly.
Real-Life Analogy: Let's Design Vehicles
Suppose we want to create a program where:
- Vehicle has some basic properties like speed and weight.
- Car adds its own property like number of doors.
- Bike adds a helmet storage feature.
Now, would it be smart to repeat speed and weight in Car and Bike separately?
"No! That feels like unnecessary duplication."
Exactly!
We want to reuse the common features (like speed and weight) and only add the special features in Car and Bike.
In C++, we achieve this using a feature called Inheritance.
Building Intuition with Small Example First
Suppose we define a general Vehicle class:
#include <iostream>
using namespace std;
// Base class
class Vehicle {
public:
// Function to set speed
void setSpeed(int s) {
speed = s;
}
// Function to set weight
void setWeight(int w) {
weight = w;
}
protected:
int speed; // Speed of the vehicle
int weight; // Weight of the vehicle
};
What did we do here?
We created a Vehicle class with:
- Two protected variables: speed and weight.
- Two public functions to set these values.
Protected variables mean: They are accessible within Vehicle and classes that inherit from it, but not outside these classes.
Now let's create a Car
Now, suppose we want a Car that can set its number of doors too.
// Derived class
class Car : public Vehicle {
public:
// Function to set number of doors
void setDoors(int d) {
doors = d;
}
// Function to display car details
void display() {
cout << "Speed: " << speed << " km/h" << endl;
cout << "Weight: " << weight << " kg" << endl;
cout << "Doors: " << doors << endl;
}
private:
int doors; // Number of doors in the car
};
Let's understand this piece together
- Car inherits from Vehicle using public access.
- That means:
- setSpeed() and setWeight() functions remain public in Car.
- speed and weight are available inside Car (because they are protected in Vehicle).
- Car adds a new private data member doors.
- Car has a display() function to show all its details.
Time to test it in main()!
int main() {
// Create a Car object
Car myCar;
// Set speed, weight and doors
myCar.setSpeed(120);
myCar.setWeight(1500);
myCar.setDoors(4);
// Display car details
myCar.display();
return 0;
}
What happens here?
- We create an object myCar.
- We use the inherited functions setSpeed() and setWeight().
- We use setDoors() to set the special Car-specific property.
- Finally, display() prints everything nicely.
OUTPUT:
Speed: 120 km/h
Weight: 1500 kg
Doors: 4
Why is this awesome?
Because we reused the code from Vehicle without writing it again in Car.
Plus, Car can add its own personality (more doors, sunroof, sports mode… you name it).
What is actually happening?
All this idea —
Sharing features from a general class to a specialized class — is called INHERITANCE.
- Vehicle is called the Base class (or Parent class).
- Car is called the Derived class (or Child class).
Types of Inheritance Based on Access Specifier
I ask you:
"When Car inherits from Vehicle, how should the members behave?"
"Should they remain public? Or become private?"
Good question!
In C++, it depends on the access specifier used:
Inheritance Type |
Base class public members become |
Base class protected members become |
public |
public |
protected |
protected |
protected |
protected |
private |
private |
private |
Most of the time, we use public inheritance because it preserves the relationship properly.
Protected Members - Why Useful?
If the base class makes variables protected instead of private, the derived class can use them.
For example:
- In Vehicle, speed is protected.
- In Car, we could directly access speed.
But if it was private?
- Car could NOT access it directly!
Another Example: Let's Add a Bike
Let's have more fun. Suppose we create a Bike class too.
// Derived class
class Bike : public Vehicle {
public:
// Function to set helmet storage availability
void setHelmetStorage(bool hs) {
helmetStorage = hs;
}
// Function to display bike details
void display() {
cout << "Speed: " << speed << " km/h" << endl;
cout << "Weight: " << weight << " kg" << endl;
cout << "Helmet Storage: " << (helmetStorage ? "Yes" : "No") << endl;
}
private:
bool helmetStorage; // True if helmet storage is available
};
Using Bike in Main
int main() {
// Create a Bike object
Bike myBike;
// Set speed, weight, and helmet storage
myBike.setSpeed(80);
myBike.setWeight(200);
myBike.setHelmetStorage(true);
// Display bike details
myBike.display();
return 0;
}
OUTPUT
Speed: 80 km/h
Weight: 200 kg
Helmet Storage: Yes
Multiple Inheritance: What if a class inherits from two parents?
Let’s dream a little more:
Suppose we want a FlyingCar —
- It should have properties of Car (like doors)
- It should have properties of a Plane (like wingspan).
How to inherit from both Car and Plane?
Answer: We use Multiple Inheritance.
Simple Syntax for Multiple Inheritance
class FlyingCar : public Car, public Plane {
// Class contents
};
Both parents are separated by a comma.
The derived class FlyingCar now inherits members from both Car and Plane.
Interview Question Time
Now let’s quickly discuss some famous interview questions!
Interview Question |
Quick Tip for Answer |
What is Inheritance? |
Mechanism to reuse code from one class to another. |
What are Base and Derived Classes? |
Base provides features; Derived inherits and can add more. |
How does access specifier affect inheritance? |
Public keeps public; private hides it. |
What gets inherited? |
All non-private data/functions (except constructors,
destructors, operators, friends). |
What is Multiple Inheritance? |
A class inherits from more than one base class. |
Why protected access is important? |
Allows derived classes to access, but hides from outside. |
Does a derived class inherit constructors? |
No. It must define its own constructors. |
Explain IS-A relationship with examples. |
Car IS-A Vehicle, Dog IS-A Animal, etc. |
Quick Summary of the Discussion
- Inheritance allows code reusability.
- It implements an IS-A relationship between classes.
- We define a Base (general) class and a Derived (specific) class.
- There are three types of inheritance based on access (public, protected, private).
- Multiple inheritance allows a class to have more than one parent.
- Protected members are very useful in Inheritance.
Final Fun Example: Inheriting Animal -> Dog
#include <iostream>
using namespace std;
// Base class
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};
// Derived class
class Dog : public Animal {
public:
void bark() {
cout << "The dog barks!" << endl;
}
};
int main() {
// Create Dog object
Dog myDog;
// Call functions
myDog.eat(); // inherited from Animal
myDog.bark(); // defined in Dog
return 0;
OUTPUT:
This animal eats food.
The dog barks!
And that's the beauty of Inheritance!
We work less, reuse more, and create beautiful programs just like real-world hierarchies.