0% found this document useful (0 votes)
4 views22 pages

Module 3

Module III of the ES203 course covers the concept of inheritance in object-oriented programming using C++. It explains various types of inheritance including single, multilevel, multiple, hierarchical, and hybrid inheritance, along with access modes, abstract classes, and the diamond problem. The module also discusses composition, aggregation, method overriding, and the role of constructors in derived classes.

Uploaded by

pbcg.common
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views22 pages

Module 3

Module III of the ES203 course covers the concept of inheritance in object-oriented programming using C++. It explains various types of inheritance including single, multilevel, multiple, hierarchical, and hybrid inheritance, along with access modes, abstract classes, and the diamond problem. The module also discusses composition, aggregation, method overriding, and the role of constructors in derived classes.

Uploaded by

pbcg.common
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module III: Inheritance

ES203 – Object Oriented Programming Using C++

Dr. Sreemana Datta


Asst. Professor
Department of Computer Science & Engineering
Amity School of Engineering & Technology
Amity University, Jharkhand

February 19, 2026

ES203 – OOP Using C++ Module III: Inheritance 1 / 22


Module III — Roadmap

1 Inheritance Fundamentals

2 More Inheritance Types & Access Modes

3 Abstract Classes & Ambiguity Resolution

4 Aggregation, Composition & Method Overriding

5 Constructors in Derived Classes & Nested Classes

ES203 – OOP Using C++ Module III: Inheritance 2 / 22


What is Inheritance?
Inheritance is the mechanism by which a new class (derived/child) Benefits:
acquires the properties and behaviors of an existing class (base/parent). 1 Code Reusability — Don’t repeat yourself (DRY)
2 Extensibility — Add new features without changing old code
3 Hierarchy — Models real-world “is-a” relationships
Analogy: Family Traits
4 Polymorphism — Enables virtual functions
Your parents (base class) pass on traits to you (derived class):
You inherit eye color, height genes Terminology:
You add your own skills, hobbies
Base class = Parent / Super class
You might even override some traits (different career than parents!)
Derived class = Child / Sub class
Syntax:
class Derived : access_mode Base { ... };

ES203 – OOP Using C++ Module III: Inheritance 3 / 22


Type 1: Single Inheritance
One derived class inherits from one base class.

Animal class Animal {


public :
string name ;
void eat () {
inherits cout « name « " is eating . " « endl ;
}
void sleep () {
cout « name « " is sleeping . " « endl ;
Dog }
};

class Dog : public Animal { // Single inheritance


Dog is-a Animal public :
void bark () {
cout « name « " says Woof ! " « endl ;
}
};

int main () {
Dog d ;
d . name = " Buddy " ; // Inherited member
d . eat () ; // Inherited method
d . bark () ; // Own method
return 0;
}

ES203 – OOP Using C++ Module III: Inheritance 4 / 22


Type 2: Multilevel Inheritance
A class derives from a class which itself is derived from another class — like a chain.

Animal class Animal {


public :
// Grandparent

void eat () { cout « " Eating ... " « endl ; }


};

class Dog : public Animal { // Parent


Dog public :
void bark () { cout « " Barking ... " « endl ; }
};

class Puppy : public Dog { // Child ( inherits BOTH !)


public :
Puppy };
void play () { cout « " Playing ... " « endl ; }

Grandparent → Parent → Child int main () {


Puppy p ;
p . eat () ; // From Animal ( grandparent )
p . bark () ; // From Dog ( parent )
p . play () ; // Own method
return 0;
}

ES203 – OOP Using C++ Module III: Inheritance 5 / 22


Type 3: Multiple Inheritance
A class inherits from two or more base classes simultaneously.

Father Mother class Printable {


public :
void print () {
cout « " Printing document ... " « endl ;
}
};

class Scannable {
Child public :
void scan () {
cout « " Scanning document ... " « endl ;
}
Child inherits from both parents! };

// Multiple inheritance : comma - separated


class Al lI n On eP r in t er
: public Printable , public Scannable {
public :
void fax () {
cout « " Faxing document ... " « endl ;
}
};

int main () {
A ll In O ne P ri nt e r hp ;
hp . print () ; // From Printable
hp . scan () ; // From Scannable
hp . fax () ; // Own method
return 0;
}

ES203 – OOP Using C++ Module III: Inheritance 6 / 22


