Inheritance 2
Inheritance 2
• Inheritance is a relationship
• The class being inherited from is called the parent class, base class, or
superclass, and the class doing the inheriting is called the child class,
derived class, or subclass.
Inheritance
• A child class inherits both behaviors (member functions) and properties
(member variables) from the parent
• During inheritance, the data members of the base class get copied in the
derived class and can be accessed depending upon the visibility mode
used. The order of the accessibility is always in a decreasing order i.e.,
from public to protected.
• Inheritance allows programmers to create new classes built upon existing
ones, enabling code reuse and efficient software development.
Inheritance:is-a relationship
• A apple is a fruit
• A Banana is a fruit
• Triangle is a shape
• A car is a vehicle.
• Orange is a fruit.
• A surgeon is a doctor.
• A dog is an animal.
Syntax
Example
Access Specifiers in inheritance
• Private members, protected members are inaccessible outside of
the class.
• Private members of the base class cannot be used by the derived
class unless friend declarations within the base class explicitly
grant access to them.
• The protected members can be accessed within the class and
from the derived class.
Access Specifiers in inheritance
• The base class will contain data members and methods that are
common to all of the derived classes.
• Public members are accessible by all functions in the program
• Private members are accessible only by member functions and
friends of the base class.
• Protected members of a base class are accessible by members and
friends of the base class AND by members and friends of the derived
classes
C++ protected Access Specifier
Example: Area of Rectangle using inheritance
• Class definition
• Derived Class definition
• Main function
(i) Class Definition
(ii) Derived Class definition
Types of Inheritance
• Single Inheritance
• Multilevel Inheritance
• Multiple Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
Single Inheritance
• When the derived class inherits only one base class, it is known
as Single Inheritance.
Example of Single Inheritance:
Example of Single Inheritance:
• Base is the class name and the parent class, which contains the
property named salary and the value 900.
• Another class named Derived, which is the child class, which inherits
the property of the parent class and has its property named as a bonus
which contains the value of 100.
• In the child class, there is a function named sum(), which is used to add
the salary and bonus. In the main function, an object is created named
“x” of the “Derived” class which is a child class, and using that object,
the properties, and the sum function are called from the derived class,
which will add the salary and bonus and gives it as output.
Multiple Inheritance in C++