0% found this document useful (0 votes)
23 views290 pages

Inheritance Batch Final

The document covers the concept of constructors and destructors in C++, detailing types of constructors including default, parameterized, copy, and dynamic constructors. It explains the characteristics and uses of these constructors, along with examples of their implementation and constructor overloading. Additionally, it discusses inheritance in C++ and provides real-life examples of how these concepts are applied.

Uploaded by

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

Inheritance Batch Final

The document covers the concept of constructors and destructors in C++, detailing types of constructors including default, parameterized, copy, and dynamic constructors. It explains the characteristics and uses of these constructors, along with examples of their implementation and constructor overloading. Additionally, it discusses inheritance in C++ and provides real-life examples of how these concepts are applied.

Uploaded by

22e120
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 290

19E604-DATA STRUCTURES USING C++

INHERITANCE IN C++

22E104 AKALYA P
22E117 GANASRI R
22E124 JANANI E

DEPARTMENT OF ELECTRICAL AND ELECTRONICS


ENGINEEIRNG

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

• Constructor is a member function(a special function)


• The constructor in C++ has the same name as the class
or structure
• It is invoked automatically when an object is created
• The purpose of the constructor is to initialize the data
member of the object
• It constructs the values i.e. provides data for the object
that is why it is known as constructor.
• Constructor do not have a return type

5
NEED FOR CONSTRUCTORS

WITHOUT CONSTRUCTORS WITH 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:

• SYNTAX FOR DEFINING OUTSIDE:

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
}

Output : The value of x,y is 0 0


9
CONSTRUCTORS EXAMPLE 3
class Multiply {
int a, b;
public:
Multiply() { a and b are private members
a = 0; of a class
b = 0; }
void display() {
cout << "The value of a and b is " << a << " " << b << endl;
}};
int main() {
Multiply m1;
cout << "The value of a and b is " << m1.a << " " << m1.b;
return 0;
}
Output : compilation error

10
CHARACTERISTICS OF CONSTRUCTORS

● The name of the constructor is the same as its class name.


● Constructors are mostly declared in the public section of the class though it can
be declared in the private section of the class.
● Constructors do not return values; hence they do not have a return type.
● A constructor gets called automatically when we create the object of the class.

11
TYPES OF CONSTRUCTORS

1. Default constructor/ Non-Arg constructor


2. Parameterized constructor
3. Copy constructors
4. Dynamic constructors

12
1.DEFAULT CONSTRUCTOR/ NON-ARG CONSTRUCTOR

• A constructor which does not receive any parameters is called a Default


Constructor or a Zero Argument Constructor.
• Every class object is initialized with the same set of values in the default
constructor.
• Even if a constructor is not defined explicitly, the compiler will provide a default
constructor implicitly.
• The default constructor for class A will be A : : A ( )

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

In example beside, we have not


defined any constructor, so compiler
will provide an empty body
constructor to the class, which is
called as default constructor.

15
DEFAULT CONSTRUCTOR EXAMPLE 3

class Employee { ● In the example, the


public:
int age; constructor is not defined.
// Default constructor not defined.
// Compiler calls default constructor. ● So the compiler creates a
};
default constructor and
int main() { initialize the age value to
Employee e1;
cout << e1.age; 0 by default.
return 0;
}

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

• Using the default constructor, it is impossible to initialize different objects


with different initial values.
• What if we need to pass arguments to constructors which are needed to
initialize an object?
• There is a different type of constructor called Parameterized Constructor
to solve this issue.

20
USES OF PARAMETERISED CONSTRUCTORS

• It is used to initialize the various data elements of different objects with


different values when they are created.
• It is used to overload constructors.

21
PARAMETERISED CONSTRUCTOR EXAMPLE 1

class Employee { int main() { Output:


Employee c1(40); 40
public:
Employee c2(30); 30
int age; Employee c3(50); 50
Employee(int x) {
cout << c1.age << "\n";
age = x;
cout << c2.age << "\n";
} cout << c3.age << "\n";
}; return 0;
}

