Inheritance
Inheritance
1
What Is Inheritance?
• Provides a way to create a new class from an
existing class
• The new class is a specialized version of the
existing class
2
Why and When to use Inheritance in C++?
5
Single Inheritance in C++:
• When the derived class inherits only one base
class, it is known as Single Inheritance.
6
The "is a" Relationship
• Inheritance establishes an "is a"
relationship between classes.
– A car is a vehicle
– A flower is a plant
– A football player is an athlete
7
Example
class Base {
public:
float salary = 900;
};
class Derived: public Base {
public:
float bonus = 100;
void sum() {
cout << "Your Total Salary is: " << (salary + bonus) << endl;
}
};
int main() {
// Creating an object of the derived class.
Derived x;
Your Salary is: 900
Your Bonus is: 100
// Gets the salary variable of Base class.
cout << "Your Salary is:" << x.salary << endl;
Your Total Salary is: 1000
// Gets the bonus variable of the Derived class.
cout << "Your Bonus is:" << x.bonus << endl;
x.sum();
return 0;
}
8
Example-02
#include <iostream>
void setHeight(int h) { // Access width and height using base class protected
height = h; members
} std::cout << "Width: " << rectangle.width << std::endl;
std::cout << "Height: " << rectangle.height << std::endl;
protected:
int width; // Calculate and print the area using the derived class method
int height; std::cout << "Area: " << rectangle.getArea() << std::endl;
};
// Derived class inheriting from Shape return 0;
class Rectangle : public Shape { }
public:
int getArea() {
return width * height;
}
}; 9
Class Task
• Create a C++ program with a base class Person and a
derived class Student using single inheritance.
• The Person class should store basic information such
as name and age, while the Student class, inheriting
from Person, should include details like student ID
and GPA. Implement constructors to initialize the
data and display functions to output the information.
Demonstrate the relationship by creating an object
of the Student class in the main function and
showcasing the details using class methods.
10
Inheritance – Terminology and Notation in
C++
• Base class (or parent) – inherited from
• Derived class (or child) – inherits from the base class
• Notation:
class Student // base class
{
. . .
};
class UnderGrad : public student
{ // derived class
. . .
};
CS1 -- Inheritance and Polymorphism 11
Back to the ‘is a’ Relationship
• An object of a derived class 'is a(n)' object of
the base class
• Example:
– an UnderGrad is a Student
– a Mammal is an Animal
• A derived object has all of the characteristics
of the base class
27
Multilevel Inheritance
Multilevel inheritance is a type of inheritance
where a class inherits from another class, which
in turn inherits from another class. This creates a
hierarchy of classes, with each class inheriting
properties and methods from its parent class. It
allows for the creation of more specialized
classes and promotes code reuse.
Animal Class:
Animal is the base class with properties like name and methods like eat() and sleep().
Mammal Class (inherits from Animal):
Mammal is derived from Animal and includes additional behaviors like giveBirth() and makeSound().
Bird Class (inherits from Animal):
Bird is derived from Animal and includes additional behaviors like layEggs() and fly().
Create a Dog Class (inherits from Mammal):
In the main program, instantiate an object of the Dog class, name it "Rex," and demonstrate its ability to
perform actions inherited from the various classes in the hierarchy.
36
#include<iostream>
using namespace std;
Example
class base{
public:
base(){
cout<<"Base class"; }
};
class childA:public base {
public:
childA(){
cout<<" Child A"; }
};
class childB:public base {
public:
childB(){
cout<<" Child B";
}
};
int main(){
childA obja;
cout<<"\n";
childB objb;
}
Example-02
38
Class Task
You are developing a library management system in C++. The system should handle
information about various types of materials, including books and DVDs. Both books
and DVDs have common attributes such as a title, author/director, and publication
year. However, they also have specific attributes unique to each type.
Design a base class called Material that includes common attributes and methods for
both books and DVDs. Ensure that it has a constructor to initialize common attributes.
Create two derived classes, Book and DVD, which inherit from the Material class. Each
derived class should have additional attributes specific to books and DVDs,
respectively.
Implement a function in each derived class that displays information about the
material. For example, the function in the Book class might display information like
title, author, publication year, and the number of pages, while the function in the DVD
class might display title, director, publication year, and duration.
In the main function, create instances of both the Book and DVD classes and
demonstrate the use of inheritance by calling the display function for each type of
material.
39
Multiple Inheritance in C++
• In C++ programming, a class can be derived
from more than one parents. When a class is
derived from two or more base classes, such
inheritance is called Multiple Inheritance.
Multiple Inheritance in C++ allow us to
combine the features of several existing
classes into a single class.
45
Ambiguity in Multiple Inheritance
• In multiple inheritance, a single class is
derived from two or more parent classes. So,
there may be a possibility that two or more
parents have same named member function.
If the object of child class needs to access one
of the same named member function then it
results in ambiguity. The compiler is confused
as method of which class to call on executing
the call statement.
CS1 -- Inheritance and Polymorphism 46
Ambiguity in Multiple Inheritance
54
Hybrid Inheritance
• Hybrid Inheritance is the combination of two
or more inheritances : single, multiple,
multilevel or hierarchical Inheritances.
57
Diamond problem
Output??
58
OUTPUT
59
How can this problem be solved?
60
61
Types of Inheritance
Type of Inheritance Definition Example
A derived class inherits from only class Animal { /* ... */ }; class Mammal :
Single Inheritance
one base class. public Animal { /* ... */ };
63
Single Inheritance-Questions
Type of Inheritance Example Home Task
1. How does single
inheritance help
maintain a clear and
simple class hierarchy?
2. In what situations is
single inheritance
preferable over multiple
inheritance?
3. Explain a real-world
cpp class Animal { /* ... */ }; scenario where single
Single Inheritance class Mammal : public inheritance is a suitable
Animal { /* ... */ }; design choice.
4. What challenges might
arise when using single
inheritance, and how
can they be addressed?
5. How does the base
class's functionality
contribute to the derived
class in a single
inheritance scenario? 64
Multiple Inheritance
1. Describe a scenario
where multiple
inheritance is beneficial
for code reuse.
2. What precautions
should be taken to
avoid ambiguity in
multiple inheritance?
3. How does multiple
cpp class Base1 { /* ... */ }; inheritance support the
class Base2 { /* ... */ }; class development of a
Multiple Inheritance
Derived : public Base1, diverse class hierarchy?
public Base2 { /* ... */ }; 4. Explain a situation
where multiple
inheritance might lead
to complex relationships
between classes.
5. What are the
advantages and
challenges of using
multiple inheritance in
software design?
65
Hierarchical Inheritance
1. Provide an example of a
real-world scenario where
multilevel inheritance
accurately models
relationships. 2. How does
multilevel inheritance
contribute to the organization
and structure of a program? 3.
cpp class Animal { /* ... */ };
Discuss the impact of changes
class Mammal : public Animal {
Multilevel Inheritance in the base class on derived
/* ... */ }; class Dog : public
classes in multilevel
Mammal { /* ... */ };
inheritance. 4. What
challenges may arise when
implementing multilevel
inheritance, and how can they
be addressed? 5. Explain the
advantages of using multilevel
inheritance for code readability
and maintenance.
69
Classes in the Hospital Management System:
Person Class:
Attributes: name, age
Methods: displayDetails()
Explanation: The Person class serves as the base class for both doctors and patients. It encapsulates common
attributes like name and age. The displayDetails() method can be overridden in derived classes to show specific
details for doctors and patients.
Doctor Class (Derived from Person):
72
Classes in the Online Shopping System:
Product Class (Base Class):
Attributes: productId, productName, price
Methods: displayDetails()
Explanation: The Product class is the base class for all products. It encapsulates common attributes such as
productId, productName, and price. The displayDetails() method can be overridden in derived classes to show
specific details for each product category.
Electronics Class (Derived from Product):
Additional Attributes: brand, warrantyPeriod
Additional Methods: checkWarranty(), displayDetails()
Explanation: The Electronics class inherits from the Product class and adds attributes like brand and
warrantyPeriod. It includes methods specific to electronics, such as checking the warranty period and displaying
details.
Clothing Class (Derived from Product):
Additional Attributes: size, material
Additional Methods: getSizeAvailability(), displayDetails()
Explanation: The Clothing class inherits from the Product class and adds attributes like size and material. It
includes methods specific to clothing, such as checking size availability and displaying details.
Books Class (Derived from Product):
Additional Attributes: author, genre
Additional Methods: getAuthorDetails(), displayDetails()
Explanation: The Books class inherits from the Product class and adds attributes like author and genre. It
includes methods specific to books, such as fetching author details and displaying book details.