Chapter 29 of 48

Inheritance

Think about a college management system. A Student has a name, an age and a roll number. A Teacher has a name, an age and a salary. A Staff member has a name, an age and a department. If we write three separate classes, the name, the age and every function that works on them get copied three times. Fix a bug in one copy and you have to remember to fix the other two.

The real-world relationship is obvious: a student is a person, a teacher is a person. C++ lets us express exactly that with inheritance: write the common part once in a Person class, and let Student and Teacher inherit it and add only what is new.

In this chapter you will learn the syntax, how access specifiers behave across inheritance (the famous public/protected/private table), the order in which constructors and destructors run, the five types of inheritance, name hiding, inheriting constructors, and the diamond problem with its fix, virtual inheritance. We build on Classes & Objects, Constructors & Destructors and Static Members.


What Is Inheritance?

Inheritance is the mechanism by which a new class (the derived class) is created from an existing class (the base class), so that the derived class automatically contains the members of the base class and can add new members of its own.

Some vocabulary you will see everywhere:

TermAlso calledMeaning
Base classParent class, superclassThe existing class being inherited from
Derived classChild class, subclassThe new class that inherits
Base class subobject—The part of a derived object that is a complete base object

Inheritance models an is-a relationship. "A Student is a Person" makes sense, so Student can derive from Person. "A Car is an Engine" does not; a car has an engine, so Car should simply contain an Engine data member. That is called composition, and choosing correctly between the two is a common interview question.


Syntax and a First Example

class DerivedName : access-specifier BaseName {
    // new members of the derived class
};

The access specifier is public, protected or private. In practice you will use public almost all the time; we will see the other two shortly.

#include <iostream>
#include <string>

class Person {                       // base class
public:
    std::string name;
    int age = 0;

    void introduce() const {
        std::cout << "Hi, I am " << name << ", age " << age << '\n';
    }
};

class Student : public Person {      // derived class
public:
    int rollNo = 0;

    void showRoll() const {
        std::cout << name << " has roll number " << rollNo << '\n';
    }
};

int main() {
    Student s;
    s.name = "Asha";      // inherited from Person
    s.age = 20;           // inherited from Person
    s.rollNo = 42;        // Student's own member

    s.introduce();        // inherited member function
    s.showRoll();         // Student's own member function
}

Output:

Hi, I am Asha, age 20
Asha has roll number 42

Student declared only rollNo and showRoll(), yet a Student object also has name, age and introduce(). Memory-wise, every Student object contains a complete Person inside it:

Student object s
+--------------------------+
|  Person subobject        |
|    name   = "Asha"       |
|    age    = 20           |
+--------------------------+
|  rollNo   = 42           |   ← added by Student
+--------------------------+

Why is this useful?

  • Reuse: common code is written and tested once.
  • Extensibility: new kinds (e.g. Teacher) are added without touching Person.
  • Polymorphism: code written for a Person& can work with any kind of person. This is the topic of the next chapter.

Access Control: private, protected and public Members

A derived class inherits all data members of the base, including private ones. But inheriting a member and being allowed to name it are different things:

  • private members of the base are inside the derived object, but the derived class's code cannot access them directly.
  • protected members are accessible to the base class and its derived classes, but not to outside code such as main().
  • public members are accessible to everyone.
#include <iostream>

class Base {
private:
    int secret = 1;      // only Base's own members and friends
protected:
    int shared = 2;      // Base + classes derived from Base
public:
    int open = 3;        // everyone

    int getSecret() const { return secret; }
};

class Derived : public Base {
public:
    void show() const {
        // std::cout << secret;          // error: 'secret' is private within this context
        std::cout << "shared = " << shared << '\n';           // OK: protected
        std::cout << "open   = " << open << '\n';             // OK: public
        std::cout << "secret = " << getSecret() << '\n';      // OK: via public function
    }
};

