These are the notes for C++ episode 15. Episode 14 gave us a first look at class Savings : public Account. Here you will see why that idea matters: copy-pasting a class lets a bug fix reach one copy and miss the other. You will invent the base class (the shared part, written once) and the derived class (base + extras), learn the is-a test, call the parent's constructor from the child's initializer list, prove the construction and destruction order, give a child its own version of a function while reusing the parent's with Person::show(), compare public, protected and private inheritance, and build a chain of three classes. At the end you will meet the problem the next episode solves. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; the outputs and error messages are copied from those runs.
The problem: the copy-paste bug
We're building a school app. A Student has a name, an age and a roll number, plus canVote(): true if the age is 18 or more. A Teacher has a name, an age and a subject. That's almost the same class, so we do the obvious thing: copy Student, paste it, change one line.
Last week someone found a bug: canVote() said age > 18, so 18-year-olds couldn't vote. They fixed it in Student (age >= 18)... and forgot the copy in Teacher.
#include <iostream>
#include <string>
using namespace std;
class Student {
string name; int age; int roll;
public:
Student(string n, int a, int r) : name(n), age(a), roll(r) {}
bool canVote() const { return age >= 18; }
};
class Teacher {
string name; int age; string subject;
public:
Teacher(string n, int a, string s) : name(n), age(a), subject(s) {}
bool canVote() const { return age > 18; }
};
int main() {
Student s("Aman", 18, 7);
Teacher t("Neha", 18, "Art");
cout << boolalpha;
cout << "Aman can vote: " << s.canVote() << endl;
cout << "Neha can vote: " << t.canVote() << endl;
return 0;
}
Output:
Aman can vote: true
Neha can vote: false
boolalpha makes cout print true/false instead of 1/0.
Aman (a student) and Neha (a trainee teacher) are both 18, and they get different answers.
Why it failed: one idea, "a person with a name and an age", lives in two places. Every fix must be made twice, and someday someone forgets. Add Principal, Clerk and Driver and it's five copies.
The fix: a base class and derived classes (mobile plans)
Think of mobile plans:
| Mobile plans | In C++ |
|---|---|
| The basic plan: calls + SMS | class Person, the base class (parent): the shared part, written once |
| The premium plan: "everything in Basic, plus OTT" | class Student : public Person, a derived class (child): gets everything, adds more |
| Premium is a plan: it works anywhere a plan works | a Student is a Person: the is-a test |
class Student : public Person means: a Student is everything a Person is, plus whatever Student adds. This is inheritance. The child inherits the parent's members.
The is-a test. Only inherit when the child is really a kind of the parent. A student is a person, a teacher is a person: inherit. A car is not an engine; a car has an engine. "Has-a" means the engine should be a member of Car (this is called composition), not its parent.
The child must build the parent's part
The obvious way to write Student's constructor is to assign everything in the body:
#include <iostream>
#include <string>
using namespace std;
class Person {
string name; int age;
public:
Person(string n, int a) : name(n), age(a) {}
bool canVote() const { return age >= 18; }
void show() const { cout << name << ", " << age << endl; }
};
class Student : public Person {
int roll;
public:
Student(string n, int a, int r) { name = n; age = a; roll = r; }
};
int main() {
Student s("Aman", 18, 7);
s.show();
return 0;
}
g++ says:
main.cpp:15:37: error: no matching function for call to 'Person::Person()'
main.cpp:15:39: error: 'std::string Person::name' is private within this context
main.cpp:15:49: error: 'int Person::age' is private within this context
Three errors:
no matching function for call to 'Person::Person()': before aStudent's body runs, thePersonpart inside it must be built. We didn't say how, so C++ triedPerson()with no arguments, and there isn't one (Person only hasPerson(string, int)).'std::string Person::name' is private within this context(and the same forage):nameis private toPerson, so even its own child can't touch it. Private means only the class itself (episode 14).
The fix: call the parent's constructor in the initializer list
The child hands the values up to the parent: : Person(n, a), roll(r). Person builds its own part, then the child sets its own members.
#include <iostream>
#include <string>
using namespace std;
class Person {
string name; int age;
public:
Person(string n, int a) : name(n), age(a) {}
bool canVote() const { return age >= 18; }
void show() const { cout << name << ", " << age << endl; }
};
class Student : public Person {
int roll;
public:
Student(string n, int a, int r) : Person(n, a), roll(r) {}
};
class Teacher : public Person {
string subject;
public:
Teacher(string n, int a, string s) : Person(n, a), subject(s) {}
};
int main() {
Student s("Aman", 18, 7);
Teacher t("Neha", 18, "Art");
s.show();
cout << boolalpha << s.canVote() << " " << t.canVote() << endl;
return 0;
}
Output:
Aman, 18
true true
s.show() works even though Student never wrote show(): it came from Person for free. And there is one canVote(), fixed once, so both answers are true.
Rules for the child's constructor:
- The parent's constructor goes first in the initializer list:
: Person(n, a), roll(r). - If you leave it out, C++ calls the parent's default constructor
Person(). If the parent has none, you getno matching function for call to 'Person::Person()'. - The child can only set its own members in its initializer list.
: name(n)inStudentis an error; that'sPerson's job.
Construction and destruction order (building a house)
You can't build the first floor before the foundation. The parent is the foundation: the Person part is built first, then the Student part on top. Demolition goes the other way: the top floor first.
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
Person() { cout << "Person built" << endl; }
~Person() { cout << "Person gone" << endl; }
};
class Student : public Person {
public:
Student() { cout << "Student built" << endl; }
~Student() { cout << "Student gone" << endl; }
};
int main() {
Student s;
cout << "-- main ends --" << endl;
return 0;
}
Output:
Person built
Student built
-- main ends --
Student gone
Person gone
One object, two constructors and two destructors:
| Stage | Order |
|---|---|
| Building | parent → child (Person then Student) |
| Destroying | child → parent (~Student then ~Person) |
The child's destructor runs first because the child's part may still use the parent's part while it cleans up.
A child's own version of a function
Person::show() prints only the name and age. A Student should also show its roll number, so Student writes its own show() with the same name. Inside it, Person::show() calls the parent's version (the :: is the scope resolution operator: "the show that belongs to Person"), so we don't repeat the name-and-age code.
#include <iostream>
#include <string>
using namespace std;
class Person {
string name; int age;
public:
Person(string n, int a) : name(n), age(a) {}
bool canVote() const { return age >= 18; }
void show() const { cout << name << ", " << age << endl; }
};
class Student : public Person {
int roll;
public:
Student(string n, int a, int r) : Person(n, a), roll(r) {}
void show() const {
Person::show();
cout << " roll " << roll << endl;
}
};
int main() {
Student s("Aman", 18, 7);
s.show();
return 0;
}
Output:
Aman, 18
roll 7
When a child writes a function with the same name as the parent's, the child's version hides the parent's one for objects of the child type (s.show() now picks Student::show()). Person::show() still reaches the parent's version.
Careful: hiding hides every parent function with that name, even ones with different parameters:
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
void show() const { cout << "Person" << endl; }
};
class Student : public Person {
public:
void show(int roll) const { cout << "Student, roll " << roll << endl; }
};
int main() {
Student s;
s.show();
return 0;
}
g++ says:
main.cpp:16:11: error: no matching function for call to 'Student::show()'
Student::show(int) hid Person::show(). Fix it by bringing the parent's version back with using Person::show; inside the child:
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
void show() const { cout << "Person" << endl; }
};
class Student : public Person {
public:
using Person::show;
void show(int roll) const { cout << "Student, roll " << roll << endl; }
};
int main() {
Student s;
s.show();
s.show(7);
return 0;
}
Output:
Person
Student, roll 7
Types of inheritance
The word after the colon decides how the parent's members look from outside the child:
#include <iostream>
#include <string>
using namespace std;
class Person {
string name; int age;
public:
Person(string n, int a) : name(n), age(a) {}
bool canVote() const { return age >= 18; }
void show() const { cout << name << ", " << age << endl; }
};
class Student : private Person {
public:
Student(string n, int a) : Person(n, a) {}
};
int main() {
Student s("Aman", 18);
s.show();
return 0;
}
g++ says:
main.cpp:19:11: error: 'void Person::show() const' is inaccessible within this context
main.cpp:19:11: error: 'Person' is not an accessible base of 'Student'
With private inheritance, everything Student got from Person becomes private inside Student, so main can't use any of it.
| Parent's member | class S : public P |
class S : protected P |
class S : private P |
|---|---|---|---|
public |
stays public | becomes protected | becomes private |
protected |
stays protected | stays protected | becomes private |
private |
never usable in S |
never usable in S |
never usable in S |
- Public inheritance is the one for is-a. Use it almost always.
- In a
class,class Student : Personwith no word means private inheritance. In astruct, no word means public. Always writepublic. - The parent's private members are never usable in the child, whatever the word. If a child really needs a member, the parent makes it protected (episode 14):
#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name;
public:
Person(string n) : name(n) {}
};
class Student : public Person {
public:
Student(string n) : Person(n) {}
void hello() const { cout << "Hi, I am " << name << endl; }
};
int main() {
Student s("Aman");
s.hello();
cout << s.name << endl;
return 0;
}
g++ says:
main.cpp:20:15: error: 'std::string Person::name' is protected within this context
Remove the last line of main and it prints:
Hi, I am Aman
Chains of classes: multilevel inheritance
A monitor is a student with a duty. Monitor : public Student, and Student : public Person. Each level passes its part up: Monitor calls Student(n, a, r), which calls Person(n, a).
#include <iostream>
#include <string>
using namespace std;
class Person {
string name; int age;
public:
Person(string n, int a) : name(n), age(a) {}
bool canVote() const { return age >= 18; }
void show() const { cout << name << ", " << age << endl; }
};
class Student : public Person {
int roll;
public:
Student(string n, int a, int r) : Person(n, a), roll(r) {}
void show() const { Person::show(); cout << " roll " << roll << endl; }
};
class Monitor : public Student {
string duty;
public:
Monitor(string n, int a, int r, string d) : Student(n, a, r), duty(d) {}
};
int main() {
Monitor m("Riya", 16, 3, "Attendance");
m.show();
cout << boolalpha << m.canVote() << endl;
return 0;
}
Output:
Riya, 16
roll 3
false
show() came from Student, canVote() came from Person (16 is under 18: false). This is multilevel inheritance. The building order for a Monitor is Person, Student, Monitor, and the destroying order is the reverse (see practice question 2).
A class can also have two parents at once. That is multiple inheritance:
#include <iostream>
#include <string>
using namespace std;
class Singer {
public:
void sing() const { cout << "La la la" << endl; }
};
class Dancer {
public:
void dance() const { cout << "Spin!" << endl; }
};
class Performer : public Singer, public Dancer {};
int main() {
Performer p;
p.sing();
p.dance();
return 0;
}
Output:
La la la
Spin!
It has traps (two parents with the same member name, or two parents with a common grandparent: the "diamond"), so we leave it for later and use it rarely.
Common mistakes (and the real g++ messages)
| Mistake | Code | What g++ says / what happens | Fix |
|---|---|---|---|
| Child constructor doesn't call the parent's, and the parent has no default constructor | Student(...) { name = n; ... } |
error: no matching function for call to 'Person::Person()' |
: Person(n, a), roll(r) |
| Touching the parent's private members in the child | name = n; in Student |
error: 'std::string Person::name' is private within this context |
let the parent's constructor set it, or make it protected |
Private inheritance (or no word in a class) |
class Student : private Person |
error: 'void Person::show() const' is inaccessible within this context and error: 'Person' is not an accessible base of 'Student' |
class Student : public Person |
Using protected data from main |
cout << s.name; |
error: 'std::string Person::name' is protected within this context |
use a public function |
| Same-name function with other parameters in the child | void show(int roll) in Student, then s.show(); |
error: no matching function for call to 'Student::show()' |
using Person::show; in the child |
| Inheriting when it isn't is-a | class Car : public Engine |
compiles, but wrong design | Car has an Engine member |
| Copy-pasting a class instead of inheriting | Student and Teacher with the same code |
compiles, but fixes reach one copy only | shared part in a base class |
Mini project: staff and manager salaries
A shop's Employee has a private name and salary, a constructor, getName() and pay(). A manager is an employee, plus a bonus. Manager passes the name and salary up to Employee, and writes its own pay(): Employee::pay() plus the bonus.
#include <iostream>
#include <string>
using namespace std;
class Employee {
string name;
double salary;
public:
Employee(string n, double s) : name(n), salary(s) {}
string getName() const { return name; }
double pay() const { return salary; }
};
class Manager : public Employee {
double bonus;
public:
Manager(string n, double s, double b) : Employee(n, s), bonus(b) {}
double pay() const { return Employee::pay() + bonus; }
};
int main() {
string n; double s, b;
cin >> n >> s;
Employee e(n, s);
cin >> n >> s >> b;
Manager m(n, s, b);
cout << e.getName() << ": " << e.pay() << endl;
cout << m.getName() << ": " << m.pay() << endl;
return 0;
}
Input:
Ravi 25000
Priya 40000 8000
Output:
Ravi: 25000
Priya: 48000
Manager wrote only what's new: one member and one function. Everything else came from Employee.
Extend it: add an Intern with a stipend (practice question 3).
The next problem
Both Student and Teacher have their own show() now. We put them in one list of Person pointers (each one is a person, so &s fits in a Person*), and call show() on each:
#include <iostream>
#include <string>
using namespace std;
class Person {
string name; int age;
public:
Person(string n, int a) : name(n), age(a) {}
void show() const { cout << name << ", " << age << endl; }
};
class Student : public Person {
int roll;
public:
Student(string n, int a, int r) : Person(n, a), roll(r) {}
void show() const { cout << "Student, roll " << roll << endl; }
};
class Teacher : public Person {
public:
Teacher(string n, int a) : Person(n, a) {}
void show() const { cout << "Teacher" << endl; }
};
int main() {
Student s("Aman", 18, 7);
Teacher t("Neha", 18);
Person* list[2] = {&s, &t};
for (int i = 0; i < 2; i++) list[i]->show();
return 0;
}
Output:
Aman, 18
Neha, 18
Person::show() both times! The pointer's type is Person*, so C++ picked Person's version, not the real object's. Next episode fixes exactly this with virtual functions.
Practice
- Add
Principal : public Teacherwith a school name, and ashow()that reusesTeacher::show(). - Print the build and destroy order for three levels:
Person,Student,Monitor. Predict it first. - Add an
Internwith a stipend to the salary project, and print the total pay. - What error do you get when
Personhas no default constructor andStudent's constructor doesn't callPerson(...)?
Solution
1. Each level reuses the one above it with Parent::show().
#include <iostream>
#include <string>
using namespace std;
class Person {
string name; int age;
public:
Person(string n, int a) : name(n), age(a) {}
void show() const { cout << name << ", " << age << endl; }
};
class Teacher : public Person {
string subject;
public:
Teacher(string n, int a, string s) : Person(n, a), subject(s) {}
void show() const {
Person::show();
cout << " teaches " << subject << endl;
}
};
class Principal : public Teacher {
string school;
public:
Principal(string n, int a, string s, string sc) : Teacher(n, a, s), school(sc) {}
void show() const {
Teacher::show();
cout << " heads " << school << endl;
}
};
int main() {
Principal p("Mrs Iyer", 52, "Physics", "City Public School");
p.show();
return 0;
}
Output:
Mrs Iyer, 52
teaches Physics
heads City Public School
2. Built bottom up, destroyed top down.
#include <iostream>
using namespace std;
class Person {
public:
Person() { cout << "Person built" << endl; }
~Person() { cout << "Person gone" << endl; }
};
class Student : public Person {
public:
Student() { cout << "Student built" << endl; }
~Student() { cout << "Student gone" << endl; }
};
class Monitor : public Student {
public:
Monitor() { cout << "Monitor built" << endl; }
~Monitor() { cout << "Monitor gone" << endl; }
};
int main() {
Monitor m;
cout << "-- main ends --" << endl;
return 0;
}
Output:
Person built
Student built
Monitor built
-- main ends --
Monitor gone
Student gone
Person gone
3. An intern needs nothing new: its stipend is its salary, so Intern only passes the values up.
#include <iostream>
#include <string>
using namespace std;
class Employee {
string name;
double salary;
public:
Employee(string n, double s) : name(n), salary(s) {}
string getName() const { return name; }
double pay() const { return salary; }
};
class Manager : public Employee {
double bonus;
public:
Manager(string n, double s, double b) : Employee(n, s), bonus(b) {}
double pay() const { return Employee::pay() + bonus; }
};
class Intern : public Employee {
public:
Intern(string n, double stipend) : Employee(n, stipend) {}
};
int main() {
Employee e("Ravi", 25000);
Manager m("Priya", 40000, 8000);
Intern i("Kabir", 12000);
cout << e.getName() << ": " << e.pay() << endl;
cout << m.getName() << ": " << m.pay() << endl;
cout << i.getName() << ": " << i.pay() << endl;
cout << "Total: " << e.pay() + m.pay() + i.pay() << endl;
return 0;
}
Output:
Ravi: 25000
Priya: 48000
Kabir: 12000
Total: 85000
4. error: no matching function for call to 'Person::Person()' (the first example under "The child must build the parent's part"). Fix: : Person(n, a) in the child's initializer list, or give Person a default constructor.
Quick quiz
What does this print?
#include <iostream>
#include <string>
using namespace std;
class A {
public:
A() { cout << "A"; }
~A() { cout << "a"; }
};
class B : public A {
public:
B() { cout << "B"; }
~B() { cout << "b"; }
};
int main() {
B x;
return 0;
}
- A.
BAab - B.
ABab - C.
ABba - D.
BAba
Answer
C: ABba (verified). The parent part is built first (A), then the child (B). At the end of main the child is destroyed first (b), then the parent (a).
Interview questions
- What is inheritance? A way to create a new class (derived) from an existing one (base), so the derived class gets the base's members and adds or changes some. It removes duplicated code and models is-a relationships.
- What is the difference between is-a and has-a? Is-a (a Student is a Person) is modelled with public inheritance. Has-a (a Car has an Engine) is modelled with a member (composition). Prefer composition when in doubt.
- In what order are constructors and destructors called with inheritance? Constructors: base first, then derived (members in declaration order before the derived body). Destructors: the exact reverse.
- How does a derived class pass values to the base constructor? In its member initializer list:
Student(string n, int a, int r) : Person(n, a), roll(r) {}. - Can a derived class access the base's private members? No. It can access public and protected members. Private members exist inside the object but are only usable by the base's own functions.
- What is the difference between public, protected and private inheritance? They limit how the base's public and protected members appear through the derived class: public keeps them as they are, protected makes public ones protected, private makes both private.
- What is the default inheritance for
classandstruct?class: private.struct: public. - What is name hiding? A function in the derived class hides all base functions with the same name, even with different parameters.
using Base::name;brings them back. - What does
Person::show()mean insideStudent? Call theshowthat belongs toPerson, using the scope resolution operator::. - What is multilevel vs multiple inheritance? Multilevel: a chain (Person → Student → Monitor). Multiple: one class with two or more direct parents (
class Performer : public Singer, public Dancer). - Why does a
Person*pointing to aStudentcallPerson::show()? Withoutvirtual, the function is chosen at compile time from the pointer's type (static binding). Episode 16 coversvirtual.
Glossary
| Term | Plain meaning | Example |
|---|---|---|
| Inheritance | Building a new class on top of an existing one, so it gets the old one's members | class Student : public Person |
| Base class (parent) | The class whose members are inherited: the shared part | Person |
| Derived class (child) | The class that inherits and adds more | Student, Teacher |
| Inherit | Get the members of the parent without writing them again | Student gets show() and canVote() |
| is-a | The child is a kind of the parent: the test for inheritance | a Student is a Person |
| has-a (composition) | One object contains another as a member | a Car has an Engine member |
| Copy-paste duplication | The same code in two places, so fixes must be made twice | canVote() in Student and Teacher |
| Member initializer list | : ... after a constructor's brackets; sets parts as they're built |
: Person(n, a), roll(r) |
| Parent constructor call | Building the base part from the child's initializer list | : Person(n, a) |
| Default constructor | A constructor with no arguments; used for the parent if you don't call another | Person() |
| Construction order | Parent part built first, then the child | Person built, Student built |
| Destruction order | Child destroyed first, then the parent | Student gone, Person gone |
| Name hiding | A child's function hides all parent functions with the same name | Student::show(int) hides Person::show() |
| Redefining a function | A child writing its own version of a parent's function | Student::show() |
Scope resolution operator (::) |
Picks the version that belongs to a class | Person::show() |
using declaration |
Brings hidden parent functions back into the child | using Person::show; |
boolalpha |
Makes cout print true/false instead of 1/0 |
cout << boolalpha; |
| Access specifier | public, protected, private: who can use a member |
protected: string name; |
protected |
Usable by the class and its children, not by outside code | Person::name in prot.cpp |
| Public inheritance | The parent's public members stay public through the child | : public Person |
| Protected inheritance | The parent's public members become protected in the child | : protected Person |
| Private inheritance | Everything inherited becomes private in the child | : private Person |
| Accessible base | A base whose members outside code may use through the child | not the case with private inheritance |
| Multilevel inheritance | A chain of classes: grandparent → parent → child | Person → Student → Monitor |
| Multiple inheritance | A class with two or more direct parents | class Performer : public Singer, public Dancer |
| Diamond problem | Two parents that share one grandparent, so the grandparent's part appears twice | a later episode |
| Static binding | The function is chosen while compiling, from the pointer's type | Person* calls Person::show() |
Summary
- Copy-pasting a class puts one idea in two places, so a fix reaches one copy and misses the other.
- Put the shared part in a base class and derive the others:
class Student : public Person. Inherit only for is-a; for has-a, use a member. - The child's constructor calls the parent's in its initializer list:
: Person(n, a), roll(r). Without it:no matching function for call to 'Person::Person()'. - The parent's private members are never usable in the child; use the parent's constructor or
protected. - Built parent → child, destroyed child → parent.
- A child can write its own version of a function; it hides the parent's, and
Person::show()reuses the parent's code. - Public inheritance keeps public things public;
private(the default in aclass) hides everything inherited. - Multilevel inheritance chains classes; multiple inheritance gives one class two parents.
- A
Person*pointing to aStudentstill callsPerson::show().
Next episode: virtual functions and polymorphism. One call, list[i]->show(), that runs the right version for every kind of object.