Inheritance Part1
Inheritance Part1
13 Inherit
13.1 Introduction
Inheritance is a powerful feature of object-oriented programming. It is a pr
creating new classes from the existing ones. The class from which we er
new class is called the base class. The new class is called the derived clasS.
base class is also known as super class or parent class. Similarly, the d
class is also known as sub class or child class.
For example, an organization consists of various types of employees : manag
engineers, technicians and so·on. We can take employee as a base class ~
can derive a new class engineer. In this case, employee is the base class
engineer is the derived class.
The inheritance relationship is shown in figure. 13.1.
( Feature A)
.·: Base Class
( Feature B)
~ .
Defined in derived class { ( ·Feature C )
( FeatureA )
Defined on base { Derived Class
class but inherit
from base dass
( - Feature B )
FIGURE 13.1
(376)
•.
I -
Most important advantage or h · · .. · · · --
. . in entance 1s reusab1hty. Reusing existing code saves
!~e ~n? ~oney and increases a program's reliability Inheritance can also help in
e ongma conceptualization of a programming probl~m and in the overall design
of the program. · '
■ ·hli-b·i·Uiit·i·t·iltk?iii·&i·1hM%·1••Nit•·iiitttii·&
D Explore the importance of inheritance.
D Define derived classes.
D Explain protected visibility mode.
D Explain various types of inheritance.
D Define a virtual base class.
D Distinguish between overriding and overloading.
□ C~eate objects of derived classes.
□ Write constructors in the derived classes.
□ Declare an object of a class in another class.
};
The colon symbol(:) show the relationshi of a derived lass to its base class.
The visibility mode may be private or public. The default rgg_de is private.
Example 13.1
class d : public b
{
};
(3n)
In this example, d is the name of derived class and bis the name of base ~ss.
Visibility mode is public. Visibility mode public specifies that the features of base
class are publicly·derived or publicly Inherited.
When the base class is publicly inherited, each public mem_ber in the base class
becomes public member in deriv~d class. The private members of base class
are not inherited. · ··
Example 13.2
class d : private b
{
}
..- - ' ? ' - ~ 'l.'. ,• .· . •
In this example, d is the name of derived ~lass and b is the name of base class.
Visibility mode is private. Visibility mo.de private specifies that the features of base
class are privately derived or privately inherited. · ··
When the base class is privately inherite~, ~b public member in the base cl~
b~omes private member in the derived class. The priv~te members of base class
are not inherited. •
Example 13.3
Let us consider a simple program to illustrate inheritance.
PROGRAM
.
II Single inheritance
~ · · _,.,. · #include <.i.ostream.h>
#include <.iomanip.h>
#include <.conio.h> · ., ·
II Base class
class student
I
-::-[ . .introll;
• char name[25];
public:
void getdllla()
{
cout<.<"Enter roll number''<<.endl.·'
.
CUl>>roU;
. (378)
I
.
cout<<"Enter name of student"<<.endl·,
crn>>name;
)
void display()
{
cout<<"Roll No. : "<<roll<<.endl; •
cout<<"Nsme : "<<name<<.endl;
)
'~ ✓
//derived class
int subl,sub2; . .
publie:
void readdata();
void putdata();
};
•oid test :: readdata()
{
getdata(); //base class function
cout<<"Enter the marks of subject 1"<<.endl;
cin>>subl; ·
cou.t<<"Enter the marks of subject-2"<<.endl; '-....,
cin>>sub2;
}
Poid test :: putdata()
{
display(); /H,ase class function
cou.t<<"Marks of Subject-I: "<<subl<<.endl; .
cou.t<<"Marks of Subject-2 : "<<sub2<<endl;
}
POid main()
{
test x; //object of deriPed class created
clrscr( );
x.readdata();
x.putdata();
getch( );
}
(379)
7
/bu,:
E111n roll 11--'>u
J(JJ
Eifler 1111a1e of sllulr,,J
Smad ·
£1116 1M llUl1'b of wjttt - I
78 -
Ellkr du ,naris of nJ,jttt - 2
&7
Roll lio. : 101
l,·ame : Shnank
!,larks of subjed - 1 : 78
!,larks of subjttt - 2 : 87
pm,ate : pmme :
d rol
name name
P'.de : p&.dc :
~() geldata()
cnpay(} dsptay()
,_.d
t • > t
• Dem,eddasa
das&teat
Pl.de
darMllion
Oeri"8d das1s
da9s test
pmate : private:
U1 SIA>1
M>2 SIA>2
P'.dC : pt.de:
readdata ()
readdata()
puldata()
,..................
putdata()
'.,,, ~
~. clsplay()
:
gefdala( ) . :
•.................:: i....-- ~
FIGURE 13.2
(380)
..
UJ~
It is clear from t~e program that all ·pd6nc·members of base class, student, are
,
also the public members of derived class, test
Example 13.4
Consider the example 13.3 after changing the visibility mode from public to private.
PROGRAM
II Single inheriJance
#include <iostream.h>
. #include <iomanip.h>
#include <conio.h>
II Base class
class student
{
int roU;
char name/25];
public:
,oi4 getdaJa()
{
cout<<"Enur roU number''<<endl;
cin>>roll;
cout<<''Enter name of student"<<endl;
cin>>name;
J
void display()
{
cout<<''RoU No. : "<<roU<<endl;
cout<<''NtuM : "<<nmn,<<endl;
J
);
(381)
t-•()id na,l,l11taOi
Mid p11tdata();
};
void test :: ree1d1lata() ,
{
getd11taJ);. //base class fu11ction
corll<<"E11Jer tire marks of subject-l"<<1ndl;
cin>>sllb I;
cout<<"Enter tl,e marks of subject-2"<~ndl;
cin>>sub2;
}
void test :: putdata()
{
display(); //base class function
cout<<"Marks of Subject-I : "<<Subl<~ndl;
cout<<"Marks of Subject-2 : "<<Sub2<~ndl;
}
void main()
{
test x; //object of derived class created
clrscr( );
x.readdata();
x.putdata(); .
getch( );
}
Run :
Enter roll number
101
Enter name of.student
Shivank
Enter the marks of subject - 1
78
Enter the marks of subject - 2
87
Roll No.: 101
Name : Shivank
Marks of subject - 1 : 78
Marks of subject ·• 2 : 87
(382)
Relationship of base class and derived class Is shown In figure 13.3.
FIGURE 13.3
It is clear from this program that all the public members of base class, student are
the private members of derived class, test.
class samplt
{
prfralt :
.. . II BJ dc/au/J
II visible to member Junctions of its own
...
protected :
.. ... II visible to mt mbcr Junctio11s
. .. II of iJs OM"n and derfred class
public:
II visible to all
};
Now, it is also possible to inherit a base class in protected mode known as protected
derivation. In protected derivation, both the public and protected members of the
base ·class beeome protected members of the derived class.
When a protected member is inherited in public mode, it becomes protected in
the derived class. When a protected member is inherited in private mode, it becomes
priva~e in the derived class. 1 ·
Hence, we have three types of derivation namely private, public and protected.
The figure '13.4 shows the effect of inheritance on the visibility of members.
protected protected
public public
(384)
FtGURE 13.4
The foffowing table 13.1 eummanzes the ~ ~ ~ ·. -J ~~
-
l
Bu, dau ,,rir.iill• ,mra,;.•
,,..,,,,,,,
'"""'' ➔
➔
l+iaf u,Mrit,4
Prir.i,
!•• illlltmlH
r,..,md
,..,
,,_rw-'-•-~
pMblic ➔ PriNt, helttl#' hMw -
TA8LE 13.1
Let us review the aocess control to lhe prt.;allt, p,ollcted and p.Mc ,,., c.s ~
a class. The Table 13.2 summarizes the 8CXK1 control lo privat e..,~ ~
of a class. -
Acc,11ibl1 fro• Attnsi)k ,,...
•ri•
Acc,11 AttnN N,~
S1Hcif11r •••cla1
,., ..-~·
,
ci..1 #jJC'ffMP·•• c- - [
,..
.... '
pMblif
prot1ct14
'"""'
,,,
, .. .. l
'
'I
'
'
TAalE 11.2
~
~~~If ~hec:k-1
1. What ii Inheritance?
2.. What ii lhe maJn advantage ol inherilanoe.
3. Habueau aandade rived dlll Ndlid,d eamemb ef Mldlan Mtlh.. ,,,.
name, whk:h member function WII be called by an obtect of lie def1Wd dim. . •
I (315)
' ..
,
4. What is protect~d access specifier?
A
, Base class
D - derived class
1y.~!"ultiple Inheritance .
In multiple inheritance, a derived class is created from two or more base classes•
shown in the figure 13.6. ·
(386)
.····-.;,;,~
:-•"
C'-«_jB J Cl~>aAL,C
c:>
C-b4,~ Pt ..,cl°"~ t
/;-')~ fr J \
•
~ ~---~
~l<- ~
Base class-1 Base clasa-2 Base class-3
X y z
•
D
It can be observed from fig. 13.6 that the class D Inherits properties from the classes
X, Yand Z.
Example 13.5 ·
Figure 13.7 and following program illustrate the concep~ of multiple inheritance.
'~ '~
class test
private: .
sub 1
sub2 ..
plblic:
readda~()
putdata ()
Derived Class
·•
FIGURE6.7
(387)
II M11lti11I, lnh,rltnnce
linrl11de <fo.dr,nm.11'>
#inrlml, <iomnr,ip.h>
#inclr,de <c,min.h>
II Bast clnu •1
cla.fs str,dent
{
int roll;
char name[25];
public:
void getdata()
{
cout<<"Enfer roll number''<-andl;
cin>>roll;
c<,ut<<"Enter name of student"<-andl;
cin>>name;
J
void display()
{
cout<<"Roll No. : "<<roll<-andl;
cout<<"Name : "<<.name<-andl;
J
};
//base class -2
class sports
{
char game[20];
public:
void getgame()
{
cout<<"Enter _th, nam, of th, gam1,,<<6ndl;
cin>>gam,;
)
(388)
void putgame()
(
cout<<"Game : "<<.game<<.endl;
}
};
I/derived class with public visibility mode
. (389)
7
R1111 ,'
Ht1tl'r roll 1111111/,er
/02
f11tt'r 1111me of ,dmle11t
Amit
E11ter the marks "! subject-I
56
E,iter the marks of subject-2
76
Enter the name of the game
Hockey
Roll No. : 102
Name: Amit
Marks of Subject -1: 56
· Marks of Subject • 2 : 76 ·
· Game : Hockey
A Basedass
FIGURE13.8
The class A is a base class for the derived class B. Class B is a base class fdl
derived class C. Therefore, the class B is known as Intermediate base -
(390)
Example 13.6
class student
private :
roll t-..,1__
name
-p
~~
public: BHeCla q
getdata()
dlsplaY() C~,
J
t ,,
class test
protected:
ln ./
sub 1
Sub2
class total
·t
private :
total_marks
Derived Class ,,,.
pubic:
oompu1e()
t FIGURE 13.9
PROGRAM
11 Multilevel inheritance
#include <iostream.h>
#include <iomanip.h>
#include <.conio.h>
II Base class
c'lass student
{
int roll;
char name[25];
public: .
void getdata()
(391)
(
ro11t<<"li11tf'r mil n11mher"<<tmll;
rin>>mll:
r,mt<<"lintrr n,,me ,,J .,1111/tmt"<<endl;
cin>>nnme;
J
oid di.,·play()
)1
{
c,mt<<"Roll No, : "<<rfJll<<endl;
co11t<<"Name : "<<name<<endl;
J
J;
I/derived class
class test : public student
{
protected: //private will not work
int subl,sub2;
public:
void readdaw(); .
void putdata(); ·
};
void test :: readdata().
{
getdata(); /H,ase class function
cout<<"Enter the marks of subject-l'~<<
endl;
cin>>subl;
cout<<"Enter the marks of subject-2"<<
endl;
cin>>sub2; ·
}
yoid test :: putdata()
{
display(); /ll,ase class function
cout<<"Marks of Subject-I : "<<subl<<
endl;
cout<<"Marks of Subject-2 : "<<sub2<<
endl;
)
(392)
{
total_mar/cs = sub] + sub l·
'
) cout<<"Sum 01 marks : "<<Jotal_marks<~ndl;
);
,oid main()
{
total x; I/object of derived class created
clrscr( ),·
x.readdata();
x.putdata();
x.compute();
getc h( );
)
Run :
Enter roU number
103
Enter ntl1M of student
Sa,u a
Enu r the marks of subject-I
88
r
Enter the marks of subject-2
80
RoU No. : 103
Name : Sa-,ila
Marks of Subject-I : 88
Mar la of Subject-2 : 80
Sum of mar1cs : 168
B A D
FIGURE 13.10 ;
BaH CIHI
class student
private :
roll
name
public :
getdata ()
display ()
public: t
public:
readdata () · readdata ( )
putdata () putdata ()
FIGURE 13.11
PROGRAM (P135.CPP)
II Hierarchical inheritance
#include <iostream.h>
#include <iomanip.h>
#ubckyde <conio.h>
II Base class
class student
{
int roll;
char name[2SJ;
public:
void getdata()
{
(394)
cout<<"Enter roll number"<<.endl·,
cin>>roll;
cout<<"Enter name of student"<<.endl;
cin>>name;
}
void display()
{
cout<<"Roll No. : "<<roll<<.endl;
cout<<"Name : "<<name<<.endl;
}
};
I/derived class 1
//derived class 2
(395)
,,,,Id rrnd,l,,tn( );
,,,,Id p11t,l11tn();
};
void hcmn :: relllltllltn()
{ f,
•
geftlt1tn(); //bm;e c/a.u 1 unctw n
co11t<<"Enter tire marb of suhject-l"<<endl;
cin>>,m hl;
cout<<"Enter the marb of subject-2"<<.endl;
cin>>sub2;
}
void bcom :: putdata()
(
display(); //base class function
cout<<"Marks of Subject-1 : "<<Subl<<.endl;
cout<<"Marks of Subject-2 : "<<Sub2<<.endl;
)
void main()
{
bsc x; I/object of derived class-1 create,!
clrscr( );
cout<<endl<<"Data of B.Sc. student is"<<.endl;
x.re~JddZ.ta.(); .. - ....:-=-· -~
- - --- - · - -- - •=-
_ _ ,.. -· ·
x.putdata();
Run:
Data of B.Sc. 'student is
Enter roll-,,umber
104 \
Enter name of student
Rakesh
Enter the marks of subject-I
70 ·
Enter the marks of subject-2
65
(396)
Rf,11 No. : JfU
Namr : Rnb.,h
MarA., fif S11h}rrt•I : 16
Marl.! ,if S11hjrct-l : 6.1
Base class A
l
- I ..
t
Derived class D
FIGURE 13.12
Example 13.8
Figure 13.13 and following example illustrate the hybrid inheritance
(~97)
BaNCIHI
CIA5!'1 81lK1enl
prtvate :
roll
name
public :
getdata() I
display() . I
e... c,111■-2
lntennedlete a.. Cl•• t class sports
ciess test
private :
protected :
sub 1 game
sub2
pl.bllo: ·
public :
getgame()
readdkta()
putgame()
putdata()
Derived Class
class total
f I •
private:
total_marks
..
. public:
oompute() '
- . -
. ..
FIGURE13.13
PROGRAM
II Hybrid inheritance
#include <iostream.h>
#include <iomanip.h>
#include <.conio.h>
II Base class
class student
{
int roU;
char name[2SJ;
public:
void getdata()
{ .
(398)
cmll<< /{ntrr n,11 n11mht'r"<<1mdl·
0
d11>>r"II,· '
".mll<<''li11tt'r name ,,J at111/t'nt"<<1mdl;
cin>>m1me;
J
void di.r.play()
{
co11t<<"Roll .No. : "<<roll<<endl;
cmll<<"Name : "<<name<<endl;
}
};
//derived class
class sports
{
char game[20];
public:
void getgame()
{
cout<<"Enter die name of the game"<<endl;
cin>>game;
)
(399)
1'0id pllll{ llltlf '()
{
rm1l<<' Gnme : "<<Jlnme<<etull;
1
}
};
Run :
Enter roll number
106
Enter name of student
Aditi
Enter the marks of subject-I ·
95 ·
Enter the marks of ~ubject-2 ·
80
Enter the name of the game
Hockey .
Roll No.: 106
Name: Aditi
Marica of Subject-I : 95
Marica of Subject-2 : BO
Game : Hockey
Sum of marks : 46
(400)