Inheritance in C++ means one class takes on the members of another class. The class that receives them is the derived class, sometimes called the child class. The class it gets them from is the base class, sometimes called the parent class. The derived class can use what the base class shares with it, and it can add things of its own.
The short answer
Think of inheritance as building on something that already exists. The base class holds the shared behavior. The derived class reuses that behavior and adds what makes it different. Writing the shared code once, in the base class, means you don’t repeat it in every class that needs it.
A comparison from everyday life
A car is a vehicle. Every car starts, stops and carries people, and those are things all vehicles do. A car also has features that not every vehicle has, such as a horn. In C++, you could write the shared behavior once in a Vehicle class, then write a Car class that inherits from Vehicle and adds its own behavior.
A small C++ example
#include <iostream>
class Vehicle {
public:
void start() const {
std::cout << "Engine started\n";
}
};
class Car : public Vehicle {
public:
void honk() const {
std::cout << "Beep beep\n";
}
};
int main() {
Car car;
car.start(); // inherited from Vehicle
car.honk(); // defined in Car
return 0;
}
Output:
Engine started
Beep beep
The Car class doesn’t have a start function written into it. It uses the one from Vehicle, because Car inherits from Vehicle. The : public Vehicle part is what sets up that relationship.
What a derived class can use
A derived class sees the base class’s members according to their access level:
- Public members can be used by the derived class and by code outside both classes.
- Protected members can be used by the derived class, but not by outside code.
- Private members belong to the base class. The derived class can’t use them directly.
Keeping data private is a core part of encapsulation in C++. The access rules have more detail than this list, and the full guide to inheritance in C++ explains how the access word after the colon changes them.
Why programmers use it
- Less repeated code. Shared code lives in one place.
- Related classes stay consistent. Every derived class starts from the same base behavior.
- Code can work with the base type. A function that takes a reference to a
Vehiclecan accept anyCar. This is the start of polymorphism in C++, where one function works with many kinds of objects.
Is it the right tool?
Try saying the sentence out loud: “A ___ is a ___.” A car is a vehicle, so inheritance may fit. A car has an engine, so the car should hold an engine as a member variable instead. Use inheritance when the is-a sentence makes sense.
Where to go next
Once the basic idea feels clear, the full Inheritance in C++ guide covers the access table, constructor order, overriding with virtual functions and common mistakes. Learning the idea first makes that material easier to follow.