22
PARAMETERISED CONSTRUCTOR EXAMPLE 2

class Point { int main() Output:


{ p1.x=10
public:
// Constructor called p1.y=15
int x,y; Point p1(10, 15);
Point(int x1, int y1)
cout << "p1.x = " <<p1.x;
{ cout<< ", p1.y = " << p1.y;
x = x1;
return 0;
y = y1; }
}
};

23
PARAMETERISED CONSTRUCTOR EXAMPLE 3

• Non-Arg (Default) constructor,which takes no


arguments
• Parameterized constructor, which takes 1 arguments as
radius.
• When a constructor is parameterized we must pass the
arguments to the constructor function when an object
is declared.

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

1. Implicit call (shorthand method)


int main()
{
circle ob(7.6);
cout<<ob.radius;
}

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

class construct int main()


{ {
public: construct o;
float area; construct o2( 10, 20);
o.disp();
// Constructor with no parameters o2.disp();
construct() return 1;
{ area = 0; }
}
// Constructor with two parameters
construct(int a, int b)
OUTPUT:
{ area = a * b; } 0
200
void disp()
{ cout<< area<< endl; }
};
30
CONSTRUCTOR OVERLOADING EXAMPLE 2

class construct int main()


{ {
public: construct o;
float area; construct o2(10, 20);
o.disp();
o2.disp();
// Constructor with no parameters return 1;
construct() }
{ area = 0; }

// Constructor with two parameters


int construct(int a, int b)
{
area = a * b; OUTPUT:
} Error:
Constructors do not have a return type
void disp()
{
cout << area << endl;
}
}; 31
CONSTRUCTOR OVERLOADING EXAMPLE 3

class Person { // create person class int main()


public: {
int age; // data member Person person1, person2(45);
Person() cout<< "Person1 Age = " <<
{ age = 20; } person1.getAge() <<endl;

Person(int a) cout<< "Person2 Age = " <<

{ age = a; } person2.getAge() <<endl;

intgetAge() return 0; OUTPUT:


} Person1 Age = 20
{ return age; }
Person2 Age = 45
};
32
CONSTRUCTOR OVERLOADING EXAMPLE 3

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

• A copy constructor is a member function that initializes an object using


another object of the same class.
• Copy constructor takes a reference to an object of the same class as an
argument.
• Whenever we define one or more non-default constructors (with parameters)
for a class, a default constructor (without parameters) should also be
explicitly defined as the compiler will not provide a default constructor in
this case.

34
SYNTAX

Class_name(const class_name &old_object);

Example:

class A
{
A(A &x) // copy constructor.
{ // copy constructor. }
};

35
COPY CONSTRUCTOR

• The process of initializing through a copy constructor is known as


copy initialization.
• A copy constructor is used to declare and initialize an object from another
object

36
TYPES OF COPY CONSTRUCTOR

• Default Copy constructor:

The compiler defines the default copy constructor. If the user


defines no copy constructor, compiler supplies its constructor.

• User Defined constructor:

The programmer defines the user-defined 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

class A A(A &i)


{ { x = i.x; }
public: int main()
int x; {
OUTPUT: 20
A(int a) A a1(20);
{ A a2(a1);
x=a; cout<<a2.x;
} return 0;
}; }

42
DYNAMIC CONSTRUCTORS

• When the allocation of memory is done dynamically (i.e., Memory is allocated


to variables at run-time of the program rather than at compile-time) using a
dynamic memory allocator new in a constructor, it is known as a Dynamic
constructor.
• By using this, we can dynamically initialize the objects.

43
DYNAMIC CONSTRUCTORS

• The constructors can also be used to allocate memory while creating


objects.
• This will enable the system to allocate the right amount of memory for each
object when the objects are not of the same size.
• The memory is created with the help of the new operator.

44
DYNAMIC CONSTRUCTORS EXAMPLE 1

class Employee { int main() {


int* due_projects; // Default constructor would be called.
Output:
public: Employee employee1 = Employee();
Due projects for
Employee() { cout << "Due projects for employee1:\n";
employee1:
// Allocating memory at run time. employee1.display();
0
due_projects = new int; return 0;
*due_projects = 0; }
}
void display() {
cout << *due_projects << endl;
}
};

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.

2. Ambiguity in Overloaded Functions


- Implicit constructors can create ambiguity when multiple overloaded functions are available.
- Solution: Mark constructors `explicit` to clarify function calls.

3. Shallow Copy Problem (Implicit Copy Constructor)


- Implicit copy constructors perform shallow copies, leading to issues with dynamic memory (e.g.,
double deletion).
- Solution: Define a custom copy constructor for deep copies.

48
Implicit VS Implicit copy constructor

Feature Implicit Constructor Implicit Copy Constructor

A constructor invoked A constructor automatically


Definition automatically or implicitly for provided by the compiler for
type conversion. copying an object.

Allows creation of objects with Creates a copy of an existing


Purpose
implicit type conversion. object.

Provided by No, unless you define it (with or


Yes, automatically generated.
Compiler without explicit).

Example Number n1 = 5; Number n2 = n1;

Potential Shallow copies for dynamic


Unintended conversions.
Issues resources.

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

Calling Constructors Within a Class


● Constructor chaining allows one constructor to call another constructor in the same
class using the this pointer.
● Purpose: Simplifies initialization logic, reduces redundancy, and improves
maintainability.
● Useful when multiple constructors share common initialization code.

51
class Person {
std::string name;
int age;

public: // Parameterized constructor


Person(const std::string& name, int age) : name(name), age(age) {}

// Default constructor calling the parameterized constructor


Person() : Person("Unknown", 0) {}

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 Three: If a class manages resources, you should explicitly define:


○ Copy Constructor
○ Copy Assignment Operator
○ Destructor

● Rule of Five (C++11): Extend Rule of Three to include:


4. Move Constructor
5. Move Assignment Operator

● Rule of Zero: Design classes using STL and RAII to avoid defining any of these
methods.

53
DESTRUCTORS

54
DESTRUCTOR

• Destructor is an instance member function which is invoked automatically


whenever an object is going to be destroyed.
• Meaning, a destructor is the last function that is going to be called before an
object is destroyed.
• Destructor has the same name as their class name preceded by a tilde (~) symbol.

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

class circle int main() { OUTPUT:


{ circle c1();
public: constructor called c1
cout<<”c1 radius: ”<<c1.radius;
Float radius; radius: 0
circle() return 0; Destructor called
{ }
cout<<”constructor called”<<endl;
radius=0;
}
~circle()
{
cout<<”destructor called”<<endl;
}
};
63
DESTRUCTOR EXAMPLE 6

int main() { OUTPUT:


class Rectangle Rectangle r1; // Correct way to
{ declare an object Error: Destructor should not
public: be manually called
int length; cout << "Length: " << r1.length <<
int breadth; endl;
Rectangle() // Constructor cout << "Breadth: " << r1.breadth
{ << endl;
cout << "Constructor called" << endl;
length = 0; r1.~Rectangle();
breadth = 0;
} return 0;
}
~Rectangle() // Destructor
{
cout << "Destructor called" << endl;
}
};

64
PROPERTIES OF DESTRUCTORS

• Destructor function is automatically invoked when the objects are


destroyed.
• It cannot be declared static or const.
• The destructor does not have arguments.
• It has no return type not even void.

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.

• This must be done to avoid memory leak

69
How to call destructors explicitly?

Destructor can also be called explicitly for an object. We


can call the destructors explicitly using the following
statement:

object_name.~class_name()

70
IS IT POSSIBLE TO CALL CONSTRUCTOR AND DESTRUCTOR
EXPLICITLY IN C++?

• A constructor is a special member function that is automatically called by the


compiler when an object is created and the destructor is also a special member
function that is also implicitly called by the compiler when the object goes out of
scope.

• Yes, it is possible to call special member functions explicitly by the programmer.

• 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"; }
};

int main() OUTPUT:


{
Test(); // Explicit call to constructor Constructor is executed

Test t; // local object Constructor is executed


t.~Test(); // Explicit call to destructor Destructor is executed
return 0; Destructor is executed
}
72
Memory Management and
Destructors
● Purpose: Destructors clean up resources to prevent memory leaks.
● Automatically called when an object goes out of scope or is explicitly
deleted.
● Particularly important when using dynamic memory allocation with
new

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.

Constructor helps to initialize the object of a Whereas destructor is used to destroy


1.
class. the instances.

It is declared as className( arguments if Whereas it is declared as ~ className(


2.
any ){Constructor’s Body }. no arguments ){ }.

Constructor can either accept arguments or


3. While it can’t have any arguments.
not.

A constructor is called when an instance or It is called while object of the class is


4.
object of a class is created. freed or deleted.

Constructor is used to allocate the memory While it is used to deallocate the


5.
to an instance or object. memory of an object of a class.
76
S. No. CONSTRUCTOR DESTRUCTOR

6. Constructor can be overloaded. While it can’t be overloaded.

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.

In a class, there can be multiple While in a class, there is always a


8.
constructors. single destructor.

There is a concept of copy constructor


While here, there is no copy destructor
9. which is used to initialize an object from
concept.
another object.

They are often called in reverse order


10. They are often called in successive order.
of constructor.

77
QUIZ 1:

1. When is a destructor called in C++?

a) When an object is created