Type 4: Hierarchical Inheritance
Multiple classes derive from a single base class.
Shape class Shape {
public :
string color ;
void setColor ( string c ) { color = c ; }
};

class Circle : public Shape {


public :
Circle Rectangle Triangle double radius ;
double area () { return 3.14159 * radius * radius ; }
};
One parent, many children
class Rectangle : public Shape {
public :
double length , width ;
double area () { return length * width ; }
};

class Triangle : public Shape {


public :
double base , height ;
double area () { return 0.5 * base * height ; }
};

ES203 – OOP Using C++ Module III: Inheritance 7 / 22


Type 5: Hybrid Inheritance
Hybrid = combination of two or more types of inheritance.

This example combines:


Person
Hierarchical: Person → Student, Employee
Multiple: Student + Employee → WorkingStudent

Student Employee
The Diamond Problem!
WorkingStudent gets two copies of Person’s data — one via
WorkingStudent Student, one via Employee.
Solution: Virtual Base Class (covered soon!)

ES203 – OOP Using C++ Module III: Inheritance 8 / 22


All Five Types of Inheritance — Summary
Type Structure Example
Single A→B Animal → Dog
Multilevel A→B→C Animal → Dog → Puppy
Multiple A, B → C Printable, Scannable → AllInOne
Hierarchical A → B, C, D Shape → Circle, Rect, Triangle
Hybrid Mix of above Person → Student + Employee →
WorkingStudent

Exam Tip
Draw diagrams! Examiners love when you illustrate inheritance types with neat diagrams and label base/derived classes clearly.

ES203 – OOP Using C++ Module III: Inheritance 9 / 22


Access Modes in Inheritance
When inheriting, the access mode determines how base class members appear in the derived class.

Base Member public inheritance protected inheritance private inheritance


public remains public becomes protected becomes private
protected remains protected remains protected becomes private
private not accessible not accessible not accessible

Simple Memory Aid


Public inheritance: “I’m proud of my parent — everything stays as it was!”
Protected inheritance: “I’m keeping family business within the family”
Private inheritance: “What I inherited is now my private property”

Private members of base class are NEVER directly accessible in derived class, regardless of the access mode. Use getters/setters!

ES203 – OOP Using C++ Module III: Inheritance 10 / 22


Access Modes — Code Demonstration
class Base {
public : int pub ;
protected : int prot ;
private : int priv ;
};

class PubDerived : public Base {


// pub -> public ( accessible outside )
// prot -> protected ( accessible in further derived )
// priv -> NOT accessible at all
void test () {
pub = 1; // OK
prot = 2; // OK ( within class )
// priv = 3; // ERROR : private members of Base never inherited
}
};

class PrivDerived : private Base {


// pub -> private ( only this class can access )
// prot -> private ( only this class can access )
// priv -> NOT accessible
void test () {
pub = 1; // OK ( but private to PrivDerived )
prot = 2; // OK ( but private to PrivDerived )
}
};

int main () {
PubDerived pd ;
pd . pub = 10; // OK : public
// pd . prot = 20; // ERROR : protected

PrivDerived pvd ;
// pvd . pub = 10; // ERROR : now private !
return 0;
}

ES203 – OOP Using C++ Module III: Inheritance 11 / 22


Abstract Classes — The Incomplete Blueprint
An abstract class is a class that: class Shape { // Abstract class
public :
Contains at least one pure virtual function // Pure virtual function
// (= 0 means " no im plemen tation ")
Cannot be instantiated (no objects) virtual double area () = 0;
Serves as a base class only
void describe () {
Forces derived classes to implement the pure virtual function cout « " I am a shape "
« endl ;
}
};

Analogy class Circle : public Shape {


double r ;
An abstract class is like the concept of “Vehicle” — you can’t drive a public :
“Vehicle” in general. You need a specific car, bike, or truck! Circle ( double r ) : r ( r ) {}
// MUST implement area () !
“Vehicle” is abstract; “Toyota Camry” is concrete. double area () override {
return 3.14159 * r * r ;
}
};

int main () {
// Shape s ; // ERROR ! Abstract !
Circle c (5) ;
cout « c . area () ; // 78.54
return 0;
}

ES203 – OOP Using C++ Module III: Inheritance 12 / 22


The Diamond Problem — Ambiguity in Hybrid Inheritance