int main() {
    Derived d;
    d.show();
    std::cout << "from main, open = " << d.open << '\n';      // OK
    // std::cout << d.shared;            // error: 'shared' is protected within this context
    std::cout << "sizeof(Base) = " << sizeof(Base)
              << ", sizeof(Derived) = " << sizeof(Derived) << '\n';
}

Output:

shared = 2
open   = 3
secret = 1
from main, open = 3
sizeof(Base) = 12, sizeof(Derived) = 12

Two lessons here. First, sizeof(Derived) is 12 bytes (three ints on this system), the same as Base: the private secret is physically present in every Derived object, it is just not accessible by name. Second, if you uncomment the two lines, GCC reports:

error: ‘int Base::secret’ is private within this context
error: ‘int Base::shared’ is protected within this context

protected is the middle ground: "my children may touch this, strangers may not". Use it sparingly. Every protected data member is part of the contract with every future derived class, so many style guides prefer private data plus protected or public member functions.


Modes of Inheritance: public, protected, private

The access specifier written before the base class name decides how inherited members are seen from outside the derived class (and by classes derived from it in turn). It can only make access stricter, never looser:

Member in baseclass D : public Bclass D : protected Bclass D : private B
publicpublic in Dprotected in Dprivate in D
protectedprotected in Dprotected in Dprivate in D
privatenot accessible in Dnot accessible in Dnot accessible in D

An easy way to remember it: the resulting access is the stricter of the member's own access and the inheritance mode. And base-class private members are never accessible to the derived class, whatever the mode.

If you leave out the mode, the default depends on the keyword used for the derived class:

class D1 : B {};    // same as class D1 : private B
struct D2 : B {};   // same as struct D2 : public B

This is a classic exam question, and a classic bug: forgetting public with class silently gives private inheritance.

What do protected and private inheritance mean?

With public inheritance the "is-a" relationship is visible to everyone, so a Student* converts to a Person* anywhere. With private inheritance the relationship is a hidden implementation detail: the derived class uses the base internally ("is implemented in terms of"), but outside code can neither call the base's functions nor convert to the base:

class Stack {
public:
    void push(int) {}
    int size() const { return 0; }
};
class LimitedStack : private Stack {   // private inheritance
public:
    using Stack::size;                 // re-expose just size()
};
int main() {
    LimitedStack s;
    s.size();      // OK
    s.push(1);     // error
    Stack* p = &s; // error
}

GCC's errors (abridged):

error: ‘void Stack::push(int)’ is inaccessible within this context
error: ‘Stack’ is an inaccessible base of ‘LimitedStack’

Notice the using Stack::size; line: a using-declaration inside the derived class can re-expose a selected base member with the access of the section it is written in. In everyday code, composition (a Stack data member) is usually clearer than private inheritance, so treat private and protected inheritance as rare tools.

A subtle rule about protected

A derived class can access a protected member only through an object of its own type (or a class derived from it), not through an arbitrary base object:

class Base {
protected:
    int x = 0;
};
class Derived : public Base {
public:
    void f(Derived& d, Base& b) {
        x = 1;      // OK: own inherited member
        d.x = 2;    // OK: through a Derived
        b.x = 3;    // error
    }
};
int main() {}

The last assignment fails with ‘int Base::x’ is protected within this context. The reason: b might really be some other class derived from Base, and Derived has no business touching that class's internals.


Constructor and Destructor Order

Since a derived object contains a base subobject, the base part must be built first, and the derived constructor can then rely on it being ready. Destruction runs in exactly the reverse order, so the derived destructor can still use the base part while it cleans up.

#include <iostream>

class A {
public:
    A()  { std::cout << "A constructor\n"; }
    ~A() { std::cout << "A destructor\n"; }
};

class B : public A {
public:
    B()  { std::cout << "  B constructor\n"; }
    ~B() { std::cout << "  B destructor\n"; }
};

class C : public B {
public:
    C()  { std::cout << "    C constructor\n"; }
    ~C() { std::cout << "    C destructor\n"; }
};

