TalentJR

🧩 C++ programming tutorial for beginners · Class 11 · Lesson 3 of 18 · Free

Inheritance in C++ – Reuse a Class to Build a New One

⏱ About 35 minutes · ▶ run real C++ here — nothing to install · no sign-in

In this lesson you will

  • Create a derived class that reuses a base class's members
  • Call the base class constructor and use protected members correctly
  • Redefine a base function in a derived class and build a multilevel chain

A school app needs students, teachers and office staff. All of them have a name, a phone number and an ID card. Writing those three things again in every class is boring and easy to get wrong. Inheritance lets you write them once and reuse them.

What is inheritance in C++?

Inheritance means making a new class from an existing one. The existing class is the base class (or parent). The new one is the derived class (or child).

class Student : public Person means "a Student is a Person, plus more". Student gets name and introduce() for free, and adds its own className.

This is called an is-a relationship. A student is a person, so inheritance fits. A school is not a person, so School should not inherit from Person.

Try it: add a new member function void greet() const to Person and call it on s. Student gets it without any change.

🧩 C++ — you can edit this code
Output
Hi, I am Meera
Meera is studying in class 11-B

💡 Always write public before the base name. Without it, a class inherits privately and outside code loses access to the base's public functions.

How do constructors work with inheritance in C++?

A derived object contains a base part inside it. So the base part must be built first. C++ always runs the base constructor before the derived constructor.

To pass values to the base constructor, call it in the member initializer list: Student(...) : Person(n). Lesson 2 showed these lists.

Run the code and watch the order of the messages. The base message comes first every time.

Try it: create a second Student and see the pair of messages repeat.

🧩 C++ — you can edit this code
Output
Person part ready: Kabir
Student part ready: roll 23
Kabir has roll number 23

What is the difference between private, protected and public in C++?

private members can be used only inside the same class. Even a derived class cannot see them.

protected members can be used inside the class AND inside classes derived from it. Outside code still cannot touch them.

public members can be used from anywhere.

Here the savings account (derived) adds interest by reading balance. That works because balance is protected. Try it: change protected to private and run. The compiler stops you.

🧩 C++ — you can edit this code
Output
Balance after a year: Rs 3120

How do I override a function from the base class in C++?

A derived class can write its own version of a base function with the same name. Calling it on a derived object then runs the new version. Without virtual this is strictly called hiding; true overriding needs virtual (Lesson 4).

You can still call the base version from inside: Person::show(). The :: means "the show that belongs to Person". This avoids copying the base code.

Important: without the word virtual, C++ picks the function from the type it sees at compile time. Lesson 4 shows why that matters and how virtual fixes it.

Try it: add a Staff class with a department and its own show().

🧩 C++ — you can edit this code
Output
Name: Mr. Iyer, Phone: 98xxxxxx01
Name: Mrs. Kulkarni, Phone: 98xxxxxx02
Teaches: Physics

What are the types of inheritance in C++?

Single inheritance: one base, one derived (Person to Student). Hierarchical: many classes from one base (Student and Teacher from Person).

Multilevel: a chain. Here Vehicle → Train → ExpressTrain. ExpressTrain gets everything from both classes above it.

Multiple inheritance (one class with two bases) also exists in C++. It has some traps, so Lesson 15 covers it on its own.

Try it: add a member int coaches to Train and print it in ExpressTrain's describe().

🧩 C++ — you can edit this code
Output
Deccan Queen: 75 km/h, 3 stops
Mumbai to Pune (150 km): 2 hours

🤔 Predict the output

Think like C++: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

#include <iostream>
using namespace std;

class A {
public:
    A() { cout << "A"; }
};

class B : public A {
public:
    B() { cout << "B"; }
};

int main() {
    B obj;
    cout << "\n";
    return 0;
}

Question 2. What does this print?

#include <iostream>
using namespace std;

class A {
protected:
    int x;
public:
    A() { x = 1; }
};

class B : public A {
public:
    B() { x = x * 10; }
};

class C : public B {
public:
    C() { x = x + 5; }
    int get() const { return x; }
};

int main() {
    C c;
    cout << c.get() << "\n";
    return 0;
}

Question 3. What does this print?

