4th Chapter Inheritance C++
4th Chapter Inheritance C++
4th Chapter Inheritance C++
Inheritance
Inheritance is a process by which new classes called derived classes are created from existing classes
called base classes.The derived classes have all the features of the base class and the programmer can
choose to add new features specific to the newly created derived class.
General syntax:
1
Derived class visibility
Base class visibility
Public derivation Private derivation Protected derivation
Visibility mode
Private mode
When a base class is inherited by a derived class in private mode,public and protected members of base
class and therefore they are accessible only within derived class i.e the public and protected members
in base class act as private members for the derived class.The private members of the base class are not
inherited in derived class.
Public mode
When a base class is inherited by derived class in public mode,public members of base class becomes
public members for the derived class and protected members of the base class become protected
members for derived class.The private members of the base class are note inherited in derived class.
Protected mode
When a base class is inherited by derived class in protected mode,the public and protected members in
the base class become protected members for the derived class.The private members of the base class
are not inherited in derived class.
2
Types of inheritance
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
1.Single inheritance
When a single class is being inherited by a class,it is called single or simple inheritance.In other words,a
derived class with only one base class is called single inheritance.single inheritance is an ability of a
derived class to inherit the member functions and variables of the existing class.A derived class is
defined as following.
Syntax:
Class body
};
Class B
derived class
General form
Class A
{
……….
};
Class B:public A
{
}
Example1
3
#include<iostream>
using namespace std;
class person
{
protected:
char name[20];
int age;
public:
void readpersondata(){
cout<<"enter name";
cin>>name;
cout<<"enter age:";
cin>>age;
}
void displaypersondata(){
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
}
};
class employee:public person
{
private:
char designation[20];
float salary;
public:
void reademployeedata(){
readpersondata();
cout<<"enter designation:";
cin>>designation;
cout<<"enter salary:";
cin>>salary;
}
void displayemployeedata(){
cout<<"the record of employee is:\n";
displaypersondata();
cout<<"designation:"<<designation<<endl;
cout<<"salary:"<<salary<<endl;
}
};
int main(){
employee emp;
4
emp.reademployeedata();
emp.displayemployeedata();
return 0;
}
Example 2
#include<iostream>
using namespace std;
class A
{
int x;
protected:
int y;
public:
int z;
void getxyz(){
cout<<"enter value of x,y,z"<<endl;
cin>>x>>y>>z;
}
void showxyz()
{
cout<<"x="<<x<<"y="<<y<<"z="<<z<<endl;
}
};
class b:public A
{
private:
int k,sum;
public:
void get_k()
{
cout<<"enter value of k"<<endl;
cin>>k;
}
void show_k(){
cout<<"k="<<k<<endl;
}
void addition(){
sum =y+z+k;
}
void display(){
5
cout<<"sum =" <<sum<<endl;
}
};
int main(){
b b1;
b1.getxyz();
b1.get_k();
b1.show_k();
b1.addition();
b1.display();
return 0;
}
2.Multiple inheritance
It is a type of inheritance in which new class is created from more than one base class.In this type of
inheritance a single derived class uses behaviour of two base classes.
Syntax
Class A{
………………
Class B
………….
};
…………….
6
Base class B Base class
A
C
Derived class
All data members in protected and public of class A and B can be accessed using object of classs C.here
two base classes A and B have been created and derived class c is created from both base classes.
Example
#include<iostream>
using namespace std;
class academicactivities{
protected:
float acd_total_marks;
public:
void readacdmarks(){
cout<<"enter total marks in exam";
cin>>acd_total_marks;
}
void displayacdmarks(){
cout<<"total academic mark is:"<<acd_total_marks<<endl;
}
};
class extraactivities
{
protected:
float discipline_marks;
float punctuality_marks;
public:
void readextramarks(){
cout<<"enter marks in discipline";
cin>>discipline_marks;
cout<<"enter marks in punctuality:";
cin>>punctuality_marks;
}
7
void displayextramarks(){
cout<<"marks in discipline:"<<discipline_marks<<endl;
cout<<"marks in punctuality:"<<punctuality_marks;
}
};
class result:public extraactivities,public academicactivities
{
float total_marks;
public:
void calculateresult(){
total_marks = acd_total_marks+discipline_marks +punctuality_marks;
}
void displayresult()
{displayacdmarks();
displayextramarks();
cout<<endl<<"total marks:"<<total_marks;
}
};
int main(){
result r;
r.readacdmarks();
r.readextramarks();
r.calculateresult();
cout<<endl<<"your record is"<<endl;
r.displayresult();
return 0;
}
8
Ambiguity in multiple inheritance
When two or more than two base classes have a function of identical name and when class inherits
from multiple base classes then ambiguity occurs.
Example
#include<iostream>
class m
{
public:
void display()
{
cout<<" class m"<<endl;
}
};
class n{
public:
void display(){
cout<<"class n"<<endl;
}
};
int main(){
p p;
p.display();
return 0;
}
which display function is used by the derived class when we inherit these two classes?
we can solve this problem by redefining the member in the derived class using resolution operator with
the function as shown below.
9
Ambiguity in single inheritance
#include<iostream>
class A
{public:
void display(){
cout<<"a"<<endl;
}
};
class B:public A{
public:
void display(){
cout<<"b"<<endl;
}
};
int main(){
B b;
b.display();
b.A::display();
b.B::display();
return 0;
In this case the function in the derived class overrides the inherited function and therefore a simple call
to display() by B type object will invoke function defined in B only.However,we may invoke the function
10
2.Multilevel inheritance
In multilevel inheritance a class is derived from another derived class.Thus base class of a derived class is
also derived of another base class.An example
A
Base class
B
Derived class
#include<iostream>
using namespace std;
class student{
private:
int roll;
public:
void getroll(){
cout<<"enter roll";
cin>>roll;
}
void displayroll(){
cout<<"roll:"<<roll<<endl;
}
};
class examination : public student{
protected: float subject1,subject2;
public:
void getmarks(){
cout<<"enter marks in first subject:";
cin>>subject1;
cout<<"enter marks in second subject:";
cin>>subject2;
}
11
void displaymarks(){
cout<<"marks in first subject:"<<subject1<<endl;
cout<<"marks in second subject:"<<subject2<<endl;
}
};
class result:public examination{
int total;
public:
void calculateresult(){
total = subject1 + subject2;
}
void displayresult(){
cout<<"total marks :"<<total;
}
};
int main(){
result r1;
r1.getroll();
r1.getmarks();
r1.calculateresult();
cout<<"-------record of student is-------"<<endl;
r1.displayroll();
r1.displaymarks();
r1.displayresult();
return 0;
}
4.Hierarchical inheritance
It is the process of deriving two or more classes form single base class.And in turn each of the derived
classes can further be inherited in same way.Thus it forms hierarchy of classes of a tree of classes which
is rooted at single class.
B C D
12
GENERAL FORM
Class A{
};
Class B:public A{
};
Class C:publc A{
};
Class D:Public A{
};
In general form three classes B and C and D are derived from same base class A.All data members in
protected and public of Class A can be accessed using object of classes B,C,D.
Example
#include<iostream>
using namespace std;
class person{
protected:
char name[20];
int age;
public:
void getperson(){
cout<<"enter name:";
cin>>name;
cout<<"enter age";
cin>>age;
}
void displayperson(){
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
}
};
class student:public person{
int roll;
float marks;
13
public:
void getstudent(){
cout<<"enter roll";
cin>>roll;
cout<<"enter total marks";
cin>>marks;
}
void displaystudent(){
cout<<"roll:"<<roll<<endl;
cout<<"total marks:"<<marks<<endl;
}
};
class employee:public person
{
char designation[20];
float salary;
public:
void getemployee(){
cout<<"enter designation:";
cin>>designation;
cout<<"enter salary";
cin>>salary;
}
void displayemployee()
{
cout<<"designation:"<<designation<<endl;
cout<<"salary:"<<salary<<endl;
}
};
int main(){
student s1;
cout<<"reading information of student"<<endl;
s1.getperson();
s1.getstudent();
cout<<"reading information of employee"<<endl;
employee e1;
e1.getperson();
e1.getemployee();
cout<<"displaying record of student"<<endl;
s1.displayperson();
s1.displaystudent();
cout<<"displaying record of employee"<<endl;
14
e1.displayperson();
e1.displayemployee();
return 0;
}
15
Hybrid inheritance
The use of more than one type of inheritance is called hybrid inheritance .It is used in such situations
where we need to apply two or more types of inheritance to design a program.
A Base class
D
Derived class from C
E
Derived class from D
#include<iostream>
using namespace std;
class person{
protected:
char name[20];
int age;
public:
void getperson(){
cout<<"enter name:";
cin>>name;
cout<<"enter age";
cin>>age;
}
void displayperson(){
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
}
};
class student:public person{
16
int roll;
public: void getstudent(){
cout<<"enter roll:";
cin>>roll;
}
void displaystudent(){
cout<<"roll:"<<roll<<endl;
}
};
class employee:public person{
char designation[20];
float salary;
public:
void getemployee(){
cout<<"enter designation:";
cin>>designation;
cout<<"enter salary:";
cin>>salary;
}
void displayemployee()
{
cout<<"designation:"<<designation<<endl;
cout<<"salary:"<<salary<<endl;
}
};
class examination:public student{
protected:
float theory_marks,lab_marks;
public:
void getmarksinsubjects(){
cout<<"enter marks of student in theory exam:";
cin>>theory_marks;
cout<<"enter marks of student in lab exam:";
cin>>lab_marks;
}
void displaymarks()
{
cout<<"marks in theory exam:"<<theory_marks<<endl;
cout<<"marks in lab exam:"<<lab_marks<<endl;
}
};
class result:public examination{
17
private:
float total_marks;
public:
void calculatetotalmarks(){
total_marks = theory_marks + lab_marks;}
void displayresult(){
cout<<"total_marks:"<<total_marks<<endl;
if(total_marks>32)
{
cout<<"congratulation"<<endl;}
else
{cout<<"sorry try again"<<endl;
}
}};
int main(){
result rs;
cout<<"reading information of student"<<endl;
rs.getperson();
rs.getstudent();
rs.getmarksinsubjects();
employee emp;
cout<<"reading information of employee"<<endl;
emp.getperson();
emp.getemployee();
cout<<"displaying record……………."<<endl;
cout<<"the record of student…."<<endl;
rs.displayperson();
rs.displaystudent();
rs.calculatetotalmarks();
rs.displaymarks();
rs.displayresult();
cout<<"******************"<<endl;
cout<<"the record of employee….."<<endl;
emp.displayperson();
emp.displayemployee();
return 0;
}
18
Using constructors and destructors in derived classes
The derived class need not have constructor as long as the base class need not have constructor
as long as the base class has no argument constructor.
However if the base class has constructor with arguments(one or more),then it is mandatory of
the derived class to have a constructor and pass the arguments to the base class constructor.
When an object of a derived class is created the constructor of the base class is executed first
and later the constructor of the derived class.
In case of multiple inheritance ,the base class is constructed in the same order in which header
appear in the declaration of the derived class.
Similarly in a multilevel inheritance,the constructor will be executed in the order of inheritance.
The header line of the derived-constructor function contains two parts separated by a colon(:).
The first part provides the declaration of the arguments that are passed to the derived class
constructor and the second part lists the function calls to the base class.
{
//body of derived constructor
}
Example
D(int a1,int a2,int b2,int d):A(a1,a2,),B(b1,b2)
{
d=d1;
}
#include<iostream>
Alpha Beta
using namespace std;
class alpha x y
{private:
int x;
public:
alpha(int i)
Gamma
{ x=i;
m, n
19
}
void show_x(){
cout<<"x="<<x<<endl;
}
};
class beta
{
private:
float y;
public:
beta(float j)
{
y =j;
}
void show_y(){
cout<<"y="<<y<<endl;
}
};
gamma g(5,7.6,30,100);
cout<<endl;
g.show_x();
g.show_y();
g.show_mn();
return 0;
}
20
Constructor in a multilevel inheritance
#include<iostream>
using namespace std;
class a
Alpha
{
public: Alpha(int nvalue)
a (int nvalue){
cout<<"a:"<<nvalue<<endl; show
}
};
class b: public a Beta
{
Beta(int nvalue, float
public: dvalue):a(nvalue)
b(int nvalue,float dvalue):a(nvalue)
{
cout<<"b:"<<dvalue<<endl;
}};
class c: public b{
public: Gamma
c(int nvalue,float dvalue,char chvalue):b(nvalue,dvalue)
{ Gamma(int
cout<<"c:"<<chvalue<<endl; ,float,char):b(nvalue,dval
}}; ue)
int main(){
c cclass(5,4.3,'r');
return 0;
}
21
Virtual base class in C++
Virtual classes are primarily used during multiple inheritance. To avoid, multiple instances of the same
class being taken to the same class which later causes ambiguity, virtual classes are used.
Class A
Class C
Class B
Class D
Consider the case where there is just one class A. Two other grades, B and C, descend from
this class A. The data members/functions of class A are inherited twice to class D, as seen in
the diagram. The first will take you through class B, and the second will take you through
class C. When an object of class D accesses any data or function member of class A, it's
unclear which data or function member would be named. One was inherited via B, and it
inherited the other via C. This throws the compiler into a loop and causes an error to
appear.
The duplication of inherited members due to these multiple paths can be avoided by
making common base class as virtual class while declaring the direct or intermediate base
classes.By making a class virtual only one copy of that class is inherited though we may
have many inheritance paths between the virtual base class and derived class.we can
speciy a base class inheritance by using the keyword virtual.
22
Constructor call in hybrid inheritance using virtual base classes.
college
Name,location
student teacher
Sname Tname
rol tcode
book
Bookname
Writername
bcode
23
#include<iostream>
#include<string.h>
class college{
string name,location;
public:
college(string a,string b)
name =a;
location=b;
void display(){
cout<<"name of college:"<<name<<endl;
cout<<"location of college:"<<location<<endl;
};
string sname;
int roll;
public:
{sname = c;
roll =d;
void display(){
24
cout<<"name of student:"<<sname<<endl;
cout<<"roll of student:"<<roll<<endl;
};
string tname;
int tcode;
public:
{ tname =c;
tcode = d;
void display(){
cout<<"name of teacher:"<<tname<<endl;
cout<<"code of teacher:"<<tcode<<endl;
};
string bookname;
string wname;
int bcode;
public:
book(string a,string b,string c,int d,string e,int t,string g ,string h,int i):student
(a,b,c,d),teacher(a,b,e,t),college(a,b){
bookname = g;
wname =h;
25
bcode =i;
void display(){
college::display();
student::display();
teacher::display();
cout<<"name of book:"<<bookname<<endl;
cout<<"code of book:"<<bcode<<endl;
cout<<"name of writer:"<<wname;
};
int main(){
b.display();
return 0;
#include<string.h>
class college{
string namecolg,location;
public:
college()
26
{
cin>>namecolg;
cin>>location;
void display(){
cout<<"name of college:"<<namecolg<<endl;
cout<<"location of college:"<<location<<endl;
};
string sname;
int roll;
public:
student():college(){
cin>>sname;
cin>>roll;
void display(){
27
cout<<"name of student:"<<sname<<endl;
cout<<"roll of student:"<<roll<<endl;
};
string tname;
int tcode;
public:
teacher():college(){
cin>>tname;
cin>>tcode;
void display(){
cout<<"name of teacher:"<<tname<<endl;
cout<<"code of teacher:"<<tcode<<endl;
};
string bookname;
string wname;
int bcode;
public:
book():student(),teacher(){
28
cout<<"etner the name of book"<<endl;
cin>>bookname;
cin>>bcode;
cin>>wname;
void display(){
college::display();
student::display();
teacher::display();
cout<<"name of book:"<<bookname<<endl;
cout<<"code of book:"<<bcode<<endl;
cout<<"name of writer:"<<wname;
};
int main(){
book b;
b.display();
return 0;
29
Question :Implement following diagram in code.
Student
Name,roll
Void sget()
Void sdisplay()
Sports
Test
Price
marks
Void ssget()
Void tget()
Void ssdisplay()
Void tdisplay()
Result
Fee
Void rget()
Void rdisplay()
#include<iostream>
class student{
int roll;
string name;
public:
void sget(){
cout<<"enter name";
cin>>name;
cout<<"enter roll";
30
cin>>roll;
void sdisplay(){
cout<<"name is "<<name<<endl;
cout<<"your roll"<<roll<<endl;
}};
float marks;
public:
void tget(){
cout<<"enter marks";
cin>>marks;
void tdisplay(){
};
int price;
public:void ssget(){
cin>>price;
void ssdisplay(){
cout<<"price is"<<price<<endl;
31
}
};
int fee;
public:
void rget(){
sget();
tget()
ssget();
cout<<"enter fees"<<endl;
cin>>fee;
void rdisplay(){
sdisplay();
tdisplay();
ssdisplay();
}};
int main(){
result r;
r.rget();
r.rdisplay();
return 0;
32
Containership or nested class
Containership is technique in which one class contains object of another class as member data.The class
which contains the object cannot access any protected or private members of the contained class.The
relationship between the container and the contained object is “has- a “ instead of “is-a”.
Question.define a class birthday with members:day,month and year.Use object of this class as member
of another class employee to read and display name and date of birth of an employee.
#include<iostream>
using namespace std;
class birthday
{
int day;
int month;
int year;
public:
void getbirthday();
void displaybirthday();
};
void birthday::getbirthday(){
cout<<"enter day:";
cin>>day;
cout<<"enter month";
cin>>month;
cout<<"enter year";
cin>>year;
}
void birthday::displaybirthday(){
cout<<day<<"/";
cout<<month<<"/";
cout<<year<<endl;
}
class employee{
char name[20];
birthday dob;
public: void getperson();
void displayperson();
};
void employee::getperson(){
cout<<"enter name:";
cin>>name;
33
cout<<"enter data of birth:"<<endl;
dob.getbirthday();
}
void employee::displayperson(){
cout<<endl<<"----------------------------------------"<<endl;
cout<<"name:"<<name<<endl;
cout<<"date of birth:";
dob.displaybirthday();
}
int main(){
employee emp;
cout<<"enter information of an employee:"<<endl;
emp.getperson();
cout<<"your entered information :"<<endl;
emp.displayperson();
return 0;
}
34
Difference between is-a rule and has-a rule
2.example: 2.example
Car is a vehicle Car has a engine
4.is –a relationship assers the instance of the 4.in “has-a” relationship class contains object of
subclass must be more specialized form of the another class as its member data to make it as a
superclass. whole.
35
Difference between inheritance and composition
36
Constructor and destructor in destructor in inheritance
Compiler automatically calls constructor of base class and derived class automatically when
derived class object is created.
If we declare derived class object in inheritance constructor of base class is executed first and
then constructor of derived class.
If derived class object goes out of scope or deleted by programmer the derived clas destructor is
executed first and then base class destructor.
Illustration of when base and derived class constructor and destructor functions are executed.
#include<iostream>
using namespace std;
class a
{
public:
a(){
cout<<"constructor in base class"<<endl;
}
~a()
{
cout<<"destructor in base class"<<endl;}
};
class b:public a
{
public:b(){
cout<<"constructor in derived class"<<endl;
}
~b(){
cout<<"destructor in derived class"<<endl;
}};
int main(){
b obj;
return 0;
}
Output
Constructor in base class
Constructor in derived class
Destructor in derived class
Destructor in base class
37
Subclass,subtype and principle of substitutability
If we consider the relationship of a data type assosciated with a parent class to the data type associated
with a child class ,the following observations can be made.
Instances of the child class must possess all the data members associated with the parent class.
instances of the child class must implement,through inheritance as least(if not explicitly
overridden),all functionality defined for parent class.(They can also define new functionality).
The instance of a child class can mimic the behavior of parent class and should be
indistinguishable from an instance of parent class if substituted in similar situation.
The term subtype is used to refer to a subclass relationship in which the principle of substitutability is
maintained to distinguish such forms from the general subclass relationship,we may or may not satisfy
this principle.
In the example below class B object is replaced by the object of class A withour any error.
This is achieved when a child class is inherited from a base class publicly.In the same example,if the
mode of inheritance is made private the base class object ‘a’ cant be replaced by the parent class object
‘a’.
38
Software reusability
Software reusability is the practice of using existing code for a new software.But in order to reuse
code,that needs to be high quality.And that means is should be safe,secure,reliable efficient and
maintainable.
In OOP,the concept of inheritance provide the idea of reusability.This means that we can add additional
features to an existing class without modifying it.This is possible by deriving a new class from the
existing one.The new class will have the combined features of both the classes.Resusability can be
provided through the concept of composition also.In composition also.In composition one class contains
the object of another classes to make it as a whole.
Advantages of reusability.
Re usability enhanced reliability.
Re usability saves the programmer time and effort.
As the existing code is reused ,it leads to less development and maintenance costs.
Extensibility as we can extend the already made classes by adding some new features.
Inheritance makes the sub classes follow a standard interface.
Forms of inheritance
39
3.Subclassing for construction:
The child class can be constructed from parent class with implementing various access specifiers.The
desired behavior from the base class can be called and construct in the child class.some arguments and
behaviors provided by the parent class may redesign inside the sub class construction.Inheritance
provides the facility to construct new class with the help of parent class.Therefore parent class provides
some construction guidelines to the child class/sub class.
40
Benefits of inheritance
Software reusability.The software reusability is very useful concept while developing new
software product with the help of previous components.Therefore some code should not be
rewrite;we just reused predefined behaviors from super class to the derived class.The behavior
of inheritance increases productivity of software designer,because the programmers do not
spend much time to rewrited the same code,that has been written and tested before.
Code sharing:inheritance provides code sharing in several levels of object oriented design;
Many users can share same parent class properties while designing the derived class for specific
task.
Polymorphishm:polymorphism in programming language permits the programmer to design
high level resusable component that can be suitable for different application design.
Information hiding:The programmer who resuses the software component needs only to
understand behaviors of particular component that interact with other components.Through
the use of private,protected and public visibility specifies the program become more
secured.The inheritance provides some data items are more secured and put some restriction to
use in the derived clases.
Rapid prototyping:while inheriting super class properties we can reused the same code and
developed new component easily.This process reduces coding time and logic is known as rapid
prototyping.With the help of inheritance software system can be design more quickly and
easily.Therefore inheritance increased software prototype because the component that behave
exactly what we required had already done before.
41