⚡0 XP🔥0

Inheritance

Lesson 7 of 12 ⏱ 6 min read ✎ 1 exercises ❓ 4-question quiz ▶ Runs C++

Reuse code by deriving classes - base and derived classes, public/protected/private inheritance, constructor order, function overriding, and single, multilevel, multiple and hierarchical inheritance.

Inheritance lets you create a new class (the derived or child class) from an existing class (the base or parent class). The derived class gets all the base's members and adds or changes what it needs. It models an "is-a" relationship: a Car is a Vehicle, a Manager is an Employee.

class Derived : public Base {
    // extra members
};

A first example#

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Tata Nexon with 4 wheels
Seats: 5
Royal Enfield with 2 wheels

Car and Bike reuse brand, wheels and info() without rewriting them.

हिंदी में समझें

Inheritance यानी विरासत - बच्चे (derived class) को माता-पिता (base class) की चीज़ें मिल जाती हैं। Car को Vehicle का brand, wheels और info() function अपने आप मिल गए; हमें बस Car की खास चीज़ (seats) जोड़नी पड़ी। इससे code दोबारा नहीं लिखना पड़ता।

Access control in inheritance#

Base member in public inheritance becomes in protected inheritance in private inheritance
public public protected private
protected protected protected private
private not accessible not accessible not accessible

public inheritance is used 95% of the time - it keeps the "is-a" relationship visible to everyone.

Constructor and destructor order#

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Base constructor
Derived constructor
--- using d ---
Derived destructor
Base destructor

The base part is built first (a house needs its foundation before the upper floor) and destroyed last.

Function overriding#

A derived class can redefine a base-class function with the same signature. Call the base version with Base::function():

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Balance 100000, interest 3500
Senior: balance 100000, interest 4000
Common Mistake

Without the virtual keyword, overriding is resolved at compile time by the pointer/reference type. A Account* pointing to a SeniorAccount would still call Account::interest(). The next lesson fixes this with virtual functions.

Types of inheritance#

Single        Multilevel        Multiple           Hierarchical
  A             A                 A     B              A
  |             |                  \   /             / | \
  B             B                    C              B  C  D
                |
                C

Multilevel#

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Hi, I am Neha
Roll 114, thesis: Crop yield prediction with ML

Multiple inheritance#

A class can have more than one base class:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Calling Mom
Photo taken
Browsing the web

The diamond problem and virtual inheritance#

If B and C both inherit from A, and D inherits from both B and C, then D contains two copies of A - and d.someAMember becomes ambiguous. Declaring class B : virtual public A and class C : virtual public A makes them share one A:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Device id: 7

Inheritance vs composition#

Inheritance means is-a. When the relationship is has-a (a Car has an Engine), put an object inside the class instead (composition). Overusing inheritance creates rigid designs - "prefer composition over inheritance" is a well-known design rule.

Summary#

  • class D : public B makes D inherit B's members; use protected for members children need.
  • Base constructors run first (call them in the initializer list); destructors run in reverse.
  • A derived class can override base functions; call the base version with Base::f().
  • C++ supports single, multilevel, multiple and hierarchical inheritance; virtual inheritance solves the diamond problem.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Employee and Manager

Employee has name and salary and show(). Derive Manager with an extra teamSize and a bonus() returning 10% of salary plus 2000 per team member. Override show() to also print the bonus. Output:

Ritu: 90000
Sameer: 150000, team 4, bonus 23000
Expected output:
Ritu: 90000
Sameer: 150000, team 4, bonus 23000

Quick Quiz

Q1.

In class Car : public Vehicle, which is the base class?

Q2.

Which members of the base class can a derived class access directly?

Q3.

When a derived object is created, which constructor runs first?

Q4.

What problem does virtual inheritance solve?