int main() {
    std::cout << "Creating C...\n";
    {
        C obj;
        std::cout << "-- obj is alive --\n";
    }   // obj goes out of scope here
    std::cout << "Done\n";
}

Output:

Creating C...
A constructor
  B constructor
    C constructor
-- obj is alive --
    C destructor
  B destructor
A destructor
Done
Construction:  base → derived   (A, B, C)    "build the foundation first"
Destruction:   derived → base   (C, B, A)    "demolish the top floor first"

The complete order for constructing an object is:

  1. Virtual base classes (explained below in the diamond problem), if any.
  2. Direct base classes, in the order they are listed in the class declaration (not the order in the initializer list).
  3. Non-static data members, in the order they are declared in the class.
  4. The body of the constructor.

The destructor does the exact reverse: body first, then members in reverse declaration order, then bases in reverse order.


Passing Arguments to the Base Constructor

If the base class has no default constructor, the derived constructor must call a base constructor explicitly, and the only place to do that is the member initializer list:

#include <iostream>
#include <string>

class Employee {
protected:
    std::string name;
    double salary;
public:
    Employee(const std::string& n, double s) : name(n), salary(s) {
        std::cout << "Employee(" << name << ")\n";
    }
    void print() const {
        std::cout << name << " earns " << salary << '\n';
    }
};

class Manager : public Employee {
    int teamSize;
public:
    // Base part is initialised FIRST, through the member initializer list
    Manager(const std::string& n, double s, int t)
        : Employee(n, s), teamSize(t) {
        std::cout << "Manager with team of " << teamSize << '\n';
    }
};

int main() {
    Manager m("Ravi", 95000, 6);
    m.print();
}

Output:

Employee(Ravi)
Manager with team of 6
Ravi earns 95000

If : Employee(n, s) were missing, the compiler would try to call Employee(), which does not exist, and the code would not compile. Also note that you cannot "call the base constructor" from inside the constructor body; by then the base part has already been constructed.


What Is Not Inherited?

A derived class inherits the base's data members and ordinary member functions, but some things behave differently:

ItemWhat happens
ConstructorsNot inherited by default. Each class has its own; you can opt in with using Base::Base; (C++11).
DestructorNot inherited. The derived class has its own, which automatically calls the base destructor.
Copy/move assignment operatorsThe derived class gets its own implicitly declared versions, which hide the base's. The implicit ones call the base's operator for the base part.
FriendsFriendship is not inherited (see Friend Functions & Classes).
Static membersNot copied: base and derived share the same single static member (see Static Members).

Inheriting constructors (C++11)

When the derived class adds no data that needs constructor arguments, writing forwarding constructors is tedious. A using-declaration inherits them all:

#include <iostream>
#include <string>

class Point {
protected:
    int x, y;
public:
    Point(int x, int y) : x(x), y(y) {}
    Point(int v) : Point(v, v) {}        // delegating constructor
};

class Pixel : public Point {
public:
    using Point::Point;                  // C++11: inherit Point's constructors
    std::string color = "black";         // gets its default member initializer

    void show() const {
        std::cout << "(" << x << ", " << y << ") " << color << '\n';
    }
};

int main() {
    Pixel p1(3, 4);      // uses inherited Point(int, int)
    Pixel p2(7);         // uses inherited Point(int)
    p1.show();
    p2.show();
}

Output:

(3, 4) black
(7, 7) black

The inherited constructors initialise the Point part; the derived class's own members use their default member initializers (here color = "black").


Redefining a Base Function: Name Hiding

A derived class may declare a function with the same name as a base function. This is called redefining (or hiding) the function. There is a trap: a name declared in the derived class hides every base function with that name, including overloads with different parameters.

#include <iostream>
class Printer {
public:
    void print() const      { std::cout << "print()\n"; }
    void print(int n) const { std::cout << "print(int) " << n << '\n'; }
};
class ColorPrinter : public Printer {
public:
    void print() const { std::cout << "ColorPrinter::print()\n"; }
};
int main() {
    ColorPrinter cp;
    cp.print(5);
}