#include <iostream>
using namespace std;

class Person {
public:
    void intro() const { cout << "I am a person\n"; }
};

class Student : public Person {
public:
    void intro() const { cout << "I am a student\n"; }
};

int main() {
    Student s;
    Person* p = &s;
    p->intro();
    return 0;
}

🧩 Your challenge

Build a tiny school directory. Write a base class Member with a protected name and id and a show() that prints "ID <id>: <name>". Derive Student (adds className) and Teacher (adds subject). Each derived show() calls Member::show() first, then prints its extra line. In main, show one student and one teacher: ID 101: Ananya Class: 11-A ID 7: Mr. Das Subject: Chemistry

Expected output :
ID 101: Ananya
  Class: 11-A
ID 7: Mr. Das
  Subject: Chemistry
🧩 C++ — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

#include <iostream>
using namespace std;

class Account {
private:
    int balance = 100;
};

class Savings : public Account {
public:
    void addInterest() { balance += 5; }
};

int main() {
    Savings s;
    s.addInterest();
    cout << "OK\n";
    return 0;
}

Line 11: error: 'balance' is a private member of 'Account'

✅ Right

#include <iostream>
using namespace std;

class Account {
protected:
    int balance = 100;
};

class Savings : public Account {
public:
    void addInterest() { balance += 5; }
    int get() const { return balance; }
};

int main() {
    Savings s;
    s.addInterest();
    cout << s.get() << "\n";
    return 0;
}

A derived class cannot see the base's private members. Make them protected if derived classes need them.

❌ Wrong

#include <iostream>
using namespace std;

class Person {
public:
    void hello() const { cout << "Hello\n"; }
};

class Student : Person {
};

int main() {
    Student s;
    s.hello();
    return 0;
}

Line 14: error: 'hello' is a private member of 'Person'

✅ Right

#include <iostream>
using namespace std;

class Person {
public:
    void hello() const { cout << "Hello\n"; }
};

class Student : public Person {
};

int main() {
    Student s;
    s.hello();
    return 0;
}

With class, leaving out public makes the inheritance private, so Person's public functions become private inside Student. Write : public Person.

❌ Wrong

#include <iostream>
#include <string>
using namespace std;

class Person {
protected:
    string name;
public:
    Person(string n) : name(n) {}
};

class Student : public Person {
    int roll;
public:
    Student(string n, int r) : roll(r) {}
};

int main() {
    Student s("Isha", 4);
    cout << "Made\n";
    return 0;
}

Line 15: error: constructor for 'Student' must explicitly initialize the base class 'Person' which does not have a default constructor

✅ Right

#include <iostream>
#include <string>
using namespace std;

class Person {
protected:
    string name;
public:
    Person(string n) : name(n) {}
};

class Student : public Person {
    int roll;
public:
    Student(string n, int r) : Person(n), roll(r) {}
    int getRoll() const { return roll; }
};

int main() {
    Student s("Isha", 4);
    cout << "Made roll " << s.getRoll() << "\n";
    return 0;
}

Person has no constructor without arguments, so Student must call Person(n) in its initializer list. Otherwise the base part cannot be built.

📌 Remember

  • class B : public A makes B a derived class that gets A's members.
  • Use inheritance only for is-a relationships: a Student is a Person.
  • The base constructor runs first; pass it values in the initializer list.
  • protected members are visible to derived classes but not to outside code.
  • A derived class can redefine a function and still call Base::function().

Finished the quiz and the challenge?

Questions students ask

Are private members inherited in C++?

Yes, they are part of every derived object, so they take memory. But the derived class's code cannot name them directly. It can use them only through the base's public or protected functions.

What is the difference between public, protected and private inheritance?

With public inheritance, the base's public members stay public in the derived class. Protected inheritance makes them protected, and private inheritance makes them private. Almost all real code uses public inheritance.

Does Java or Python inheritance work the same way?

The idea is the same. Java uses extends and Python puts the base in brackets. C++ adds choices such as protected inheritance and multiple inheritance, and functions are not virtual unless you say so.

When should I not use inheritance?

Don't use it just to reuse code when the is-a test fails. A Car has an Engine, it is not an Engine, so the Car should hold an Engine member. This is called composition.