b) When the constructor finishes execution
c) When the object goes out of scope
d) When the object is passed to a function
ANSWER : C

78
2. Which of the following will happen if a constructor is not defined in a
class?

a) The compiler automatically generates a default constructor


b) The program will fail to compile
c) The program will run with default values
d) None of the above
ANSWER : A

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?

#include<iostream>the using namespace std;

class Point {public:


ANSWER:
Point() { cout << "Normal Constructor called\n"; }
Point(const Point &t) { cout << "Copy constructor called\n"; } Normal Constructor called
}; Copy Constructor called
Copy Constructor called
int main(){ Normal Constructor called
Point *t1, *t2;
t1 = new Point();
t2 = new Point(*t1);
Point t3 = *t1;
Point t4;
t4 = t3;
return 0; 85
9.Which of the following is an example of a default constructor?

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.

● Inheritance is one of the most important features of Object-


Oriented Programming.

89
● Inheritance is a feature or a process in which, new classes are
created from the existing classes.

● The new class created is called “derived class” or “child


class” and the existing class is known as the “base class” or
“parent class”.

● The derived class now is said to be inherited from the base


class.

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:

● Why and when to use inheritance?


● Modes of Inheritance
● Types of Inheritance

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:

● Consider a group of vehicles.


● You need to create classes for Bus, Car, and Truck.
● The methods fuelAmount(), capacity(), applyBrakes() will be
the same for all three classes.
● If we create these classes avoiding inheritance then we have to
write all of these functions in each of the three classes.

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

● In the above program, the ‘Child’ class is publicly


inherited from the ‘Parent’ class so the public data
members of the class ‘Parent’ will also be inherited
by the class ‘Child’.

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

• Suppose, base class and derived class have member functions


with the same name and arguments.
• If we create an object of the derived class and try to access
that member function, the member function in the derived
class is invoked instead of the one in the base class.
• The member function of derived class overrides the member
function of base class.

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

Here, the same function print() is defined in both Base


and Derived classes. So, when we call print() from the Derived
object derived1, the print() from Derived is executed by
shadowing the function in Base.

129
Access Shadowed Function in C++

• To access the shadowed function of the base class, we use the


scope resolution operator :: .
• We can also access the shadowed function by using a pointer
of the base class to point to an object of the derived class and
then calling the function from that pointer.

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.

Explanation: In this example, the Child class is derived from


the Parent class. The Child class inherits the parent_data
member and parent_method() function from the Parent class.
However, the Child does not inherit the Parent class constructor,
destructor, and friend functions .
135
INHERITANCE EXAMPLE USING FRIEND
CLASS AND FRIEND FUNCTIONS
• Friend functions are those functions that have access to the
private, public and protected members of a class. A friend
function can be a member of another class or can be a global
function in C++.

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:

● A Mammal is an Animal (but an Animal might not be a Mammal)

● A Dog is a Mammal (but a Mammal might not be a Dog)

● A Poodle is a Dog (but a Dog might not be a Poodle)

139
Is-A Relationship - Example 1:

140
Here, the is-a relationship translates into inheritance.

● A Mammal is an Animal → Animal is the parent class and


Mammal is the child class → Mammal inherits from Animal
● A Dog is a Mammal → Mammal is the parent class and Dog
is the child class → Dog inherits from Mammal
● A Poodle is a Dog → Dog is the parent class and Poodle is
the child class → Poodle inherits from Dog

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

• In single inheritance, a class is allowed to inherit from only one


class. i.e. one subclass is inherited by one base class only.It is the
simplest among all the types of inheritance since it does not
include any kind of inheritance combination or different levels of
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

using namespace std; { private:

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;

cout << "Private cannot be accessed." << end1;

cout << "Protected = " << object1.getProt() << end1;

cout << "Public = “ << object1.getPub () << end1;

return 0;
}
170
Output:

171
Trying to Access Private Member from Base
#include <iostream> public:
using namespace std; int pub = 3;

class Base { // function to access private


private: member
int pvt = 1; int getPVT() {
return pvt;
protected: }
int prot = 2; };

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;

class Base { // function to access private


private: member
int pvt = 1; int getPVT() {
return pvt;
protected: }
int prot = 2; };

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;

class Base { // function to access private member


private: int getPVT() {
int pvt = 1; return pvt;
}
protected: };
int prot = 2;

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
}; };