Person
The Ambiguity
If Person has a member name, then TA has two copies of name:
Student::name
Student Employee
Employee::name

When you write [Link], the compiler doesn’t know which one!
TA
Two solutions:
The “Diamond” shape! 1 Scope Resolution: [Link]::name
2 Virtual Base Class: Only one copy of Person! (the real fix)
TA gets TWO copies of Person’s members — one through
Student, one through Employee.

ES203 – OOP Using C++ Module III: Inheritance 13 / 22


Solution 1: Scope Resolution for Ambiguity
class Person {
public :
string name ;
void display () { cout « " Person : " « name « endl ; }
};

class Student : public Person {


public :
int roll ;
};

class Employee : public Person {


public :
int empId ;
};

class TA : public Student , public Employee {


public :
string subject ;
};

int main () {
TA ta ;
// ta . name = " Amit "; // ERROR : ambiguous !
ta . Student :: name = " Amit " ; // OK : specify the path
ta . Employee :: name = " Amit " ; // This is a DIFFERENT copy !

ta . Student :: display () ; // Person : Amit ( via Student )


ta . Employee :: display () ; // Person : Amit ( via Employee )
return 0;
}

This works but is ugly and wasteful — we have TWO copies of name! Better solution next...

ES203 – OOP Using C++ Module III: Inheritance 14 / 22


Solution 2: Virtual Base Class (The Real Fix!)
class Person {
public :
string name ;
void display () { cout « " Person : " « name « endl ; }
};

// Use ’ virtual ’ keyword when inheriting !


class Student : virtual public Person { // Virtual inheritance
public :
int roll ;
};

class Employee : virtual public Person { // Virtual inheritance


public :
int empId ;
};

class TA : public Student , public Employee {


public :
string subject ;
};

int main () {
TA ta ;
ta . name = " Amit " ; // No ambiguity ! Only ONE copy of Person !
ta . roll = 101;
ta . empId = 5001;
ta . display () ; // Person : Amit ( just one display () )
return 0;
}

virtual public Person tells the compiler: “No matter how many paths lead to Person, keep only ONE copy.”

ES203 – OOP Using C++ Module III: Inheritance 15 / 22


Aggregation vs Composition vs Classification (Inheritance)
Inheritance Composition Aggregation
(Classification / “is-a”) (“has-a”, strong ownership) (“has-a”, weak ownership)
Dog is-a Animal Car has-a Engine Department has-a Professor
Circle is-a Shape House has-a Room Team has-a Player
Child class is a type of parent class. If the container is destroyed, the contained is If the container is destroyed, the contained can
also destroyed. Engine can’t exist without the still exist. Professor survives if department
Car. closes.

When to Use What?


Inheritance: “Is this thing a type of that?” — Dog is a type of Animal ✓
Composition: “Does this thing own that, and they die together?” — Car owns Engine ✓
Aggregation: “Does this thing use that, but both can exist independently?” — Team uses Players ✓

ES203 – OOP Using C++ Module III: Inheritance 16 / 22


Composition & Aggregation in Code
class Engine { // COMPOSITION : Engine is PART of Car
int horsepower ;
public :
Engine ( int hp ) : horsepower ( hp ) {}
void start () { cout « " Engine ( " « horsepower « " HP ) started ! " « endl ; }
};

class Car {
string brand ;
Engine engine ; // Composition : Engine created WITH Car , dies WITH Car
public :
Car ( string b , int hp ) : brand ( b ) , engine ( hp ) {}
void start () {
cout « brand « " : " ;
engine . start () ;
}
};

// AGGREGATION : Professor exists independently of Department


class Professor {
public :
string name ;
Professor ( string n ) : name ( n ) {}
};

class Department {
string deptName ;
Professor * prof ; // Pointer = aggregation ( doesn ’t own the professor )
public :
Department ( string d , Professor * p ) : deptName ( d ) , prof ( p ) {}
void show () { cout « deptName « " -> " « prof - > name « endl ; }
};

ES203 – OOP Using C++ Module III: Inheritance 17 / 22


Overriding Inheritance Methods
Overriding = derived class provides its own implementation of a method that already exists in the base class.
class Animal {
public :
void speak () { // Base version
cout « " Some generic sound ... " « endl ;
}
};

class Cat : public Animal {


public :
void speak () { // OVERRIDES base version
cout « " Meow ! Meow ! " « endl ;
}
};

