Inheritance
Open in the Padhaiko app5.1 Base class and derived class
Inheritance is the mechanism by which a new class (derived class or subclass) acquires the data members and member functions of an existing class (base class or superclass), while adding new features or customizing existing behaviour.
- Base Class: The general class whose properties are inherited (e.g.,
Person,Shape). - Derived Class: The specialized class that inherits from the base class and extends it (e.g.,
Student,Circle). - Benefits: Eliminates code duplication, enforces a clean hierarchical design, and enables run-time polymorphism.
5.2 protected access specifier
With only private and public, either a base class member is completely hidden even from derived classes (private), or it is exposed to the entire program (public). The protected access specifier sits in between:
Visibility of protected Members
A protected member of a base class:
- Is accessible inside the base class itself, its
friends, and member functions of derived classes (when inheritedpublicly orprotectedly). - Is inaccessible to outside non-member code (such as
main()).
| Access Specifier in Base | Same Class | Derived Class | Outside (main()) |
|---|---|---|---|
public | Yes | Yes | Yes |
protected | Yes | Yes | No |
private | Yes | No (only via public/protected getters or friend) | No |
5.3 Derived class declaration
A derived class lists its base class(es) after a colon : in the class header:
class Base {
protected:
int id;
public:
void setId(int i) { id = i; }
};
class Derived : public Base { // Visibility mode: public, protected, or private
private:
double gpa;
public:
void setGpa(double g) { gpa = g; }
};- If the visibility mode is omitted on a
class, C++ defaults toprivateinheritance (whereas astructdefaults topublicinheritance).
5.4 Is_a relation and Has_a relation
Object-oriented design distinguishes two fundamental class relationships:
| Aspect | Is-a Relationship (Inheritance) | Has-a Relationship (Composition) |
|---|---|---|
| Mechanism | class Car : public Vehicle | class Car { Engine eng; }; |
| Meaning | Car is a specialized Vehicle | Car has an Engine as a part |
| Interface Exposure | Derived class inherits base's public interface | Enclosing class controls what is exposed |
| Coupling | Tighter (depends on base internals/protected API) | Looser (depends only on member's public API) |
| When to Use | True generalization/specialization & polymorphism | Building complex objects from component parts |
5.5 Public, protected and private inheritance
The visibility mode (public, protected, or private) determines the maximum access level inherited base members retain inside the derived class. Note that private base members are never directly accessible to derived classes under any mode (though they still occupy space in the derived object).
| Base Class Member | public Inheritance | protected Inheritance | private Inheritance |
|---|---|---|---|
public in Base | public in Derived | protected in Derived | private in Derived |
protected in Base | protected in Derived | protected in Derived | private in Derived |
private in Base | Not directly accessible | Not directly accessible | Not directly accessible |
5.6 Member overriding
When a derived class defines a member function with the exact same name and parameter signature as a base-class function, the derived version overrides (shadows) the base version for derived objects.
- Calling
d.show()invokesDerived::show(). - To call the hidden base version explicitly from outside or inside
Derived, qualify with the scope resolution operator:Base::show()(ord.Base::show()). - Name Hiding Rule: Defining any function named
finDerivedhides all overloadedf(...)functions inBaseunlessusing Base::f;is placed inDerived.
5.7 Forms of inheritance
C++ supports five forms of class inheritance:
1. Single 2. Multilevel 3. Hierarchical
[A] [A] [A]
| | / \
[B] [B] [B] [C]
|
[C]
4. Multiple 5. Hybrid (Multipath / Diamond)
[A] [B] [A]
\ / / \
[C] [B] [C]
\ /
[D]- Single Inheritance: One derived class inherits from one base class (
class B : public A). - Multilevel Inheritance: A chain of inheritance where a derived class acts as a base for another (
A -> B -> C). - Hierarchical Inheritance: Multiple derived classes inherit from one shared base class (
A -> B,A -> C). - Multiple Inheritance: One derived class inherits from two or more base classes (
class C : public A, public B).- Ambiguity: If both
AandBdefineshow(), callingc.show()is ambiguous; resolve viac.A::show()or overrideshow()inC.
- Ambiguity: If both
- Hybrid Inheritance: A combination of two or more forms above (commonly hierarchical + multiple, forming a diamond).
5.8 Constructors in derived class
When a derived object is created, its base subobject must be initialized before the derived class adds its own state:
- Order of Execution: Base class constructor runs first, followed by member-object constructors (if any), and finally the derived class constructor.
- Passing Arguments to Base Constructor: Use the derived constructor's member initializer list:
class Base {
int a;
public:
Base(int x) : a(x) {}
};
class Derived : public Base {
int b;
public:
Derived(int x, int y) : Base(x), b(y) {} // Passes x up to Base(int)
};- Multiple Inheritance Order: In
class C : public A, public B, constructors run in the order of inheritance declaration (A(), thenB(), thenC()), regardless of the order written inC's initializer list. - Virtual Base Classes: Virtual base constructors always execute first, before all non-virtual base constructors.
5.9 Destructor in derived class
Destructors execute in the exact reverse order of constructors:
- Derived class destructor (
~Derived()) runs first, cleaning up derived resources while the base subobject is still valid. - Base class destructor (
~Base()) runs last. - In multiple inheritance (
class C : public A, public B), destruction order is~C(), then~B(), then~A().
5.10 Need of virtual base class
In multipath (diamond) hybrid inheritance (A -> B, A -> C, and B, C -> D), normal inheritance gives D two separate copies of A—one inherited through B and another through C. Accessing any member of A from D (such as d.val or d.show()) triggers an ambiguous member access compile error and wastes memory.
Virtual Base Class
Declaring B and C to inherit A using the virtual keyword (class B : virtual public A, class C : virtual public A) ensures that any further derived class D contains only one shared instance of A, eliminating both duplicate storage and ambiguity.
#include <iostream>
using namespace std;
class Person {
protected:
int id;
public:
Person(int i = 0) : id(i) {}
};
class Student : virtual public Person {
protected:
double gpa;
public:
Student(int i, double g) : Person(i), gpa(g) {}
};
class Employee : virtual public Person {
protected:
double salary;
public:
Employee(int i, double s) : Person(i), salary(s) {}
};
class TeachingAssistant : public Student, public Employee {
public:
// Most-derived class initializes the virtual base Person directly!
TeachingAssistant(int i, double g, double s)
: Person(i), Student(i, g), Employee(i, s) {}
void show() const {
cout << "ID=" << id << ", GPA=" << gpa << ", Salary=" << salary << endl;
}
};
int main() {
TeachingAssistant ta(101, 3.9, 25000);
ta.show();
return 0;
}Worked Examples
1
Model a university hierarchy using multilevel and hierarchical inheritance: Person (name, age) -> Student (roll, marks1, marks2) -> Result (total, percentage, display()). Show constructor chaining and member overriding, and trace the output for "Asha", age 20, roll 15, marks 82 and 90.
Class Hierarchy and Constructor Chaining: Result calls Student(...), which calls Person(...). Result::display() overrides Student::display() and invokes Student::display() using :: before printing the computed total and percentage:
#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name;
int age;
public:
Person(const string &n, int a) : name(n), age(a) {}
void display() const {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
class Student : public Person {
protected:
int roll;
double m1, m2;
public:
Student(const string &n, int a, int r, double x, double y)
: Person(n, a), roll(r), m1(x), m2(y) {}
void display() const {
Person::display();
cout << "Roll: " << roll << ", Marks: " << m1 << ", " << m2 << endl;
}
};
class Result : public Student {
public:
Result(const string &n, int a, int r, double x, double y)
: Student(n, a, r, x, y) {}
void display() const {
Student::display();
double total = m1 + m2;
double pct = total / 2.0;
cout << "Total: " << total << ", Percentage: " << pct << "%" << endl;
}
};
int main() {
Result r("Asha", 20, 15, 82, 90);
r.display();
return 0;
}Execution Trace:
- Construction:
Person("Asha", 20)->Student(..., 15, 82, 90)->Result(...). r.display()runsResult::display(), which callsStudent::display(), which callsPerson::display().- Total =
82 + 90 = 172, Percentage =172 / 2.0 = 86%.
Output:
Name: Asha, Age: 20Roll: 15, Marks: 82, 90Total: 172, Percentage: 86%
2
Trace the exact constructor and destructor execution order in the following virtual base + multiple inheritance program, and write its output.
#include <iostream>
using namespace std;
class VBase {
public:
VBase() { cout << "VBase "; }
~VBase() { cout << "~VBase "; }
};
class Left : virtual public VBase {
public:
Left() { cout << "Left "; }
~Left() { cout << "~Left "; }
};
class Right : virtual public VBase {
public:
Right() { cout << "Right "; }
~Right() { cout << "~Right "; }
};
class Leaf : public Right, public Left {
public:
Leaf() { cout << "Leaf "; }
~Leaf() { cout << "~Leaf "; }
};
int main() {
Leaf obj;
return 0;
}Construction Order Rules:
- Virtual base classes are constructed once and first:
VBase. - Direct non-virtual base classes are constructed in declaration order (
class Leaf : public Right, public Left):Right, thenLeft. - Derived class constructor runs last:
Leaf.
Destruction Order: Destruction runs in exact reverse of construction: ~Leaf, then ~Left, then ~Right, and finally ~VBase.
Output: VBase Right Left Leaf ~Leaf ~Left ~Right ~VBase
Exercises
Exercises — Inheritance
Contrast public, protected, and private inheritance in C++. Can a derived class ever access a private member of its base class directly?
Access Transformation Across Modes:
publicinheritance: Basepublicstayspublic; baseprotectedstaysprotected. Models an is-a relationship.protectedinheritance: Both basepublicand baseprotectedbecomeprotectedin the derived class (hidden from external callers, still accessible to further subclasses).privateinheritance: Both basepublicand baseprotectedbecomeprivatein the derived class (hidden from both external callers and further subclasses).
Direct Access to Base private Members: No—regardless of whether inheritance is public, protected, or private, a private member of a base class is never directly accessible inside a derived class (unless the derived class is explicitly declared a friend of the base class). Derived classes interact with base private data through public or protected base member functions.
public inheritance preserves public/protected levels, protected inheritance caps them at protected, and private inheritance caps them at private. A derived class can never directly access private base members (except via friend or base public/protected methods).
Differentiate between is-a (inheritance) and has-a (composition) relationships with a concrete C++ example for each.
Definitions and Comparison:
- Is-a (Inheritance): Expresses specialization where a derived class is a kind of base class (
class Circle : public Shape), inheriting its interface and enabling polymorphism. - Has-a (Composition): Expresses containment where a class holds an object of another class as a member (
class Computer { CPU cpu; };), delegating tasks to the member without exposing its full interface.
Minimal Example: class GraduateStudent : public Student models is-a (a graduate student is a student), whereas class Student { Date dob; }; models has-a (a student has a date of birth).
Is-a uses inheritance (Derived : public Base) to model specialization, whereas has-a uses composition (an object of one class as a data member of another) to model part-whole containment.
What is the diamond (multipath) problem in multiple/hybrid inheritance, and how does a virtual base class resolve it?
The Diamond Problem: When class D inherits from both B and C, and both B and C inherit non-virtually from a common base A, D inherits two separate A subobjects (one via B, one via C). Referencing d.x or d.show() from A is rejected by the compiler as ambiguous, and A's constructor/destructor run twice.
Resolution with virtual Base Class: Inheriting A virtually in both intermediate classes (class B : virtual public A and class C : virtual public A) instructs the compiler to merge the shared base into one single A subobject inside D. Ambiguity disappears and D's initializer list initializes A once directly.
Non-virtual diamond inheritance duplicates the top base class A inside D, causing memory waste and ambiguous member access. Marking A as a virtual base class in both B and C gives D a single shared A subobject.
How does member overriding work in inheritance, and how can an overridden base-class function still be invoked? Mention what happens when multiple inheritance causes ambiguity between two base classes with the same method name.
Overriding and Calling the Base Version: When a derived class defines a function with the same signature as a base class function, calling d.func() on a derived object invokes Derived::func(). The overridden base version can still be called explicitly using the scope resolution operator: Base::func() inside Derived, or d.Base::func() from outside.
Ambiguity in Multiple Inheritance: If class C : public A, public B inherits void print() from both A and B without overriding it, c.print() is a compile-time ambiguity error. Resolve it either by qualifying c.A::print() / c.B::print(), or by overriding void print() inside C to specify the desired behaviour.
Defining a matching function in a derived class overrides the base version; call the hidden base method via Base::func(). In multiple inheritance, identical method names from two bases are resolved with Base1::func() / Base2::func() or an explicit override in the derived class.
Suppose Base has int a, b; (8 bytes), Mid derives from Base and adds double x; (8 bytes), and Sub derives from Mid and adds int k; (4 bytes). Assuming no extra alignment padding or vptr, what is the memory size of a Sub object, and in what order do constructors and destructors execute when creating and destroying a Sub object?
Object Memory Layout: A derived object contains its own non-static members plus all inherited non-static data members from its base classes (including private base members): sizeof(Sub) = 8 (Base) + 8 (Mid) + 4 (Sub) = 20 bytes (assuming no padding).
Constructor and Destructor Sequence:
- Construction (Base -> Derived):
Base()->Mid()->Sub(). - Destruction (Derived -> Base):
~Sub()->~Mid()->~Base().
A Sub object occupies 20 bytes. Constructors run top-down (Base(), Mid(), Sub()), and destructors run bottom-up (~Sub(), ~Mid(), ~Base()).