class ProtectedDerived : int main() {


protected Base { ProtectedDerived object1;
public: cout << object1.getPrivate()
int getPrivate() { << endl;
return pvt; return 0;
} }

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?

a) All the data members are added


b) Only private members are added
c) Only public members are added
d) Only default data members are added

190
7.If a derived class object is created, which constructor is
called first?

a) Base class constructor


b) Derived class constructor
c) Depends on how we call the object
d) Not possible

Answer: a

191
8. Give the output of the following given program.

#include<iostream> using namespace std; //Single


Inheritance in C++ Programming
class father
{ public:
void house() { cout<<"Have own 2BHK House."<<endl; } };
class son:public father
{ public:
void car() { cout<<"Have own Audi Car."<<endl; } };
int main()
{ son o; o.house(); o.car(); return 0; }

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:
}

OUTPUT: Explanation: Try to access private members


of the base class.
Compile error
193
TYPES OF
INHERITANCE

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

//C++ program to explain


// multiple inheritance

#include <iostream>
using namespace std;

// first base class


class Vehicle {
public:
Vehicle() { cout << “ This is a vehicle \n”;}

199
//second base class
class FourWheeler {
public :
FourWheeler()
{
cout << “This is a 4 wheeler vehicle\n”;
};

//sub class derived from two base classes


class Car : public Vehicle, public FourWheeler {
};

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;
};

class C : public B, public A{ //note the order


public:
C() { cout<< ”C’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
};

class Mammal : public Animal {


public:
Mammal() {
Mammal Bird
cout << "Mammal" << endl;
}
};

class Bird : public Animal { Bat


public:
Bird() {
cout << "Bird" << endl;
}
};
204
class Bat : public Mammal, public Bird {
public:
Bat() {
cout << "Bat ." << endl;
}
};

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;
}
};