Even though Printer::print(int) is perfectly suitable, this fails:

error: no matching function for call to ‘ColorPrinter::print(int)’
note: candidate 1: ‘void ColorPrinter::print() const’

Why? Name lookup happens before overload resolution. The compiler searches for the name print, finds it in ColorPrinter, and stops searching. Only the functions found in that scope take part in overload resolution. The fix is to bring the base overloads into the derived scope:

#include <iostream>

class Printer {
public:
    void print() const      { std::cout << "Printer::print()\n"; }
    void print(int n) const { std::cout << "Printer::print(int) " << n << '\n'; }
};

class ColorPrinter : public Printer {
public:
    using Printer::print;     // bring ALL base overloads of print into scope
    void print() const { std::cout << "ColorPrinter::print()\n"; }
};

int main() {
    ColorPrinter cp;
    cp.print();               // ColorPrinter's own version
    cp.print(5);              // works only because of the using-declaration
    cp.Printer::print();      // explicitly call the base version
}

Output:

ColorPrinter::print()
Printer::print(int) 5
Printer::print()

The syntax cp.Printer::print() (or Printer::print() inside a member function) calls the base version explicitly. Derived classes often use it to extend rather than replace the base behaviour.


Types of Inheritance

Textbooks (and university exams) list five types, based on the shape of the class hierarchy:

1. Single          2. Multilevel        3. Multiple

     A                  A                 A       B
     |                  |                  \     /
     B                  B                   \   /
                        |                     C
                        C

4. Hierarchical      5. Hybrid (here: the "diamond")

       A                     A
     / | \                  / \
    B  C  D                B   C
                            \ /
                             D
TypeDescriptionExample
SingleOne derived class, one baseStudent : Person
MultilevelA chain: derived class becomes a base for anotherPerson → Employee → Manager
MultipleOne class derives from two or more basesSmartPhone : Camera, Phone
HierarchicalSeveral classes derive from one baseStudent, Teacher, Staff from Person
HybridA combination of two or more of the aboveThe diamond below

Unlike Java and C#, C++ supports multiple inheritance of classes directly.

Multiple inheritance

#include <iostream>

class Camera {
public:
    void powerOn() const { std::cout << "Camera on\n"; }
    void takePhoto() const { std::cout << "Click!\n"; }
};

class Phone {
public:
    void powerOn() const { std::cout << "Phone on\n"; }
    void call() const { std::cout << "Calling...\n"; }
};

class SmartPhone : public Camera, public Phone {   // multiple inheritance
public:
    void powerOn() const {
        Camera::powerOn();        // resolve the clash explicitly
        Phone::powerOn();
    }
};

int main() {
    SmartPhone sp;
    sp.takePhoto();       // from Camera
    sp.call();            // from Phone
    sp.powerOn();         // SmartPhone's own version calls both
    sp.Phone::powerOn();  // or pick one base explicitly
}

Output:

Click!
Calling...
Camera on
Phone on
Phone on

If both bases have a member with the same name and the derived class does not declare its own, an unqualified call like sp.powerOn() is ambiguous and will not compile. You resolve it with the scope resolution operator (Camera::powerOn()), or by declaring the member in the derived class as done here.


The Diamond Problem and Virtual Inheritance

Consider Laptop deriving from both Computer and Battery, which both derive from Device. With ordinary inheritance, a Laptop contains two separate Device subobjects, one through each path:

Ordinary inheritance              Virtual inheritance

 Device   Device                        Device
   |        |                          /      \
Computer  Battery                Computer    Battery
    \      /                           \      /
     Laptop                             Laptop

two copies of Device::id          one shared copy of Device::id

Two copies cause two problems: wasted memory and, worse, ambiguity. Which id does laptop.id mean? The compiler refuses to guess:

error: request for member ‘id’ is ambiguous
error: ‘Device’ is an ambiguous base of ‘Laptop’     (for Device* d = &laptop;)

