Explain it simply
Explain it simply
On a website every user has a name and can log in. An admin is also a user, with a name and a login, but with extra powers such as deleting posts. Instead of writing an Admin class from scratch, inheritance lets you say "an Admin is a kind of User, plus these extras".
The class that gives is the base class (or parent), and the class that inherits is the derived class (or child). Once you write class Admin : public User, every Admin object contains a User part, and User's public members can be used directly through an Admin.
Problem → Why → Solution
The problem: copy-pasted classes drift apart
Suppose Admin was copy-pasted from User instead of inheriting. Later someone fixes User::login() to refuse an empty name but forgets the copy inside Admin. On top of that, functions that accept a User refuse an Admin entirely, because to the compiler they are two unrelated types.
#include <iostream>
#include <string>
class User {
public:
std::string name;
void login() {
if (name.empty()) return; // bug fix added here...
std::cout << name << " logged in.\n";
}
};
class Admin { // copy-pasted from User
public:
std::string name;
void login() { std::cout << name << " logged in.\n"; } // ...not here
void deletePost() { std::cout << name << " deleted a post.\n"; }
};
void welcome(User& u) { u.login(); } // welcome(admin) does not compileWhy doesn't copy-paste scale?
With two copies, every fix must be made twice, and missing one makes their behavior drift. Worse, the compiler does not know that an Admin is a kind of User, so code that handles users must be written again for admins. Inheritance keeps the shared code once in the base class and puts the is-a relationship into the type system.
Core concept: a derived object contains a base part
When you write class Admin : public User { ... };, picture an Admin object in memory as a User subobject plus the members Admin adds. admin.name is the name inside the User part, and when you call admin.login(), this inside login() points at admin's User part. Member functions of the derived class can use the base's public and protected members by name, but not the base's private members, even though those are physically inside the object.
Memory layout of an Admin object
--------------------------------
Admin object
+---------------------------+
| User part | <- members declared in User
| std::string name | (login() works on this part)
+---------------------------+
| Admin part | <- members Admin adds
| (deletePost uses name) |
+---------------------------+The public keyword matters. With public inheritance, the base's public members stay public in the derived class, and an Admin can be passed anywhere a User is expected, as a User& or User*. For a class, the default base access is private, so leaving public out of class Admin : User hides User's members from everyone outside Admin (a struct defaults to public). Public inheritance is the kind this lesson is about.
Building a derived object constructs the base part first, then the derived class's members, then runs the body of the derived constructor. If the base has no default constructor, call one from the derived initializer list, as in Admin(std::string n) : User(n) {}. Destruction runs in reverse: the derived destructor first and the base destructor last.
Do not inherit just to reuse code. Inherit only when "Derived is a kind of Base" (is-a) is genuinely true. An Admin is a User and a SavingsAccount is an Account, but a Car is not an Engine: a car has an engine (has-a), so Engine belongs inside Car as a member.
- Base constructor runs
- Derived members are initialized
- Derived constructor body runs
- Destruction runs in reverse
A derived object is built on top of its base, so the foundation goes up first and the top floor comes down first.
General pattern
class Base {
public:
explicit Base(Type v) : value_(v) {}
Type value() const { return value_; } // inherited by every Derived
private:
Type value_; // Derived goes through value()
};
class Derived : public Base { // Derived is-a Base
public:
Derived(Type v, Extra e) : Base(v), extra(e) {} // Base is built first
Extra extra; // added on top of Base
};: public Base declares public inheritance. The derived constructor's initializer list starts with Base(v), which builds the base part. The base keeps its data private, and the derived class reaches it through public or protected member functions.
Example: an Admin derived from User
In this example User provides name and login(), and Admin adds deletePost(). main() uses both the base members and the derived member through a single admin object. Each message ends with endl, so they print on separate lines.
#include <iostream>
#include <string>
using namespace std;
class User {
public:
string name;
void login() {
cout << name << " logged in." << endl;
}
};
class Admin : public User {
public:
void deletePost() {
cout << name << " deleted a post." << endl;
}
};
int main() {
Admin admin;
admin.name = "Thuta Admin";
admin.login();
admin.deletePost();
return 0;
}Code breakdown
- Line 14
class Admin : public User {Admin derives publicly from User. User's public members stay public in Admin, and an Admin can be passed wherever a User& is expected.
- Line 16
void deletePost() {A new member only Admin has. A plain User object has no deletePost(), so user.deletePost() is a compile error.
- Line 17
cout << name << " deleted a post." << endl;name is declared in User, but it is public, so the derived class's member function can use it directly by name.
- Line 23
admin.name = "Thuta Admin";Sets the name in the User part of the admin object. Admin never declares name itself; it has one through inheritance.
- Lines 24-25
admin.login();Calls the inherited login(), printing "Thuta Admin logged in."; the next line calls deletePost(), printing "Thuta Admin deleted a post.".
Thuta Admin logged in.
Thuta Admin deleted a post.Calling the base constructor, and construction order
In real classes User usually keeps name private and takes it through a constructor. User then has no default constructor, so Admin's constructor must build the base part itself with User(std::move(name)). The constructors and destructors print messages, so you can watch the order.
#include <iostream>
#include <string>
#include <utility>
class User {
public:
explicit User(std::string name) : name_(std::move(name)) {
std::cout << "User(" << name_ << ") constructed\n";
}
~User() { std::cout << "User destroyed\n"; }
const std::string& name() const { return name_; }
private:
std::string name_;
};
class Admin : public User {
public:
Admin(std::string name, int level) : User(std::move(name)), level_(level) {
std::cout << "Admin level " << level_ << " constructed\n";
}
~Admin() { std::cout << "Admin destroyed\n"; }
private:
int level_;
};
int main() {
Admin admin("Thuta", 3);
std::cout << admin.name() << " is working\n";
}The output is "User(Thuta) constructed", "Admin level 3 constructed", "Thuta is working", "Admin destroyed" and "User destroyed". When main() ends, admin leaves scope; notice the Admin destructor runs first and the User destructor last. When a derived class needs no constructor logic of its own, writing using User::User; inside it inherits the base constructors instead.
Inheritance or composition?
Composition means putting an object inside another class as a member. If Car has a member Engine engine_;, the car uses the engine internally and shows only its own interface, such as start() and drive(). Writing class Car : public Engine instead drags every public Engine function, setRpm() for example, into Car's interface, and lets a Car be passed wherever an Engine& is expected, which makes no sense.
| Question | If the answer is yes | Example |
|---|---|---|
| Is X a kind of Y? | Public inheritance | Admin is a User |
| Does X have a Y? | Composition (a member) | Car has an Engine |
| Do you only want Y's code? | Prefer composition | Stack uses a std::vector |
In real projects
Where this shows up in real projects
In the standard library, std::ifstream derives from std::istream. That is why one function taking a std::istream& can read from std::cin, from a file, or from a std::istringstream in a test, without changing a line. Exception classes form a hierarchy too, with std::runtime_error derived from std::exception, as lesson 24 shows in detail.
GUI frameworks use inheritance as well; in Qt, for example, QPushButton derives from QAbstractButton, which derives from QWidget, so every widget gets basic behavior such as a size, a position and show() from QWidget. Modern codebases still keep hierarchies shallow, two or three levels, and solve the rest with composition, because the deeper a hierarchy gets, the more classes break when one base class changes.
Common mistakes
Common mistakes
1. Forgetting public and getting private inheritance
class Admin : User { ... }; is private inheritance because that is the default for a class. admin.login() fails with "'void User::login()' is inaccessible within this context", and passing admin to a function taking a User& fails with "'User' is an inaccessible base of 'Admin'". Always write class Admin : public User.
2. A same-named function hiding the base overloads
If Logger has log(int code) and FileLogger : public Logger adds log(const std::string& text), the derived log hides every base log. fileLogger.log(404) then fails with "cannot convert 'int' to 'const std::string&'". Add using Logger::log; inside FileLogger to bring the base versions back into view.
3. Modelling has-a with inheritance
class Car : public Engine leaks the whole Engine interface to users of Car and lets a Car be passed off as an Engine. Read "X is a Y" aloud; if it sounds wrong, use a member (composition) instead.
4. Inheriting from a standard container
With class Stack : public std::vector<int>, users can call insert() and change elements in the middle, breaking the stack rules. std::vector also has no virtual destructor, so deleting a Stack through a std::vector<int>* is undefined behavior. Keep the vector as a private member.
Best practices
Best practices
- Use public inheritance only for a genuine is-a relationship and prefer composition otherwise.
- Keep base class data private and give derived classes what they need through member functions.
- Write the base constructor first in the derived initializer list, matching the order in which it really runs.
- If derived objects will be deleted through a base pointer, the base needs a virtual destructor, which the next lesson covers.
Mini challenge
Mini challenge: Employee and Manager
Write an Employee base class and a Manager class derived from it, then pass a Manager to a function that expects an Employee.
- Employee has private name_ and salary_, a constructor, name() const, salary() const and describe() const
- Manager : public Employee adds reports_ (the number of direct reports) and calls the Employee constructor from its initializer list
- bonus() const = 10% of salary + 500 per direct report
- Pass both an Employee and a Manager to a payslip(const Employee&) function
#include <iostream>
#include <string>
#include <utility>
class Employee {
public:
// TODO: constructor taking a name and a salary
// TODO: name() const, salary() const
// TODO: describe() const prints "<name> earns <salary>"
private:
// TODO: name_ and salary_
};
class Manager /* TODO: inherit publicly from Employee */ {
public:
// TODO: constructor (name, salary, reports) that builds the Employee part
// TODO: reports() const and bonus() const
private:
// TODO: reports_
};
void payslip(const Employee& e) {
// TODO: print "payslip: <name> <salary>"
}
int main() {
// TODO: Employee "Aye Aye" 3000, Manager "Ko Ko" 4500 with 3 reports
// TODO: describe both, print the manager's bonus, then payslip both
}Expected: The program prints: Aye Aye earns 3000 Ko Ko earns 4500 Ko Ko manages 3 people, bonus 1950 payslip: Aye Aye 3000 payslip: Ko Ko 4500
Show hint
Manager's constructor starts with : Employee(std::move(name), salary), reports_(reports). bonus() inside Manager cannot touch salary_ directly because it is private to Employee; call the public salary() instead. With integer arithmetic, salary() / 10 is 10%.
Show solution
#include <iostream>
#include <string>
#include <utility>
class Employee {
public:
Employee(std::string name, int salary)
: name_(std::move(name)), salary_(salary) {}
const std::string& name() const { return name_; }
int salary() const { return salary_; }
void describe() const { std::cout << name_ << " earns " << salary_ << '\n'; }
private:
std::string name_;
int salary_;
};
class Manager : public Employee {
public:
Manager(std::string name, int salary, int reports)
: Employee(std::move(name), salary), reports_(reports) {}
int reports() const { return reports_; }
int bonus() const { return salary() / 10 + reports_ * 500; }
private:
int reports_;
};
void payslip(const Employee& e) {
std::cout << "payslip: " << e.name() << " " << e.salary() << '\n';
}
int main() {
Employee aye("Aye Aye", 3000);
Manager ko("Ko Ko", 4500, 3);
aye.describe();
ko.describe(); // inherited from Employee
std::cout << ko.name() << " manages " << ko.reports()
<< " people, bonus " << ko.bonus() << '\n';
payslip(aye);
payslip(ko); // a Manager is an Employee
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- class Derived : public Base puts a base part inside every derived object and inherits the base's public members.
- A class inherits privately by default, so always write public.
- The base is built first and destroyed last; call the base constructor from the derived initializer list.
- Use inheritance for is-a, and composition for has-a or plain code reuse.
The Current ISO C++ Standard (C++23) — Standard C++ Foundation