class Mammal : virtual public Animal {


public:
Mammal() {
cout << "Mammal" << endl;
}
};

class Bird : virtual public Animal {


public:
Bird() {
cout << "Bird" << endl;
}
}; 207
class Bat : public Mammal, public Bird {
public:
Bat() {
cout << "Bat ." << endl;
}
}; OUTPUT:

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.

// Base Class: Skill


class Skill {
protected:
string skillName;

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");

// Access functionality from both base classes


hero.getScore(); // Inherited from Player
hero.useSkill(); // Inherited from Skill

// Use Hero-specific functionality


hero.attack();

return 0;
}
OUTPUT:
Player Score: 100
Using skill: Fireball
Warrior is attacking with skill: Fireball

211
ADVANTAGES OF MULTIPLE INHERITANCE

• Enhanced code reusability through inheriting features from multiple


parent classes.

DISADVANTAGES 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.

Eg: Vehicle -> Car -> Sports car


Animal -> Herbivores -> Goat
213
3)Multilevel 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 derive_1 : public base // derived class from base class


{
public:
int y;
void readdata()
{
cout << "\nEnter value of y= "; cin >> у;
}
}; 217
class derive2 : public derive1 // derived from class derive1
{
private:
int z;
public:
void indata()
{ OUTPUT
cout «< ”\nEnter value of z= "; cin >> z;
}
void product()
Enter value of x = 2
{
cout << "\nProduct= " << × * y * z; Enter value of y = 3
}
};
int main() Enter value of z = 3
{
derive2 a; //object of derived class Product = 18
a. getdata();
a. readdata();
a. indata();
a-product(); //// Class Derive2 not directly inheriting base class but
return 0; it can access its functions(methods).
}
//end of program. 218
EXAMPLE 2 -MULTILEVEL INHERITANCE
#include <iostream>
using namespace std;
class A
{ public:
void display()
{ cout<<“Base class content.”;
}
};

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 B : public A B class content.


{
public: void display()
{ cout<<“B class content.”;
}

};

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 obj object of class c is defined in the main() function.

• When the display() function is called, display) in class A is executed. It's


because there is no display() function in class C and class в.

• 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).

• If display() function exists in c, the compiler overrides display() of class A


(because of member function overriding).

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.

2.Intermediate Class: TextBook


•Inherits from Book and adds the following:
•subject (string): Subject of the textbook.
•Constructor to initialize the subject along with book details.
•A method displayTextBookInfo() to display the subject along with book details.

3.Derived Class: ReferenceBook


•Inherits from TextBook and adds the following:
•edition (int): Edition of the reference book.
•Constructor to initialize the edition along with the textbook details.
•A method displayReferenceBookInfo() to display all details (book, subject, and
edition).
227
#include <iostream>
#include <string>
using namespace std;

// Base Class: Book


class Book {
protected:
string title;
string author;

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);

// Displaying ReferenceBook details


refBook.displayReferenceBookInfo();

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.

● There is one base class and multiple derived classes.

● Several other classes inherit the derived classes as well. Hierarchical


structures thus form a tree-like structure.

● Use case: When multiple classes share common functionality from a


single base class, but each has unique features.
Eg:
1.Carnivores, Omnivores, Herbivores class from ANIMAL class
2. Class bikes, cars, trucks from class Vehicles.
232
4)Hierarchical Inheritance

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 ; }
};

class B : public A // class b inheriting base class


{ public;
void product(){
cout<< “\nproduct = ”; << x * y ; }
};
class C : public A
{
public:
void sum()
{ OUTPUT:
cout << “\n Sum = “ << x +y;
}
Enter value of × and у: 10 20
};
Product= 200
int main() Enter value of × and у: 10 20
{ Sum= 30
B obj1;
C obj;
obj1.getdata();
obj1.product();
obj2.getdata();
obj2.sum();
return 0;
}