The fix is virtual inheritance: the intermediate classes write virtual before the base name, which means "share this base with anyone else who also inherits it virtually".

#include <iostream>

// Without virtual inheritance: TWO copies of Device inside Laptop
namespace plain {
    struct Device { int id = 0; };
    struct Computer : Device {};
    struct Battery  : Device {};
    struct Laptop   : Computer, Battery {};
}

// With virtual inheritance: ONE shared copy of Device
namespace fixed {
    struct Device {
        int id;
        Device(int i) : id(i) { std::cout << "Device(" << i << ")\n"; }
    };
    struct Computer : virtual Device { Computer() : Device(1) {} };
    struct Battery  : virtual Device { Battery()  : Device(2) {} };
    struct Laptop   : Computer, Battery {
        Laptop() : Device(99) {}   // most-derived class constructs the virtual base
    };
}

int main() {
    plain::Laptop a;
    // a.id = 5;                  // error: request for member 'id' is ambiguous
    a.Computer::id = 5;           // must say WHICH Device
    a.Battery::id  = 7;
    std::cout << "plain: Computer::id = " << a.Computer::id
              << ", Battery::id = " << a.Battery::id << '\n';

    fixed::Laptop b;
    b.id = 5;                     // fine: only one Device subobject
    fixed::Computer& c  = b;
    fixed::Battery&  bt = b;
    std::cout << "fixed: id = " << b.id
              << ", same Device? " << std::boolalpha
              << (&c.id == &bt.id) << '\n';
}

Output:

plain: Computer::id = 5, Battery::id = 7
Device(99)
fixed: id = 5, same Device? true

Look carefully at what was printed: only Device(99). With virtual inheritance there is only one Device, so it cannot be constructed by both Computer and Battery. The rule is:

A virtual base class is initialised by the most-derived class (the class of the complete object being created). The initializers for that virtual base written in intermediate classes are ignored when they are not the most-derived class.

That is why Laptop must mention Device(99) in its initializer list (since Device has no default constructor), and why Device(1) and Device(2) never ran. They would run if you created a plain Computer or Battery object. Virtual bases are also constructed before any non-virtual base, which is step 1 in the order listed earlier.

Virtual inheritance has a small cost (objects typically carry extra hidden pointer or offset information to locate the shared base), so use it only where a diamond actually exists. The standard library's own std::iostream, which derives from both std::istream and std::ostream, uses exactly this technique around their common virtual base std::basic_ios.


Preventing Inheritance with final (C++11)

Sometimes a class is not designed to be extended. Marking it final makes any attempt to derive from it a compile-time error:

class Base final {};
class Derived : public Base {};
int main() {}
error: cannot derive from ‘final’ base ‘Base’ in derived type ‘Derived’

final can also be applied to individual virtual functions; we will see that in the next chapter.


Upcasting: Treating a Derived Object as a Base

Because a Dog is an Animal, a Dog object can be referred to through an Animal& or Animal* (with public inheritance). This conversion is called upcasting, and it is implicit and always safe. But watch what happens when the derived class redefines a function:

#include <iostream>

class Animal {
public:
    void speak() const { std::cout << "Some generic animal sound\n"; }
};

class Dog : public Animal {
public:
    void speak() const { std::cout << "Woof!\n"; }   // hides Animal::speak
};

int main() {
    Dog d;
    Animal& ref = d;      // upcast: a Dog IS-AN Animal
    Animal* ptr = &d;     // upcast through a pointer

    d.speak();            // Dog's version
    ref.speak();          // Animal's version! (no virtual yet)
    ptr->speak();         // Animal's version!
}

Output:

Woof!
Some generic animal sound
Some generic animal sound

Through the base reference and pointer, the base version ran, even though the object is really a Dog. For an ordinary (non-virtual) function the compiler picks the function from the static type of the expression (Animal), decided at compile time. Getting the Dog version through an Animal& requires virtual functions, the subject of the next chapter, Polymorphism & Virtual Functions.