class Dog : public Animal {


public :
void speak () { // OVERRIDES base version
cout « " Woof ! Woof ! " « endl ;
}
};

int main () {
Animal a ; a . speak () ; // Some generic sound ...
Cat c ; c . speak () ; // Meow ! Meow !
Dog d ; d . speak () ; // Woof ! Woof !
return 0;
}

Overriding ̸= Overloading! Overriding: same name, same parameters, different class. Overloading: same name, different parameters, same class.

ES203 – OOP Using C++ Module III: Inheritance 18 / 22


Constructors in Derived Classes
When a derived class object is created: class Person {
string name ;
1 Base class constructor runs first public :
Person ( string n ) : name ( n ) {
2 Then derived class constructor runs cout « " Person : " « name
Destruction is in reverse order: }
« " created " « endl ;

~ Person () {
1 Derived destructor first cout « " Person : " « name
« " destroyed " « endl ;
2 Base destructor second }
};

class Student : public Person {


Analogy: Building a House int roll ;
public :
You build the foundation (base) first, then the floors (derived). // Pass argument to base !
Student ( string n , int r )
When demolishing, you remove floors first, then the foundation. : Person ( n ) , roll ( r ) {
cout « " Student roll "
« roll « " created "
« endl ;
}
~ Student () {
cout « " Student roll "
« roll « " destroyed "
« endl ;
}
};

int main () {
Student s ( " Amit " , 101) ;
}
// Person : Amit created
// Student roll 101 created
// Student roll 101 destroyed
// Person : Amit destroyed

ES203 – OOP Using C++ Module III: Inheritance 19 / 22


Constructor Order in Multiple Inheritance
class A {
public :
A () { cout « " A constructed " « endl ; }
~ A () { cout « " A destroyed " « endl ; }
};

class B {
public :
B () { cout « " B constructed " « endl ; }
~ B () { cout « " B destroyed " « endl ; }
};

class C : public A , public B { // A listed FIRST , then B


public :
C () { cout « " C constructed " « endl ; }
~ C () { cout « " C destroyed " « endl ; }
};

int main () {
C obj ;
return 0;
}
// Output :
// A constructed ( first base , in ORDER of listing )
// B constructed ( second base )
// C constructed ( derived )
// C destroyed ( reverse order !)
// B destroyed
// A destroyed

ES203 – OOP Using C++ Module III: Inheritance 20 / 22


Nesting of Classes — A Class Inside a Class
A nested class (or inner class) is a class defined inside another class.
# include < iostream >
using namespace std ;

class LinkedList {
public :
// NESTED CLASS : Node exists only in the context of LinkedList
class Node {
public :
int data ;
Node * next ;
Node ( int d ) : data ( d ) , next ( nullptr ) {}
};

private :
Node * head ;

public :
LinkedList () : head ( nullptr ) {}

void addFront ( int val ) {


Node * newNode = new Node ( val ) ;
newNode - > next = head ;
head = newNode ;
}

void display () {
Node * temp = head ;
while ( temp ) {
cout « temp - > data « " -> " ;
temp = temp - > next ;
}
cout « " NULL " « endl ;
}
};

int main () {
LinkedList list ;
list . addFront (30) ;
list . addFront (20) ;
list . addFront (10) ;
list . display () ; // 10 -> 20 -> 30 -> NULL

// Can also create Node independently ( since it ’s public ) :


LinkedList :: Node standalone (99) ;
return 0;
}

ES203 – OOP Using C++ Module III: Inheritance 21 / 22


Module III — Recap ✓
Topics Covered: 9 Aggregation vs Composition vs Classification
1 Inheritance fundamentals (is-a relationship) 10 Method Overriding
2 5 Types: Single, Multilevel, Multiple, Hierarchical, Hybrid 11 Constructor/Destructor order in inheritance
3 Access modes: public, protected, private 12 Passing args to base constructors
4 How access modes affect inherited members 13 Nested (inner) classes
5 Abstract classes & pure virtual functions
6 The Diamond Problem
7 Ambiguity resolution via scope resolution Coming Up: Module IV
8 Virtual Base Class Polymorphism! We’ll explore function overloading, operator overload-
ing, virtual functions, and pure virtual functions in depth.

ES203 – OOP Using C++ Module III: Inheritance 22 / 22

You might also like