238
EXAMPLE 2 – HIERARCHICAL INHERITANCE

Class Shape

Class Rectangle Class Triangle

239
240
241
OUTPUT

Enter the length and breadth of a rectangle:


5 10
Area of the rectangle is : 50
Enter the base and height of the triangle:
10 20
Area of the triangle is : 100

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”;}
};

//first sub class


class Car : public Vehicle {};

// second sub class


class Bus : public Vehicle {};

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();
}
};

// Derived class: Mathematics


class Mathematics : public Course {
public:
void displayDetails() {
setDetails("Mathematics", 4);
displayBaseDetails();
}
};

// Derived class: Physics


class Physics : public Course {
public:
void displayDetails() {
setDetails("Physics", 5);
displayBaseDetails();
} 246
};
int main() {
// Objects of derived classes
ComputerScience csCourse;
Mathematics mathCourse;
Physics physicsCourse;
OUTPUT SAMPLE: Course Details:
// Display course details Course Name: Computer Science
cout << "Course Details:" << endl; Credits: 3
csCourse.displayDetails();
cout << endl; Course Name: Mathematics
Credits: 4
mathCourse.displayDetails();
cout << endl; Course Name: Physics
Credits: 5
physicsCourse.displayDetails();

return 0;
}

247
5)Hybrid Inheritance

● Hybrid Inheritance is implemented by combining more than one type of


inheritance.

● It is also called as Virtual Inheritance.

● For example: Combining Hierarchical inheritance and Multiple


Inheritance.
● Use Case: When combining multiple types of inheritance to create
complex relationships while avoiding redundancy.

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

// Show all courses


obj.showEnrolledCourses();
obj.showAddedCourses();

return 0;
} 260
6)Multipath Inheritance

● It is a special case of Hybrid and multiple Inheritance.

● A derived class with two base classes and these two base classes have one common
base class is called multipath inheritance.

● Ambiguity can arise in this type of inheritance.

● Use Case: When a derived class inherits multiple times from a common base class,
requiring virtual inheritance to prevent ambiguity.

261
MULTIPATH INHERITANCE

• Here class D is derived from class


B and C.
• Class B and C are child of class A.
• From the above two points,we
can say class D is indirectly
derived from class A.
EXAMPLE 1 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.

● If we need to access the data member of Class A through the object of


Class-D, we must specify the path from which a will be accessed,
whether it is from Class B or Class C, because compiler can’t differentiate
between two copies of Class A in Class-D.

265
Avoiding ambiguity using the scope resolution operator:

● Using the scope resolution operator we


can manually specify the path from
which data member a will be accessed,
as shown in statements 3 and 4, in the
previous example.

● Still, there are two copies of ClassA in


Class-D

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;
}
};

// Final derived class


class SeniorManager : public Manager, public TechnicalLead {
public:
SeniorManager(string name, int id) : Person(name), Employee(name, id),
Manager(name, id), TechnicalLead(name, id) {}
void oversee() {
cout << name << " is overseeing all operations." << 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

Single Inheritance A child class inherits from only one parent


class.

Multiple Inheritance A child class inherits from multiple parent


classes.

Hierarchical Inheritance Multiple child classes inherit from the


same parent class.

Multipath Inheritance A class inherits from a common ancestor


through multiple paths in the inheritance
hierarchy.

Hybrid Inheritance A combination of multiple inheritance and


hierarchical inheritance, involving complex
inheritance structures.

Multilevel Inheritance A chain of inheritance where a child class


inherits from a parent class, and then
another class inherits from that child class.
QUIZ
1. Which among the following best describes the Inheritance?
a) Copying the code already written
b) Using the code already written once
c) Using already defined functions in programming language
d) Using the data and functions into derived segment

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)

A. Base1 Base2 Derived


B. Derived
C. Compiler Dependent
D. Derived Base2 Base1

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

You might also like