Inheritance vs Composition

InheritanceComposition
Relationshipis-a (Student is a Person)has-a (Car has an Engine)
Syntaxclass Car : public Engineclass Car { Engine engine; };
CouplingTight: derived class depends on base's protected detailsLoose: only the public interface is used
Runtime polymorphismYes (with virtual functions)No, by itself

Rule of thumb: prefer composition; use public inheritance when the is-a relationship is real and you want to use derived objects through base references.


Common Mistakes

  • Forgetting public: class Student : Person is private inheritance. Outside code then cannot call introduce() or convert a Student* to Person*.
  • Not calling the base constructor: if the base has no default constructor, the derived constructor must call one in its initializer list.
  • Accidentally hiding overloads: declaring print() in the derived class hides all base print overloads. Add using Base::print;.
  • Expecting derived behaviour through a base pointer without virtual: as the last example showed, a non-virtual call uses the static type.
  • Assuming initializer-list order matters: bases and members are always initialised in declaration order. GCC's -Wall includes -Wreorder, which warns when your list is written in a different order.
  • Using inheritance for has-a: class Car : public Engine lets anyone call engine functions on a car, and a Car* converts to an Engine*. Use a data member instead.
  • Diamond without virtual: leads to duplicate base subobjects and ambiguity errors.

Interview / Exam Questions

1. What is the default inheritance mode for class and for struct?

class D : B means private inheritance; struct D : B means public inheritance. The default depends on the keyword used to declare the derived class.

2. A base class has a public member p and a protected member q. Class D inherits it with protected mode. What are the accesses of p and q in D?

Both become protected in D. Protected inheritance turns public members into protected and leaves protected members as protected. Base private members remain inaccessible in D.

3. In class C : public A, public B { M m; };, in what order are constructors called?

A, then B (declaration order of the bases), then the member m, then the body of C's constructor. Destructors run in reverse: C's body, m, B, A. The order in the initializer list does not change this.

4. Are private members of a base class inherited?

Yes, they are part of every derived object (they contribute to its sizeof), but the derived class's code cannot access them by name. It can use them only indirectly through public or protected member functions of the base.

5. What is the diamond problem and how does C++ solve it?

When D inherits from B and C, and both inherit from A, D gets two copies of A, causing duplicated data and ambiguous member access. Declaring the inheritance as virtual (class B : virtual public A, same for C) makes D contain a single shared A subobject. The most-derived class is then responsible for constructing A.

6. Base has void f(int). Derived declares void f(). Does derivedObj.f(10) compile?

No. Derived's f hides all base functions named f, because name lookup stops at the first scope where the name is found. Add using Base::f; in Derived, or call derivedObj.Base::f(10).

7. Which of these are not inherited: constructors, destructor, static members, friend declarations?

Constructors (unless brought in with using Base::Base;), the destructor and friendship are not inherited. Static members are accessible from the derived class, but there is still only one shared copy for base and derived together.


Summary

  • Inheritance creates a derived class that contains everything in a base class and adds its own members. It models is-a; use composition for has-a.
  • Private base members are inherited but not accessible; protected members are accessible to derived classes but not outsiders.
  • The inheritance mode (public/protected/private) can only make inherited access stricter. Default: private for class, public for struct.
  • Construction goes base → members → derived body; destruction goes in exact reverse. Pass base constructor arguments via the initializer list.
  • Constructors, the destructor and friendship are not inherited; using Base::Base; (C++11) inherits constructors.
  • A same-named derived function hides all base overloads; fix with using Base::name;.
  • Five types: single, multilevel, multiple, hierarchical, hybrid. Diamonds need virtual inheritance, and the most-derived class constructs the virtual base.
  • final (C++11) prevents further derivation.
  • Through a base pointer or reference, non-virtual functions use the base version. To fix that, we need Polymorphism & Virtual Functions, coming next.