0% found this document useful (0 votes)
10 views

Inheritance Part1

Uploaded by

Priyanshu Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Inheritance Part1

Uploaded by

Priyanshu Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

7

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.

13.2 Defining Derived Classes


Whenever a derived class is defined, we have to specify its relationship with the
base class. The general form of specifying a derived class is

class derived_class_name : vis~bility_mode base_class_name


.. { fri"'a~ /- fuJfltt

... II members of derived 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
{

//members of derived class

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

//members of derived class


. ·. ... · ,

}
..- - ' ? ' - ~ '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

class test : public student


{ .

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

In this example, name of base dass is student


and name of derived class ~
-- Visibility mode is public. Relationship of base dass and derived class is st-.
figure 132

Bae ClaN Bae Cius

da915'Jdet1 daSS slUdent

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

{Definition of ba• and


derived class)
(Exact membera of baN and
dertved clau att. declaration)

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

. I/derived class with private visibility mode

class test : private student ·•


{
int subl,su.b2;
public:

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

B111Cl111 81H Clllt


class student cleltfl 1tud8nt
private : private :
roll roll
name name
public: public :
getdata () getdata ()
display () display ()
result of

Derived class f private


:> Derived class f
class test derivation class test
private: private :
sub1
sub2 '"l>e sub1
,._ sub 2
public : CVa Vq8e r---... •• .................
88• 8/11<1& ~ getdata( ) ~
readdeta ()
putdata () 'Ill display( ) !
!•..................
public:
readata()
putdata()
(Definition of base and
derived class)
(Exact members of base and
derived clau after declaration)

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.

13.3 The protected Access Specifier


We know that private members of a base class can not be inherited and therefore it
is not available for the derived class. What do we do if the private data needs to be
inherited by a derived class?
One way to solve this problem is by changing the visibility mode of the private
member by making it publlc, thus taking away the advantage of data hiding.
C++ provides another visibility mode, protected, for this reason. Especially when ·
private members of a class need to be accessed by derived class, it is forced to
· become protected. A member declared as protected is accessible by the member
functions within its class and any class immediately derived from It.
(383)
Now, a class can have all the three visibility mode at once in it as follows.

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.

class B Not class D : private B


inheritable
private private

protected protected

public public

(Base class) (Derived class)


(A) private derivation
--.-

class B Not class D : protected B


inheritablt
private ... private
...
protected protected

public ' -~ public

(Base class) (Derived class)

. (B) protected derivation

(384)
FtGURE 13.4
The foffowing table 13.1 eummanzes the ~ ~ ~ ·. -J ~~
-

,·u;w,,, ., •• :,,~ ,,.,_


\ "iA·ihilit, of priNt, ,rwttlH ,..,.,
.,,.•..
.. ~

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?

I Answers / Hints to Self Check·1 ]


1. Inheritance Is the mechanism which allows a class to Inherit the properties 01
already existing class. '
2. Reusability.
3. The member function of the derived class.
4. A member declared as protected Is accessible by_the member functions Withii
I
its class and any class immediately derived from 1t. 1

13.4 Types of Ineritance


There are five types of inheritance :
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

13.4,J' Single Inheritance


/ . In ~ingle inh"eriSance, there is only one base class and one derived class as shown ii
1 the figure 13.5.

A
, Base class

D - derived class

FIGURE 13.5 (SINGLE INHERITANCE)


Example 13.3 and example 13.4 are th~ examples of single inheritance.

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

FIGURE 13.6 (MULTIPLE INHERITANCE)

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.

BaseClau-1 Base Clau-2


class student class sports
private: ... private: '
roU , gam~
name ., --
(
public: public:
getdata() getgame ()
cisplay () putgame ()

'~ '~

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

class test : public student, public sports


(
int subl,sub2;
public:
void naddata();
void putdata();
};
void test :: readdata() ·
(
getdata(); //base c'/ass-1 function
cout<<"Enter the marks of subject-1"<<.endl;
cin>>subl;
cout<<''Enter the marks of su.bject-2"<<.endl;
cin>>sub2;
gdga,u(); I/base c'/ass-2 function
}
void tell :: putdata()
{
displlq(); I/base c'/ass-1 function
cout<<''Marks of Subject-I : "<<Subl<<endl;
cout<<"Marks of Subject-2 i: "<<Sub2<<endl;
putgtuM(); //base c'/ass-2 fo1nction
}

te,t z; 1/objed of derived ct'ass created


clncr( );
z.naddata-0;
z.putdata();
·getcli( );
}

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

~.4.3 Multilevel Inheritance . . .


· In multilevel inheritance, a class 1s denved from an already denved class a111
in figure 13.8.

A Basedass

B Intermediate Base c;lase


' .
c· Derived cl. .

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

Figure 13.9 and following program illustrate the multilevel inheritance.

class student
private :
roll t-..,1__
name
-p
~~
public: BHeCla q
getdata()
dlsplaY() C~,
J
t ,,
class test
protected:
ln ./

sub 1
Sub2

public: Intermediate Ba• Cla•


readdata()
putdata()

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

class total : public test


{
int totalJnarlcs;
public:
void compute()

(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

13.4.4 Hierarchical Inheritance


derived from 9ne base clrss as
In hierarchical inheritance, two or more classes are
shown in figure. 13.10.

B A D

derived class--1 derived clas&-2 derived c:lass-3

FIGURE 13.10 ;

CW-6 A ; CJcv--\ ,B : ~ A , I , (393)


: Cl~..,3 c.. ~ C.~ t-..
Example 13.7
Figure 13.11 and following program Illustrate the hierarchical inheritance.

BaH CIHI

class student
private :
roll
name

public :
getdata ()
display ()

class bsc classbcom


private: private:
sub 1 sub 1
sub2 sub2

public: t
public:
readdata () · readdata ( )
putdata () putdata ()

Derived class-1 Derived dass-2

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

class bsc : public student


(
int subl,sub2;
public:
void readdata();
void putdala(); .
};
void bsc :: readdata() <
( '

getdala(); I/base class function


cout<<"Enter the marks of subject-l"<<endl;
cin>>subl;
· cout<<.'Enter the marks of subject-2"<<endl;
cin>>sub2;
}
void bsc :: putdala()
{
display(); //base class function
cout<<"Marks of Subject-I : "<<Bubl<<endl;
cout<<."Marks of Subject-2 : "<<Bub2<<endl;
·)

//derived class 2

class bcom : public student


{
int subl,sub2;
public:

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

bsc y; //object of derived class-2 created


cout<<endl<<"Data of B.Com. student is"< ~
y.readdata();
y.putdata();
getch( );
)

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

lhrta ,if 8.Ct,m "111d,nt L,


Enttr roll n11mber
501
Enter name of student
Ashok
Enter the marks of sr,bject-1
85.
Enter the marks of subject-2
82
Roll No. : 501
Name: Ashok
Marks of Subject-I : 85
Marks of Subject-2 : 82

1145 Hybrid Inheritance


Figure
Hybrid Inheritance is a combination of two or more types of inheritance.
multiple
13.12 shows a hybrid inheritance. It is a combination of multilevel and
inheritance. .. ·

Base class A
l

lntennedlata Base class B


.. I · C· 1--tsra
. ,

- 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 test : public student


{ •
protected: //private will not work
int subl,sub2;
public:
void readdata(); ·
void putdata();
};
void test :: readdata()
{
getdata(); //base class function
cout<<"Enter the marks of subject-1 "<<endl;
cin>>subl;
cout<<"Enter the marks of subject-2"<<.endl;
cin>>sub2;
}
void test·:: putdata()
{
display(); //base class function
cout<<"Marks of Subject-I : "<<Subl<<endl;
cout<<"Marks of Subject-2 : "<<Sub2<<.endl;
}
//base class -2

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

}
};

rlau totnl : p11l1lic te.vt,pul,lic .vports


{
i,rt total_marks;
p11blic:
void comp11te()
{ "\

total marks = sub1 + sub2;


cout<<"Sum of marks : "<<JotalJnarlcs<<.endl;
)
);
void main()
{
total x; //object of derived class created _
clrscr( );
x.readdata();
x.getgame();
x.putdata();
x.putgame();
x.compute();
getch( );
}

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)

You might also like