Inheritance Batch Final
Inheritance Batch Final
INHERITANCE IN C++
22E104 AKALYA P
22E117 GANASRI R
22E124 JANANI E
1
CONTENTS:-
1. Constructors
a. Introduction
b. Need for Constructors
c. Characteristics
d. Types of Constructors
i. Default Constructors
ii. Parameterised Constructors
iii. Copy Constructors
iv. Dynamic Constructors
2. Destructors
2
CONTENTS:-
3. Inheritance
4. Types of Inheritance
1.Single inheritance
2.Multilevel inheritance
3.Multiple inheritance
4.Hierarchical inheritance
5.Hybrid inheritance
6. Multipath inheritance
5. Real life examples
3
CONSTRUCTORS
BY
AKALYA P
22E104
4
CONSTRUCTOR
5
NEED FOR CONSTRUCTORS
class Person{
class Person{
public:
public:
int age; int age;
}; Person(int a){
int main(){ age = a;
Person p1; }
p1.age=10; };
cout<<p1.age; int main(){
} Person p1(10);
cout<<p1.age;
}
Output:10 Output:10
6
SYNTAX FOR CONSTRUCTORS
• Constructors can be defined inside the class declaration or outside the class
declaration
• SYNTAX FOR DEFINING INSIDE:
7
CONSTRUCTORS EXAMPLE 1
Class sum
{
public: • Here for the class sum the
int x,y;
sum()
constructor sum is created and
{ declared as public
x=0; • So whenever a object of class
y=0;
}; sum is created, the data members
}; x, y are initialized to 0.
int main()
{
sum s1;
cout<<”The value of x, y is”<<x<<y;
}
Output : The value of x,y is 0 0 8
CONSTRUCTORS EXAMPLE 2
Class sum
{
public:
int x,y;
sum(); Constructor is to be declared as public
};
sum::sum() and defined outside the class.
{
x=0;
y=0;
};
int main()
{
sum s1;
cout<<”The value of x, y is ”<<s1.x<<s1.y
}
10
CHARACTERISTICS OF CONSTRUCTORS
11
TYPES OF CONSTRUCTORS
12
1.DEFAULT CONSTRUCTOR/ NON-ARG CONSTRUCTOR
13
DEFAULT CONSTRUCTOR EXAMPLE 1
class sample
class sample
{ {
int mark; int mark;
public :
public:
sample()
void average () How complier {
interprets
{ }
void average ()
..
{..}
} };
};
14
DEFAULT CONSTRUCTOR EXAMPLE 2
15
DEFAULT CONSTRUCTOR EXAMPLE 3
Output: 0
16
NON ARG TYPE CONSTRUCTOR EXAMPLE 4
class circle
•In the example behind the
{
float radius; constructor takes no argument
public: and simply initializes the radius
circle() to zero.
{
radius = 0; •Non-arg constructor is also
} called as default constructor.
};
int main(){
circle c1;
cout<<c1.radius;
}
Output: 0
17
NON ARG TYPE CONSTRUCTOR EXAMPLE 5
#include <iostream>
using namespace std;
class construct {
public:
int a, b; OUTPUT:
a:10
construct()
b:20
{ a = 10;
b = 20;
}
};
int main()
{ construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 1;
18
}
DEFAULT CONSTRUCTOR NON-ARG TYPE CONSTRUCTOR
• It is given by the compiler • It is given by the developer
class sample class sample
{ {
int a; int a;
public: public:
sample( )
sample( )
{
} { a =0;
void average () }
{ void average ()
.. {
} ..
}; }
};
19
PARAMETERISED CONSTRUCTORS
20
USES OF PARAMETERISED CONSTRUCTORS
21
PARAMETERISED CONSTRUCTOR EXAMPLE 1
22
PARAMETERISED CONSTRUCTOR EXAMPLE 2
23
PARAMETERISED CONSTRUCTOR EXAMPLE 3
24
PARAMETERISED CONSTRUCTOR EXAMPLE 4
#include <iostream> int main() {
using namespace std;
class Rectangle { Rectangle rect1(4, 5);
cout << "Area of Rectangle: " << rect1.area() << endl;
private:
return 0;
int width; }
int height;
public:
Rectangle(int w, int h) { OUTPUT:
Area of Rectangle : 20
width = w;
height = h;
}
int area() {
return width * height;
}
25
};
DEFAULT CONSTRUCTOR PARAMETERISED CONSTRUCTOR
26
TWO WAYS OF CALLING A CONSTRUCTOR:
EXAMPLE 1
Output: 7.6
27
TWO WAYS OF CALLING EXAMPLE 2
2. Explicit call:
int main()
{
circle ob;
ob = circle(7.6);
cout<<ob.radius;
}
Output: 7.6
28
CONSTRUCTOR OVERLOADING
• In C++, We can have more than one constructor in a class with same name, as
long as each has a different list of arguments.
• A constructor is called depending upon the number and type of arguments
passed.
• While creating the object, arguments must be passed to let compiler know,
which constructor needs to be called.
29
CONSTRUCTOR OVERLOADING EXAMPLE 1
int main()
#include <iostream>
{
using namespace std;
A obj1(10, 20);
class A {
A obj2(5);
public:
obj1.print();
int sum = 0;
obj2.print();
A() // default constructor with no argument
return 0;
A(int a, int x = 0) // parameterized constructor with
}
//one default argument
{ Output:
sum = a + x; Sum =30
} Sum =5
void print() { cout << "Sum =" << sum << endl; }
};
33
COPY CONSTRUCTOR
34
SYNTAX
Example:
class A
{
A(A &x) // copy constructor.
{ // copy constructor. }
};
35
COPY CONSTRUCTOR
36
TYPES OF COPY CONSTRUCTOR
37
#include<iostream>
using namespace std;
EXAMPLE 1 IMPLICIT COPY CONSTRUCTOR
class Sample
{ int id;
public:
void init(int x)
{ id=x; Output
} ID=10
void display() ID=10
{ cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();
Sample obj2(obj1); //or obj2=obj1;
obj2.display(); 38
EXAMPLE 2 EXPLICIT COPY CONSTRUCTOR
#include <iostream>
using namespace std;
class Sample int main()
{ int id; {
Sample obj1;
public:
obj1.init(10);
void init(int x)
obj1.display();
{ id=x; Sample obj2(obj1); copy constructor called
} obj2.display();
Sample(){} //default constructor with empty body return 0;
Sample(Sample &t) //copy constructor }
{ id=t.id;
}
void display() Output
{ ID=10
cout<<endl<<"ID="<<id;
ID=10
}
}; 39
COPY CONSTRUCTOR EXAMPLE 3
class add
{
Add a1;
int m, n ;
public : ● Would automatically invoke the first
add ( )
constructor and set both m and n of a1 to
{ m = 0 ; n = 0 ;}
zero.
add (int a, int b)
{m = a ; n = b ;}
Add a2(10,20);
add (add & i) ● Would call the second constructor which
{m = i.m ; n = i.n ;}
will initialize the data members m and n
};
of a2 to 10 and 20 respectively
40
class add Add a3(a2);
{ ● Would invoke the third constructor
int m, n ;
public : which copies the values of a2 into a3.
add ( ) ● The value of m will be 10 and n will be
{ m = 0 ; n = 0 ;}
20.
add (int a, int b) ● This type of constructor is called the
{m = a ; n = b ;}
“copy constructor”.
add (add & i) ● Constructor Overloading
{m = i.m ; n = i.n ;}
● More than one constructor function is
}; defined in a class
41
COPY CONSTRUCTOR EXAMPLE 4
42
DYNAMIC CONSTRUCTORS
43
DYNAMIC CONSTRUCTORS
44
DYNAMIC CONSTRUCTORS EXAMPLE 1
45
DYNAMIC CONSTRUCTORS EXAMPLE 2
class geeks {
int* p; int main() Output:
public: 123
{ // five objects will be created
geeks() 123
{ // for each object
123
p = new int[3]{ 1, 2, 3 };
for (int i = 0; i < 3; i++) // default constructor would be called 123
{ // and memory will be allocated 123
cout << p[i] << " ";
} // to array dynamically
cout << endl;
geeks* ptr = new geeks[5];
}
}; }
46
47
ISSUES
Implicit vs Explicit Constructor
1. Unintended Type Conversions
- Implicit constructors allow automatic type conversions, which can cause unexpected behavior.
- Solution: Use the `explicit` keyword to prevent unintended conversions.
48
Implicit VS Implicit copy constructor
49
Constructor Delegation
• Circular Delegation
- A constructor cannot delegate to itself directly or indirectly, leading to infinite
recursion and a compilation error.
• Increased Complexity
- Overusing delegation can make the code harder to understand, especially if
constructors are chaining excessively.
50
Constructor Chaining
51
class Person {
std::string name;
int age;
void display() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}};
int main() { OUTPUT: Name: Unknown, Age: 0
Person p1;
p1.display();
return 0;} 52
The Rule of Three/Five/Zero
● Rule of Zero: Design classes using STL and RAII to avoid defining any of these
methods.
53
DESTRUCTORS
54
DESTRUCTOR
55
• It is not possible to define more than one destructor.
• The destructor is the only way to destroy the object created by the
constructor.
• Destructor can-not be overloaded.
• Destructor neither requires any argument nor returns any value.
• It is automatically called when object goes out of scope.
• Destructor release memory space occupied by the objects created by
constructor.
56
• In destructor, objects are destroyed in the reverse of an object creation
• The thing is to be noted here, if the object is created by using new or the constructor
uses new to allocate memory which resides in the heap memory or the free store,
the destructor should use delete to free the memory.
• If we do not write any destructor then compiler will provide a zero argument
destructor with empty implementation and it is called as default destructor
57
SYNTAX
58
DESTRUCTOR EXAMPLE 1
OUTPUT:
59
DESTRUCTOR EXAMPLE 2
OUTPUT:
DESTRUCTOR EXAMPLE 3
OUTPUT:
61
DESTRUCTOR EXAMPLE 4
OUTPUT
62
DESTRUCTOR EXAMPLE 5
64
PROPERTIES OF DESTRUCTORS
65
• An object of a class with a Destructor cannot become a member of the
union.
• A destructor should be declared in the public section of the class.
• The programmer cannot access the address of destructor.
66
WHEN IS DESTRUCTOR CALLED?
A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called
67
CAN A DESTRUCTOR BE CALLED MORE THAN ONCE?
• No, there can be only one destructor in a class with classname preceded by ~, no
parameters and no return type.
• Once a destructor is invoked for an object, the object no longer exists; the
behavior is undefined if the destructor is invoked for an object whose lifetime
has ended.
• If the destructor for an automatic object is explicitly invoked, and the block is
subsequently left in a manner that would ordinarily invoke implicit destruction
of the object, the behavior is undefined.
68
WHEN DO WE NEED TO WRITE A USER-DEFINED DESTRUCTOR?
• If we do not write our own destructor in class, compiler creates a default destructor for us.
• The default destructor works fine unless we have dynamically allocated memory or
pointer in class.
• When a class contains a pointer to memory allocate in class, we should write a destructor
to release memory before the class instance is destroyed.
69
How to call destructors explicitly?
object_name.~class_name()
70
IS IT POSSIBLE TO CALL CONSTRUCTOR AND DESTRUCTOR
EXPLICITLY IN C++?
• When the constructor is called explicitly the compiler creates a nameless temporary
object and it is immediately destroyed. That’s why 2nd line in the output is called to
destructor.
71
EXAMPLE 1 EXPLICIT AND IMPLICIT CALL
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "Constructor is executed\n"; }
~Test() { cout << "Destructor is executed\n"; }
};
73
#include <iostream>
class String {
char* str;
public:
String(const char* input) {
str = new char[10]; // Allocate memory (fixed size for simplicity)
strcpy(str, input); // Copy string
}~String() {
delete[] str; // Release memory
std::cout << "Destructor called, memory released!" << std::endl;
} void display() {
std::cout << "String: " << str << std::endl; }}; OUTPUT:
int main() { String: Hello
String s("Hello"); Destructor called, memory
s.display(); released!
return 0; // Destructor is called here
} 74
CAN A DESTRUCTOR BE VIRTUAL?
Yes, In fact, it is always a good idea to make destructors virtual in base class
when we have a virtual function.
75
S.
CONSTRUCTOR DESTRUCTOR
No.
The constructor’s name is same as the class Here, its name is also same as the class
7.
name. name preceded by the tiled (~) operator.
77
QUIZ 1:
78
2. Which of the following will happen if a constructor is not defined in a
class?
79
3. A constructor with default arguments is called when no arguments are
provided during object creation.
True / False
ANSWER : TRUE
80
4. Can a destructor take arguments in C++?
a)Yes
b) No
c) Only in some cases
d) Yes, but only as pointers
ANSWER: B
81
5. For constructor overloading, each constructor must differ in
___________ and __________
a) Number of arguments and type of arguments
b) Number of arguments and return type
c) Return type and type of arguments
d) Return type and definition
ANSWER: A
82
6. What will be the output of the following C++ code?
#include <iostream> int main(int argc, char const *argv[])
#include <string> {
using namespace std; A obj;
obj.assign(5);
class A{
cout<<obj.return_value();
int a; }
public:
A(int i){
a = i;
}
void assign(int i){
a = i; ANSWER : ERROR
}
int return_value(){
return a;
} 83
7. What will happen if you manually call the destructor of an object in C++?
a) The destructor will be called again automatically
b) The program will crash
c) The destructor is called only once at the end of the scope
d) There is no effect
ANSWER : B
84
8. What is the output of the following program?
a) MyClass(int x) {}
b) b) MyClass() {}
c) c) MyClass() : x(0) {}
d) d) Both b and c
ANSWER:D
86
10. What is the output of the following program?
int main(){
#include <iostream> Point p1;
using namespace std; Point p2 = p1;
class Point cout << "x = " << p2.getX() << "
{int x, y; y = " << p2.getY();
public: return 0;
Point(int i = 0, int j = 0) { x = i; y = j; } }
int getX() { return x; }
OUTPUT:
int getY() { return y; } x=0 y=0
};
87
Inheritance
By
GANASRI R
22E117
88
Introduction
● The capability of a class to derive properties and characteristics
from another class is called Inheritance.
89
● Inheritance is a feature or a process in which, new classes are
created from the existing classes.
90
● When we say derived class inherits the base class, it means, the
derived class inherits all the properties of the base class, without
changing the properties of base class and may add new features
to its own.
● These new features in the derived class will not affect the base
class.
91
Example
Base Class (Animal): This class has a method eat() which
prints a message.
Derived Class (Dog): This class inherits from the Animal class
using the public keyword. It has its own method bark() in
addition to the inherited eat() method.
Main Function: An object of the Dog class is created. This
object can call both the eat() method (inherited from Animal)
and the bark() method (specific to Dog).
92
This example demonstrates how the Dog class inherits the
properties and behaviors of the Animal class, allowing for code
reuse and a hierarchical class structure.
93
The topic is divided into the following subtopics:
95
WHY AND WHEN TO USE INHERITANCE?
INHERITANCE EXAMPLE 1 :
If there are three sections A, B and C in a school, the classes
for these sections will have the same functions like students(),
timetable(), classteacher(),etc.Without inheritance, we will have
to define these functions in all three classes. Thus, writing the
same code thrice.
96
97
● You can clearly see that the above process results in duplication
of the same code 3 times.
● This increases the chances of error and data redundancy. To
avoid this type of situation, inheritance is used.
● If we create a class Classroom and write these three functions in
it and inherit the rest of the classes from the Classroom class,
then we can simply avoid the duplication of data and increase
re-usability.
98
99
INHERITANCE EXAMPLE 2:
100
WITHOUT INHERITANCE:
101
● You can clearly see that the above process results in duplication
of the same code 3 times.
● This increases the chances of error and data redundancy. To
avoid this type of situation, inheritance is used.
● If we create a class Vehicle and write these three functions in it
and inherit the rest of the classes from the Vehicle class, then
we can simply avoid the duplication of data and increase re-
usability.
102
WITH INHERITANCE
103
Inheritance Example 3
• Consider a group of chocolates.
• We need to create classes for milky bar, snickers, and KitKat.
• The methods are quantity(),price(),company() will be same
for all the three classes.
• If we avoid using inheritance for these three classes then we
have to write all of these functions in each of the three
classes.
104
Without Inheritance
105
• You can clearly see that the above process results in
duplication of the same code 3 times.
• This increases the chances of error and data redundancy. To
avoid this type of situation, inheritance is used.
• If we create a class Chocolates and write these three
functions in it and inherit the rest of the classes from the
Chocolates class, then we can simply avoid the duplication of
data and increase re-usability.
106
With Inheritance
107
ADVANTAGES:
• Code reusability.
• Avoiding code duplication.
• Improving code flexibility.
• Provide better code structure and management.
• Avoid possible code errors.
• Data hiding.
• Polymorphism.
• Overriding.
108
SYNTAX
Implementing inheritance in C++: For creating a sub-class that is
inherited from the base class we have to follow a syntax.
109
Where;
class - keyword to create a new class
derived_class_name - name of the new class, which will inherit
the base class
access-specifier - either of private, public or protected. If neither
is specified, PRIVATE is taken as default
base-class-name - name of the base class
110
Inheritance - Example 1 : C++ program to demonstrate implementation
of Inheritance
111
112
Output:
Child id is: 7
Parent id is: 91
113
Inheritance Example 2
#include <iostream> void sleep() {
using namespace std; cout << "I can sleep!" << endl;
// Base class };
class Animal { // Derived class
public: class Dog : public Animal{
void eat() { public:
cout << "I can eat!" << endl; void bark() {
} cout << "I can bark! Woof woof!"
<< endl;
114
}; return 0;
int main() { }
Dog myDog;
// Calling base class functions
myDog.eat();
myDog.sleep();
// Calling derived class function
myDog.bark();
115
Output :
I can eat!
I can sleep!
I can bark! Woof woof!
NOTE : The derived class inherits the features from the base
class and can have additional features of its own. And that will
not affect the base class.
116
Inheritance - Example 3:
117
Modes of Inheritance:
● There are 3 modes of inheritance.
1. Public Mode
2. Protected Mode
3. Private Mode
118
ACCESS SPECIFIERS
● Access specifiers define how the members (attributes and
methods) of a class can be accessed.
● In C++, there are three access specifiers:
➢ Public: members are accessible from outside the class
➢ Protected: members cannot be accessed from outside
the class, however, they can be accessed in inherited
classes.
➢ Private: members cannot be accessed (or viewed) from
outside the class.
119
● The table summarizes the above three modes and shows the
access specifier of the members of the base class in the subclass
when derived in public, protected and private modes.
120
ACCESS SPECIFIERS:
121
Public Mode: If we derive a subclass from a public base class. Then
the public member of the base class will become public in the derived
class and protected members of the base class will become protected
in the derived class.
Protected Mode: If we derive a subclass from a Protected base class.
Then both public members and protected members of the base class
will become protected in the derived class.
Private Mode: If we derive a subclass from a Private base class.
Then both public members and protected members of the base class
will become Private in the derived class.
122
Note: The private members in the base class cannot
be directly accessed in the derived class, while
protected members can be directly accessed.
123
Access Specifiers Inheritance – Example 1:
124
Inheritance - Example 2:
Output:
If you try to access a private member, an error occurs:
error: y is private 125
Note: A derived class doesn’t inherit access to
private data members. However, it does inherit a
full parent object, which contains any private
members which that class declares. All the public
and protected members of the base class are
inherited.
126
Member Function Overriding in Inheritance
127
Example
// C++ program to demonstrate class Derived public Base {public:
shadowing base class member function void print() {
#include <iostream> cout << "Derived Function" << endl;
using namespace std; }
class Base { };
public: int main()
void print() { {
cout << "Base Function" << endl; Derived derived1;
} derived1.print();
}; return 0;
128
Output
Derived Function
129
Access Shadowed Function in C++
130
// C++ program to access shadowed function public:
// in main() using the scope resolution void print() {
operator :: cout << "Derived Function" << endl;
}
#include <iostream> };
using namespace std;
int main() {
class Base { Derived derived1, derived2;
public: derived1.print();
void print() {
cout << "Base Function" << endl; // access print() function of the Base class
} derived2.Base::print();
};
return 0;
class Derived : public Base { }
131
Output
Derived Function
Base Function
132
INHERITANCE EXAMPLE USING
CONSTRUCTORS AND DESTRUCTORS
• Constructor enables an object to initialize itself at the time of
its creation. It is known as the automatic initialization of
objects.
• Destructor destroys the objects when they are no longer
required.
133
134
OUTPUT:
Parent class constructor called.
Parent data: 10
Child data: 20
This is a method in Parent class.
This is a method in Child class.
Parent class destructor called.
136
EXAMPLE:
Output:
137
When to Use Inheritance and When Not to use inheritance?
When To Use Inheritance (Is-A Relationship)
Consider the following classes:
● Animal
● Mammal
● Dog
● Poodle
138
Based on our general knowledge, we know that:
139
Is-A Relationship - Example 1:
140
Here, the is-a relationship translates into inheritance.
141
Is-A Relationship – Example 2:
142
When Not To Use Inheritance (Has-A Relationship)
The has-a relationship is often mistakenly interpreted as an
inheritance.
A "has-a" relationship implies that one class contains or is
composed of another class as a part or member.
Consider the following classes:
● Company
● Department
● Employee
143
Based on our general knowledge, we know
that:
● A Company has many Departments (but a Department is not
a Company)
● A Department has many Employees (but an Employee is not
a Department)
144
● Here, the has-a relationship does not translate into inheritance.
The Department should not inherit from Company, and
Employee should not inherit from Department.
● Here, notice that Department does not inherit from Company —
instead, a Company has an attribute departments which is a list
containing many Department objects. Similarly, Employee does
not inherit from Department. Instead, a Department has an
attribute employees — a list containing many Employee
objects.
145
Has-A Relationship - Example:
146
To summarize:
● The main advantage of inheritance is code re-usability.
● The access specifiers are three types:
➔ Public
➔ Private
➔ Protected
● If no access specifier is mentioned private is taken as default .
147
Types of Inheritance
1.Single inheritance
2.Multiple inheritance
3.Multilevel inheritance
4.Hierarchical inheritance
5.Hybrid inheritance
6.Multipath inheritance
148
1)Single Inheritance
149
150
151
Syntax:
class Base_Class
{
// class definition
};
class Derived_Class: acess_specifiers Base_Class
{
// class definition
};
int main()
{
Base_Class obj1;
Derived_Class obj2;
// code
}
152
Single Inheritance in public – Example 1:
Output:
This is a Vehicle
153
Single Inheritance in public – Example 2:
#include <iostream> class derive: public base //single derived class
int y;
class base //single base class
public :
{
void readdata()
public:
{
int x;
cout << “Enter the value of y = “; cin >> y;
void getdata()
}
{
void product()
cout << “Enter the value of x = “ ; cin >> x;
{
}
cout << “Product = “ << x * y;
}; } };
154
int main()
{
derive a; //object of derived class Output:
a.getdata();
a.readdata();
Enter the value of x = 3
a.product(); Enter the value of y = 4
return 0; Product = 12
} //end of program
155
Single Inheritance in public – Example 3:
OUTPUT:
I am an animal
I am a dog
156
Single Inheritance in public – Example 4:
157
158
Output:
Enter the Value of A= 3
Enter the Value of B= 5
Product of 3 * 5 = 15
159
Single Inheritance in public – Example 5:
160
161
Output:
Product of 4 * 5 = 20
162
163
In the protected visibility mode, the public and protected members of the base class
become protected while the private members remain private. So as a result, the public
and protected members of the base class are accessed only inside the derived class.
They will throw an error if you try to access them outside the derived class. Meanwhile,
the private member will remain inaccessible out of the base class.
The following code snippet illustrates how to apply the protected visibility mode in a
derived class in Single Inheritance:
class base_class_1
{
// data members
// member functions
};
class derived_class: protected base_class_1
{
// data members
// member functions
};
164
Single Inheritance in protected – Example 1:
165
Output :
Private cannot be accessed.
Protected = 2
Public =3
166
167
In the private visibility mode, all the access specifiers i.e., private, protected, and
the public become private. It means that you cannot access them outside of the class
in which they are defined. They can only be accessed through the member functions
of the same class. And since it cannot inherit the private members, these members
can also be not inherited further.
The following code snippet illustrates how to apply the private visibility mode in a
derived class in Single Inheritance:
class base_class_1
{
// data members
// member functions
};
class derived_class: private base_class_1
{
// data members
// member functions
168
• };
Single Inheritance in private – Example 1:
#include <iostream>
using namespace std; class PrivateDerived : private Base {
public:
class Base { // function to access protected member
private: from Base
int pvt = 1;
int getProt() {
protected: return prot:
int prot = 2; }
// function to access public member
public:
int getPub() {
int pub = 3;
return pub;
}
// function to access private member };
int getPVT() {
return pvt;
}
}; 169
int main() {
PrivateDerived object1;
return 0;
}
170
Output:
171
Trying to Access Private Member from Base
#include <iostream> public:
using namespace std; int pub = 3;
172
class ProtectedDerived : protected int getPub() {
Base { return pub;
public: }
// function to access protected };
member from Base
int getProt() { int main() {
return prot; ProtectedDerived object1;
} cout << "Private = " << object1.pvt
<< endl
// function to access public return 0;
member from Base }
173
The private member pvt is not accessible
directly outside the Base class, which causes a
compilation error. The correct way to access it
would be via the public member function
getPVT() from the Base class.
174
Trying to Access protected Member from
Outside the Derived Class
#include <iostream> public:
using namespace std; int pub = 3;
175
class ProtectedDerived : protected return pub;
Base { }
public: };
// function to access protected
member from Base
int main() {
int getProt() {
ProtectedDerived object1;
return prot;
cout << "Protected = " <<
} object1.prot << endl;
return 0;
// function to access public }
member from Base
int getPub() {
176
Since prot is a protected member of Base, and
ProtectedDerived inherits it as protected, prot is inaccessible
directly from outside the class, even though it is a derived
class object.
177
Trying to Access Public Member from Derived
Object in Protected Inheritance
#include <iostream> public:
using namespace std; int pub = 3;
178
class ProtectedDerived : protected return pub;
Base { }
public: };
// function to access protected
member from Base
int main() {
int getProt() {
ProtectedDerived object1;
return prot;
cout << "Public = " << object1.pub
} << endl;
return 0;
// function to access public }
member from Base
int getPub() {
179
In protected inheritance, members that were public in the
base class become protected in the derived class, which means
they are not accessible directly from objects of the derived
class.
180
Trying to Access Base Class Private Member
via Derived Class Method
#include <iostream>
using namespace std; public:
int pub = 3;
class Base {
private: // function to access private
int pvt = 1; member
int getPVT() {
protected: return pvt;
int prot = 2; }
181
}; };
182
The private member pvt is inaccessible directly within the
derived class unless accessed via a public function from
Base, like getPVT().
183
Errors :
•Direct access to private members of Base results in an error.
•Direct access to protected members of Base from outside
the derived class results in an error.
•Direct access to public members of Base in the derived class
results in an error due to protected inheritance.
•Accessing private members of Base directly within the
derived class results in an error, unless through a public getter
function.
184
QUIZ:
1. Which among the following can be used together in a single class?
a) Only private
b) Private and Protected together
c) Private and Public together
d) All three together
Answer: d
185
2.Which access specifier should be used so that all the parent class
members can be inherited and accessed from outside the class?
a) Private
b) Default or public
c) Protected or private
d) Public
186
3. If a class is derived privately from a base class then
______________________________
a) no members of the base class is inherited
b) all members are accessible by the derived class
c) all the members are inherited by the class but are hidden and cannot
be accessible
d) no derivation of the class gives an error
Answer: c
187
4. What is the difference between protected and private access
specifiers in inheritance?
a. private member is not inheritable and not accessible in derived class.
b. protected member is inheritable and also accessible in derived class.
c. Both are inheritable but private is accessible in the derived class.
d. Both are inheritable but protected is not accessible in the derived class.
Answer: b
188
5. The derivation of Child class from Base class is indicated by ____
symbol.
a. ::
b. :
c. ;
d. |
189
6.On which specifier’s data, does the size of a class’s
object depend?
190
7.If a derived class object is created, which constructor is
called first?
Answer: a
191
8. Give the output of the following given program.
Output
192
9. Give the output of the following given program.
#include<iostream>
void show()
using namespace std;
{
class Base
cout<<" data1 = "<<data1<<" data2 = "<<
{
}
private:
};
int data1, data2;
int main(void)
public:
{
Base(int a = 0, int b = 0): data1(a), data2(b)
Derived d;
{
d.show();
}
return 0;
};
class Derived: public Base
{
public:
}
JANANI E
22E124
Types of Inheritance
On the basis of the relationship between the derived class and the base class:
1.Single inheritance
2.Multiple inheritance
3.Multilevel inheritance
4.Hierarchical inheritance
5.Hybrid inheritance
6.Multipath inheritance
195
2)Multiple Inheritance
● Multiple Inheritance is a feature of C++ where a class can inherit from more than one
class. i.e one subclass is inherited from more than one base class.
● The constructors of inherited classes are called in the same order in which they are
inherited.
● Use Case:
When a class needs functionality from multiple sources.
Eg : Class representative
196
Multiple Inheritance
197
Multiple Inheritance Syntax
class subclass_name : access_mode base_class1, access_mode base_class2,...
{
// body of subclass
};
class B
{
… .. …
};
class C
{
… .. …
};
class A: public B, public C
{
… .. …
};
Here, the number of base classes will be separated by a comma (‘, ‘) and the access mode for every base class must be specified.
198
Example 1 – Multiple inheritance
#include <iostream>
using namespace std;
199
//second base class
class FourWheeler {
public :
FourWheeler()
{
cout << “This is a 4 wheeler vehicle\n”;
};
200
// main function
int main() Output
{
//Creating object of sub
This is a Vehicle
class will This is a 4 wheeler
//invoke the constructor
of base classes.
Vehicle
Car obj;
return 0;
}
201
Example 2 – Multiple inheritance
#include<iostream>
using namespace std;
class A{
public:
A() { cout<< ”A’s constructor called” << endl;
};
class B{
public:
B() { cout<< ”B’s constructor called” << endl;
};
int main()
{
C c;
return 0;
} 202
DIAMOND PROBLEM
• The diamond problem occurs when two super Animal
classes(Mammal and Bird) of a class have a
common base class(Animal).
Mammal Bird
• For example in the diagram, the Bat class gets
two copies of all attributes of Animal class.
This cause ambiguities.
Bat
203
Example 3 – Diamond Problem
#include <iostream>
using namespace std;
class Animal {
public:
Animal() {
cout << "Animal" << endl;
} Animal
};
int main() {
Bat bat;
return 0;
}
205
OUTPUT:-
Animal
Mammal
Animal
Bird
Bat
In the above program, Animal Is called two times. Destructor of Person will al so be called two
times when object ‘bat' is destructed. So object ”bat" has two copies of all members of animal, this
causes ambiguities. The solution to this problem is virtual keyword. We make the classes Mammal
and Bird as virtual base classes to avoid two copies of Animal' in Bat class.
206
SOLUTION FOR DIAMOND PROBLEM:-
#include <iostream>
using namespace std;
class Animal {
public:
Animal() {
cout << "Animal" << endl;
}
};
Animal
Mammal
int main() { Bird
Bat bat; Bat
return 0;
} Animal() is called one
208
Implementing a class hierarchy for a game.
•There is a Player class that provides a getScore method.
•There is a Skill class that provides a useSkill method.
•You need to create a Hero class that inherits from both Player and
Skill and provides additional functionality like attack.
public:
Skill(string skill) : skillName(skill) {}
void useSkill() {
cout << "Using skill: " << skillName << endl;
}
209
};
// Derived Class: Hero (inherits from both Player and Skill)
class Hero : public Player, public Skill {
private:
string heroName;
public:
Hero(string name, int initialScore, string skill)
: Player(initialScore), Skill(skill), heroName(name) {}
void attack() {
cout << heroName << " is attacking with skill: " << skillName << endl;
}
};
210
int main() {
// Create a Hero object
Hero hero("Warrior", 100, "Fireball");
return 0;
}
OUTPUT:
Player Score: 100
Using skill: Fireball
Warrior is attacking with skill: Fireball
211
ADVANTAGES OF MULTIPLE INHERITANCE
• Diamond Problem: Multiple inheritance can lead to the diamond problem, where ambiguity arises
if a subclass inherits from two classes that have a common ancestor. This can result in confusion and
complexities in method resolution.
3)Multilevel Inheritance
● In this type of inheritance, a derived class is created from another derived class.
● The multi-level inheritance includes the involvement of at least two or more than
two classes. One class inherits the features from a parent class and the newly
created sub-class becomes the base class for another new class.
Use Case:
Forms a linear chain of inheritance.
214
215
Multilevel inheritance Syntax
Class C
Class B
Class A
216
EXAMPLE 1 - MULTILEVEL INHERITANCE
#include <iostream>
using namespace std;
class base //single base class
{
public: Class base
int x;
void getdata()
{ Class derive_1
cout << "Enter value of x= "; cin >> ×;
}
}; Class derive_2
Class B : public A
{
};
Class C : public B
{
};
int main()
{
c obj;
obj.display();
return 0;
219
EXAMPLE 3 -MULTILEVEL INHERITANCE
#include <iostream>
using namespace std;
class A
{ public:
void display()
{ cout<<“Base class content.”;
}
OUTPUT :
};
};
Class C : public B
{
};
int main()
{
c obj;
obj.display();
return 0;
220
• In above program, class c is derived from class B (which is derived from base
class A).
• The compiler first looks for the display() function in class c. Since the function
doesn't exist there, it looks for the function in class B (as ( is derived from B).
• The function also doesn't exist in class B, so the compiler looks for it in class A
(as B is derived from A).
221
EXAMPLE 4 – MULTILEVEL INHERITANCE
Class Vehicle
Class Fourwheeler
Class Car
222
OUTPUT:
223
Example 4 – MULTILEVEL INHEIRTANCE
#include <iostream>
using namespace std;
class M
{
protected:
int m;
public:
void get_m(int);
};
class N: public M
{
protected:
int n;
public:
void get_n(int);
};
224
class P : public N
{
public:
void display(void);
};
void M :: get_m(int x)
{
m = x;
}
void N :: get_n(int y)
{
n = y;
}
void P :: display(void)
{
cout << “m = “ << m << “\n”;
cout << “n = “ << n << “\n”;
cout << “m*n = “ << m*n << “\n;
} 225
OUTPUT:
int main()
{
m = 10
P p;
n = 20
p.get_m(10); m*n = 200
p.get_n(20);
p.display();
return 0;
}
226
You are tasked with designing a library system using multilevel inheritance. The structure is as follows:
1.Base Class: Book
•Represents a general book with the following attributes and methods:
•title (string): Title of the book.
•author (string): Author of the book.
•Constructor to initialize these attributes.
•A method displayBookInfo() to display the book's details.
public:
Book(string t, string a) : title(t), author(a) {}
void displayBookInfo() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
}
};
228
// Intermediate Class: TextBook
class TextBook : public Book {
protected:
string subject;
public:
TextBook(string t, string a, string s) : Book(t, a), subject(s) {}
void displayTextBookInfo() {
displayBookInfo();
cout << "Subject: " << subject << endl;
}
};
229
// Derived Class: ReferenceBook
class ReferenceBook : public TextBook {
private:
int edition;
public:
ReferenceBook(string t, string a, string s, int e) : TextBook(t, a, s), edition(e) {}
void displayReferenceBookInfo() {
displayTextBookInfo();
cout << "Edition: " << edition << endl;
}
};
230
int main() {
// Creating a ReferenceBook object
ReferenceBook refBook("C++ Programming", "Bjarne Stroustrup",
"Programming", 4);
return 0;
}
OUTPUT:
Title: C++ Programming Author: Bjarne Stroustrup Subject: Programming Edition: 4
231
4)Hierarchical Inheritance
● In this type of inheritance, more than one subclass is inherited from a
single base class. i.e. more than one derived class is created from a
single base class.
233
234
SYNTAX HIERARCHCIAL INHERITANCE:
class A
{
// body of the class A. Class A
}
class B : public A
Class B Class C
{
// body of class B.
} Class D
class C : public A
{
// body of class c.
}
class D : public A
{
// body of class D.
} 235
236
EXAMPLE 1 – HIERARCHICAL INHEIRTANCE
#include <iostream>
using namespace std;
Class A
class A // single base class
{ public;
int x,y;
void getdata(){ Class B Class C
cout<< “\nEnter value of x and y:\n”; cin >>
x >> y ; }
};
238
EXAMPLE 2 – HIERARCHICAL INHERITANCE
Class Shape
239
240
241
OUTPUT
REMARKS
// shape length and height method is common to both shapes.
242
Example 3 – HIERARCHICAL INHERITANCE
#include <iostream>
using namespace std;
Class Vehicle
// base class
class Vehicle{
public:
Class Car Class Bus
vehicle() { cout<< “This is a vehicle\n”;}
};
243
Example 3 – HIERARCHICAL INHERITANCE
// main function
int main()
{ Output
Car obj1; This is a Vehicle
Bus obj2; This is a Vehicle
return 0;
}
244
University Course Hierarchy
You are tasked to design a class hierarchy for a university system. The base class is Course, and derived classes
include ComputerScience, Mathematics, and Physics. Each derived class should have a method to display the
course name and the number of credits.
#include <iostream>
using namespace std;
// Base class
class Course {
protected:
string courseName;
int credits;
public:
void setDetails(string name, int cr) {
courseName = name;
credits = cr; }
void displayBaseDetails() {
cout << "Course Name: " << courseName << endl;
cout << "Credits: " << credits << endl; }
}; 245
// Derived class: ComputerScience
class ComputerScience : public Course {
public:
void displayDetails() {
setDetails("Computer Science", 3);
displayBaseDetails();
}
};
return 0;
}
247
5)Hybrid Inheritance
248
5)Hybrid Inheritance
Hierarchical inheritance
Multiple inheritance
249
250
A
Single
B C
Multiple
251
EXAMPLE 1 – HYBRID INHERITANCE
Animal
Single
Dog Domestic
Multiple
Rocky
252
OUTPUT
OUTPUT:
This is an Animal that is Dog and Domestic
Name of the dog is Rocky!
int main()
{
Rocky mydog;
return 0
}
253
EXAMPLE 2 HYBRID INHERITANCE
A
Single
B C
Multiple
D
255
int main() OUTPUT:
{
D d; Enter the value of 'a' :
d.mul(); 5
return 0; Enter the value of 'b’ :
} 6
Enter the value of c is :
7
Multiplication of a,b,c is : 210
256
You are tasked to model an online education platform where:
•Person class represents a generic individual with basic attributes like name.
•Student class inherits from Person, with additional functionality like enrollCourse.
•Teacher class inherits from Person, with functionality like addCourse.
•StudentTeacher class combines both Student and Teacher, inheriting their
functionalities and allowing someone to both enroll in courses and teach courses.
#include <iostream>
#include <vector>
using namespace std;
// Base class
class Person {
protected:
string name;
public:
Person(string personName) : name(personName) {}
void showName() {
cout << "Name: " << name << endl;
}
}; 257
// Derived class 1
class Student : virtual public Person {
protected:
vector<string> enrolledCourses;
public:
Student(string studentName) : Person(studentName) {}
void enrollCourse(string course) {
enrolledCourses.push_back(course);
cout << name << " enrolled in " << course << endl;
}
void showEnrolledCourses() {
cout << name << "'s Enrolled Courses: ";
for (const string &course : enrolledCourses) {
cout << course << " ";
}
cout << endl;
}
};
258
// Derived class 2
class Teacher : virtual public Person {
protected:
vector<string> addedCourses;
public:
Teacher(string teacherName) : Person(teacherName) {}
void addCourse(string course) {
addedCourses.push_back(course);
cout << name << " added course " << course << endl;
}
void showAddedCourses() {
cout << name << "'s Added Courses: ";
for (const string &course : addedCourses) {
cout << course << " ";
}
cout << endl;
}
}; 259
// Hybrid class
class StudentTeacher : public Student, public Teacher {
public:
StudentTeacher(string name) : Person(name), Student(name), Teacher(name) {}
};
int main() {
StudentTeacher obj("Alex");
obj.showName();
OUTPUT:
// As a Student Name: Alex
obj.enrollCourse("Math"); Alex enrolled in Math
obj.enrollCourse("Science"); Alex enrolled in Science
Alex added course Physics
// As a Teacher Alex added course Chemistry
obj.addCourse("Physics"); Alex's Enrolled Courses: Math Science
obj.addCourse("Chemistry"); Alex's Added Courses: Physics Chemistry
return 0;
} 260
6)Multipath Inheritance
● A derived class with two base classes and these two base classes have one common
base class is called multipath inheritance.
● Use Case: When a derived class inherits multiple times from a common base class,
requiring virtual inheritance to prevent ambiguity.
261
MULTIPATH INHERITANCE
B C
263
264
● In the previous example, both Class B and Class C inherit Class A, they
both have a single copy of Class A.
● However Class D inherits both Class B and Class C, therefore Class D has
two copies of Class A, one from Class B and another from Class C.
265
Avoiding ambiguity using the scope resolution operator:
266
Avoiding ambiguity using the virtual base class:
Example 2
MULTIPATH
INHERITANCE
B C
267
According to the above example, Class-D
has only one copy of ClassA, therefore,
statement 4 will overwrite the value of a,
given in statement 3.
268
You are tasked to model an employee hierarchy where:
•Person class represents a generic individual with basic attributes like name.
•Employee class inherits from Person, with attributes like employeeID.
•Manager and TechnicalLead both inherit from Employee.
•SeniorManager inherits from both Manager and TechnicalLead, resolving ambiguity with virtual inheritance
#include <iostream>
using namespace std;
// Base class
class Person {
protected:
string name;
public:
Person(string personName) : name(personName) {}
void showName() {
cout << "Name: " << name << endl;
}
};
269
// Intermediate class
class Employee : virtual public Person {
protected:
int employeeID;
public:
Employee(string personName, int id) : Person(personName),
employeeID(id) {}
void showEmployeeID() {
cout << "Employee ID: " << employeeID << endl;
}
};
// Derived class 1
class Manager : virtual public Employee {
public:
Manager(string name, int id) : Person(name),
Employee(name, id) {}
void manageTeam() {
cout << name << " is managing the team." << endl;
}
};
270
// Derived class 2
class TechnicalLead : virtual public Employee {
public:
TechnicalLead(string name, int id) : Person(name), Employee(name, id) {}
void leadProject() {
cout << name << " is leading the project." << endl;
}
};
271
int main() {
SeniorManager obj("Sophia", 101);
obj.showName();
obj.showEmployeeID();
obj.manageTeam();
obj.leadProject();
obj.oversee();
return 0;
}
SAMPLE OUTPUT:
Name: Sophia
Employee ID: 101
Sophia is managing the team.
Sophia is leading the project.
Sophia is overseeing all operations.
272
INHERITANCES FLOWCHART
COMPARISION OF TYPES OF INHERITANCES
INHERITANCE TYPE DESCRIPTION
275
Answer: d
Explanation: It can only be indicated by using the data and functions that we use in
derived class, being provided by parent class. Copying code is nowhere similar to this
concept, also using the code already written is same as copying. Using already
defined functions is not inheritance as we are not adding any of our own features.
276
2. Which among the following best defines single level inheritance?
a) A class inheriting a derived class
b) A class inheriting a base class
c) A class inheriting a nested class
d) A class which gets inherited by 2 classes
277
Answer: b
Explanation: A class inheriting a base class defines single level inheritance.
Inheriting an already derived class makes it multilevel inheritance. And if base
class is inherited by 2 other classes, it is multiple inheritance.
278
3. Which among the following is correct for a hierarchical inheritance?
a) Two base classes can be used to be derived into one single class
b) Two or more classes can be derived into one class
c) One base class can be derived into other two derived classes or more
d) One base class can be derived into only 2 classes
279
Answer: c
Explanation: One base class can be derived into the other two derived
classes or more. If only one class gets derived by only 2 other classes, it is
also hierarchical inheritance, but it is not a mandatory condition, because
any number of derived classes can be there.
280
4. Which type of inheritance leads to diamond problem?
a) Single level
b) Multi-level
c) Multiple
d) Hierarchical
281
Answer: c
Explanation: When 2 or more classes inherit the same class using multiple
inheritance and then one more class inherits those two base classes, we get
a diamond like structure. Here, ambiguity arises when same function gets
derived into 2 base classes and finally to 3rd level class because same name
functions are being inherited.
282
5. class X, class Y and class Z are derived from class BASE. This is ______
inheritance.
A. Multiple
B. Multilevel
C. Hierarchical
D. Single
283
6)
A. Compiler Dependent
B. Base1 Base2 Derived
C. Base2 Base1 Derived
D. Compiler Error 284
6)
A. Compiler Dependent
B. Base1 Base2 Derived
C. Base2 Base1 Derived ANS: B
D. Compiler Error 285
#include <iostream>
#include <string.h>
7) using namespace std;
class Class1 {
public:
Class1() A) Class1 constructor called
{
cout << "Class1 constructor called " << endl;
} B) Class2 constructor called
}; Class1 constructor called
class Class2 : public Class1 {
public:
Class2() C) Class1 constructor called
{ Class2 constructor called
cout << "Class2 constructor called " << endl;
}
}; D) Class2 constructor called
int main()
{
Class2 OB; ANS : C
return 0;
}
286
8)
A. In find
B. In course
C. Compiler Error: Ambiguous call to
print()
D. None of the above
ANS: B
287
9)
ANS: D
288
10)
class B: public A
#include <iostream> {
#include <string> int a = 15;
using namespace std; public:
class A void print(){
{ cout<<a; A) 1510
float d; }
public: B) 1010
};
int a; C) 1515
void change(int i){ int main() D) 5110
a = i; {
}
void value_of_a(){
B b; ANS: A
b.change(10);
cout<<a; b.print();
} b.value_of_a(); This is because in C++, when you declare a
}; member with the same name in a derived
return 0; class, it hides any member with the same name
in the base class.
}
289
THANK YOU!
290