Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
117 views305 pages

285 - OOPS Lecture Notes Complete

The document provides an introduction to object oriented programming and C++. It discusses different types of programming languages like machine level language, assembly level language, and high level languages. It also lists the topics that will be covered in lectures related to object oriented programming concepts in C++.

Uploaded by

Barbie Joo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views305 pages

285 - OOPS Lecture Notes Complete

The document provides an introduction to object oriented programming and C++. It discusses different types of programming languages like machine level language, assembly level language, and high level languages. It also lists the topics that will be covered in lectures related to object oriented programming concepts in C++.

Uploaded by

Barbie Joo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 305

2 P.

T.
O
SYLLABUS
Obj
ectOr
ient
edPr
ogr
ammi
ng
TextBooks:
1. ObjectOri
ent
edPr ogr
ammi
ngwi
thC++ byE.Bal
agurusamy,McGraw-Hi
l
l
Educat
ion(I
ndia)
2. ANSIandTur boC++ by AshokeN.Kamt
hane,PearsonEducat
ion

ReferenceBooks:
1.BigC++ -Wi l
eyI
ndia
2.C++: TheCompl eteRefer
ence-Schil
dt,
McGraw-Hi
llEducation(
Indi
a)
3.C++andObj ectOr
ientedProgr
ammi ng–Jana,PHILearning.
4.ObjectOrientedProgr
ammi ngwithC++ -Raji
vSahay ,
Oxf or
d
5.Mast er
ingC++ - Venugopal ,McGraw-Hi
l
lEducat
ion( I
ndia)

3 P.
T.
O
4 P.
T.
O
CONTENTS
Lectur
e01:
Int
roduct
ion

5 P.
T.
O
Lect
ure02: ObjectOr ient edPr ogr ammi ng
Lect
ure03: BASI CCONCEPTSOFOBJECTSORI ENTEDPROGRAMMI
NG
Lect
ure04: BENEFI TSOFOOP
Lect
ure05: BasicsofC++
Lect
ure06: Tokens
Lect
ure07: BasicDat at ypesi nC++
Lect
ure08: Symbol i
cConst ant
Lect
ure09: Oper at ors
Lect
ure10: Cont rol St ruct ur es
Lect
ure11: Funct ionsi nC++
Lect
ure12: Funct ionOv erloadi ng
Lect
ure13: Class
Lect
ure14: MemberFunct ion
Lect
ure15: Nest i
ngofMemberf uncti
on
Lect
ure16: Arraywi t
hCl ass
Lect
ure17: Stati
cDat aMember
Lect
ure18: Fri
endl yf unct i
ons
Lect
ure19: Retur ningObj ect s
Lect
ure20: Const ruct or s
Lect
ure21: Destr uct or s
Lect
ure22&23: Oper at or
Over
loadingLect
ure24: Ty pe
Conversi
on
Lect
ure25: Classt oBasi ct y pe
Lect
ure26: I
nher itance
Lect
ure27: Mul t
ilev el Inher i
t ance
Lect
ure28: Hierar chi cal I
nher i
tance
Lect
ure29: Virt
ual BaseCl ass
Lect
ure30: Polymor phi sm
Lect
ure31: Virt
ual funct ions
Lect
ure32: PureVi rtual Funct ions
Lect
ure33: C++f unct ionov erri
ding
Lect
ure34: Except i
onHandl ing
Lect
ure35: Arrayr ef er enceoutofbound
Lect
ure36: Cont ainer shi pinC++
Lect
ure37: Templ at e
Lect
ure38: ClassTempl at e
Lect
ure39: Virt
ual dest ruct or s
Lect
ure40: Managi ngConsol eI/O
Lect
ure41: Namespaces
Lect
ure42: New&Del et eOper ators

6 P.
T.
O
Modul
e-1:

LECTURE-
1

Int
roduct
ion:
Programmerswrit
einst
ruct
ionsi
nv ariouspr ogr
ammi ngl
anguagest
oper
for
mthei
r
computati
ontaskssuchas:
(i
) Machi nelev elLanguage
(i
i) Assemblyl evelLanguage
(i
ii
) Highl
evel Language

MachinelevelLanguage:
Machine code ormachi ne language is a setofi nst
ruct
ions executed dir
ectlybya
computer
'scent r
alprocessinguni t(CPU).Eachinst
ructi
onper f
ormsav eryspecifi
ctask,
suchasal oad,aj ump,oranALUoper ati
ononauni tofdatainaCPUr egisterormemor y.
Ever
yprogram directl
yexecutedbyaCPUi smadeupofaser i
esofsuchi nstr
uctions.

Assembl ylevelLanguage:
Anassembl ylanguage(orassembl
erlanguage)isalow-l
evelprogr ammi nglanguagefora
comput er
,orot herprogr
ammabl edevi
ce,inwhichther
eisav eryst r
ong( gener
all
yone-to-
one) correspondence between the language and the architecture'
s machi ne code
i
nstruct
ions.Assembl yl
anguageisconv er
tedintoexecutabl
emachi necodebyaut il
ity
program referr
edtoasanassembl er;
theconversi
onprocessisref erredtoasassembl y,
or
assembl i
ngt hecode.

HighlevelLanguage:
High-
lev
ellanguagei sanyprogrammi nglanguagethatenablesdev el
opmentofapr ogram
i
nmuchsi mplerpr ogrammingcont extandi sgenerall
yi ndependentoft hecomput er'
s
hardwarear chi
tecture.High-l
evellanguagehasahi gherl evelofabstracti
onf r
om t he
computer,andf ocusesmor eont heprogramminglogicratherthantheunderly
inghardware
component ssuchasmemor yaddressingandregi
sterut
ili
zati
on.

Thef i
rsthi
gh-l
evelprogrammingl anguageswer edesignedinthe1950s.Now t hereare
dozens ofdiff
erentlanguages,i ncluding Ada ,Algol,BASIC,COBOL,C,C++,JAVA,
FORTRAN, LI
SP,Pascal,andProlog.Suchl anguagesareconsider
edhigh-
lev
elbecausethey
areclosert
ohumanl anguagesandf artherfr
om machinelanguages.I
ncontrast,
assembly
l
anguagesareconsideredlow-levelbecauset heyar
ev er
yclosetomachinelanguages.

Thehi
gh-
lev
elpr
ogr
ammi
ngl
anguagesar
ebr
oadl
ycat
egor
izedi
ntot
wocat
egor
ies:

(
iv) Pr
ocedur
eorient
edprogr
ammi ng(
POP)language.
(
v) Objector
ient
edprogr
ammi ng(
OOP)language.

7 P.
T.
O
Pr
ocedur
eOr
ient
edPr
ogr
ammi
ngLanguage

Inthepr
ocedureor
ientedapproach,
thepr
obl
em i
svi
ewedassequenceoft
hingst
obedone
suchasreadi
ng,calculat
ionandpri
nti
ng.

Procedur
eorient
edprogr
ammingbasi
cal
lyconsi
stofwri
ti
ngali
stofi
nstr
uct
ionoracti
onsf
or
thecomputertofol
l
owandorgani
zi
ngtheseinst
ruct
ioni
ntogr
oupsknownasfunct
ions.

Main
pr
ogram

Funct
ion-
1 Funct
ion-
2 Funct
ion-
3

Thedi
sadv
antageoftheprocedureori
entedpr
ogrammi
ngl
anguagesi
s:
1.Global
dataaccess
2.I
tdoesnotmodel realwordprobl
em ver
ywel
l
3.Nodatahidi
ng

Gl
obal
dat
a Gl
obal
dat
a

Funct
ion-
1 Funct
ion-
2 Funct
ion-
3

Local
dat
a Local
dat
a Local
dat
a

Char
act
eri
sti
csofpr
ocedur
eor
ient
edpr
ogr
ammi
ng:

1.Emphasisi sondoi ngthings(algor


it
hm)
2.Largeprogr amsar edi
videdi nt
osmal lerpr
ogr amsknownasf unct
ions.
3.Mostoft hef unct
ionsshar eglobaldata
4.Datamov eopenl yaroundt hesy st
em f r
om functiontof
unct
ion
5.Functi
ont ransfor
msdat af rom onefor mtoanot her.
6.Employst op-downappr oachi nprogram design

8 P.
T.
O
LECTURE-
2

Obj
ectOr
ient
edPr
ogr
ami
ng

“Objector
ient
ed programming as an approach thatpr
ovi
des a wayofmodul ar
izi
ng
programsbycreat
ingparti
ti
onedmemor yareaforbothdat
aandfunct
ionst
hatcanbeused
astemplat
esforcreat
ingcopiesofsuchmodulesondemand”.

Obj
ectA Obj
ectB

Dat
a Dat
a

Communi
cat
i

Funct
ions Funct
ions

Obj
ectC

Funct
ions

Dat
a

Feat
uresoft
heObj
ectOr
ient
edpr
ogr
ammi
ng

1.Emphasi sisondoingr at herthanprocedure.


2.programsar edivi
dedi ntowhatar eknownasobj ect
s.
3.Datast r
ucturesar
edesi gnedsucht hattheycharact
erizetheobj ect
s.
4.Functionsthatoperateont hedataofanobj ectareti
edt ogetherinthe
datast r
ucture.
5.Dataishi ddenandcan’ tbeaccessedbyext ernal
functions.
6.Objectsmaycommuni cat ewitheachotherthroughfunct i
ons.
7.Newdat aandfunctionscanbeeasi lyadded.
8.Foll
owsbot t
om-upappr oachi npr
ogram design.

9 P.
T.
O
LECTURE-
3

BASI
CCONCEPTSOFOBJECTSORI
ENTEDPROGRAMMI
NG

1.Object
s
2.Cl
asses
3.Dataabstracti
onandencapsul
ati
on
4.I
nherit
ance
5.Polymorphism
6.Dynamicbi ndi
ng
7.Messagepassi ng

OBJECTS

Obj
ectsar
ethebasi
crun-
ti
meenti
ti
esinanobj
ect
-or
ientedsyst
em.Theymayrepresenta
per
son,apl
ace,
abankaccount
,atabl
eofdat
aoranyitem t
hatthepr
ogram musthandle.

Thefundamentalideabehi
ndobjector
ientedapproachi
stocombi
nebot
hdat
aand
f
unct
ionint
oasi ngl
eunitandtheseuni
tsarecall
edobjects.

Theterm object
smeansacombi nati
onofdat aandprogram thatr
epresentsome
realwor
dentit
y.Forexample:consi
deranexampl enamedAmi t;Amitis25yearsoldand
hissal
aryi
s2500.TheAmi tmayber epresentedinacomputerprogr
am asanobj ect
.The
datapar
toftheobjectwoul
dbe( name:Amit,age:
25,sal
ary
:2500)

Thepr ogr
am par
toft heobjectmaybecol lecti
onofpr ogr
ams( r
etr
iveofdata,
changeage,changeofsal
ary).I
ngeneralevenanyuser–defi
nedt y
pe-suchasemployee
maybeused.I ntheAmi
tobjectt
hename, ageandsalar
yarecal
ledatt
ri
butesoftheobj
ect.

Obj
ect
:St
udent STUDENT

DATA Tot
al
Name
Dat
e-of
-bi
rt
h
Marks Av
erage

FUNCTIONS
Total
Average Di
spl
ay
Displ
ay

CLASS:

Agroupofobj
ectst
hatshar
ecommonpr
oper
ti
esf
ordat
apar
tandsomepr
ogr
am par
t
ar
ecol
l
ect
ivel
ycal
ledascl
ass.

I
nC++acl assisanewdatat
ypethatcont
ainsmemberv
ari
abl
esandmember
f
unct
ionst
hatoperat
eonthevari
abl
es.
1 P.
T.
1 O
DATAABSTRACTI
ON:

Abstr
acti
onr efer
stot
heactofr epr esent
ingessent
ialf
eat
ureswit
houti
ncl
udi
ngthe
backgrounddet ail
sorexplanat
ions.Cl assesuset heconceptofabst r
act
ionandare
defi
nedassize,
wi dt
handcostandfunctionst ooperat
eont heat
tri
but
es.

DATAENCAPSALATI
ON:

Thewr appingupofdataandf uncti


oni
ntoasingl
eunit(cal
l
edcl
ass)isknownas
encapsulati
on.Thedat aisnotaccessibl
etot
heoutsideworl
dandonlythosefunct
ions
whichar ewr apped intheclasscanaccessi t
.Thesefuncti
onsprov
idetheinter
face
betweent heobjectsdat
aandtheprogram.

I
NHERI
TENCE:

I
nher
itanceist hepr ocessbywhi chobjectsofonecl assacquirethepr oper
ti
esof
anot
herclass.Intheconceptofi nher
it
anceprovidestheideaofreusabli
ty.Thismeant hat
wecanaddaddi t
ionalfeaturestoanexisti
ngcl
asswi thoutmodifyingit
.Thisispossibl
eby
desi
ninganewcl asswi llhavethecombinedfeaturesofboththeclasses.

POLYMORPHI
SIM:

Pol
ymorphism meanst heabil
it
ytot akemorethanoneform.Anoper
ati
onmayex hi
bit
di
ff
erenti
nstance.Thebehav
iourdependsupont
hetypeofdat
ausedi
ntheoper
ati
on.

Alanguagefeat
urethatal
l
owsafunct
ionoroperat
ortobegivenmorethanonedefi
nit
ion.
Thetypesoftheargumentswi
thwhi
chthefunct
ionoroper
atoriscal
l
eddeter
mineswhi ch
def
ini
ti
onwillbeused.

Ov
erl
oadi
ngmaybeoper
atorov
erl
oadi
ngorf
unct
ionov
erl
oadi
ng.

Iti
sabl etoexpr
esstheoper ati
onofaddit
ionbyasingleoperat
ersay‘+’
.Whent hi
sis
possibl
eyouusetheexpressi
onx+yt odenotet
hesum ofxandy ,
formanydif
fer
entty
pes
ofxandy ;int
egers,fl
oatandcomplexno.Youcanev endefinethe+operati
onfortwo
str
ingstomeantheconcatenat
ionoft
hestri
ngs.

DYNAMI
CBI
NDI
NG:

Bi
ndingref
erst
ot heli
nki
ngofapr ocedurecallt
ot hecodet
ot heexecutedin
responsetothecall
.Dynamicbindi
ngmeanst hecodeassoci atedwithagivenprocedure
calli
snotknownunt i
llt
heti
meoft hecallatrun-
ti
me.I tisassociat
edwit
hapol ymor phi
c
refer
encedependsuponthedynamictypeofthatr
eference.

1 P.
T.
1 O
MESSAGEPASSI
NG:

Anobjector
ient
edpr
ogr
am consi
stsofasetofobj
ect
sthatcommuni
cat
ewi
th
each
ot
her
.

A messagef oranobjectisar equestforexecut


ionofapr ocedureand
ther
eforewil
linv
okeaf uncti
on(procedur
e)int herecei
vi
ngobj ectt
hatgener at
esthe
desi
redresul
t.Messagepassi
nginv
olvesspeci
fyi
ngthenameoft heobject
,thenameof
thefunct
ion(
message)andinf
ormat
iontobesent.

Empl
oyee .Sal
ary(
name)

Obj
ect I
nfor
mat
ion
Message

1 P.
T.
1 O
LECTURE-4

BENEFI
TSOFOOP:

Oopoffersseveralbenefit
st obotht
hepr ogr
am designerandtheuser.Obj
ect-
ori
ent
ed
cont
ri
butestothesol ut
ionofmanyproblemsassociatedwiththedev
elopmentandqual
it
y
ofsof
twareproducts.Theprinci
pal
advantagesare:

1. Throughi nher i
tancewecanel i
mi nater edundantcodeandext endt heuseof
exi
st i
ngcl asses.
2. Wecanbui ldpr ogr amsf rom thest andar dwor kingmodul est hatcommuni cate
wit
honeanot her ,ratherthanhav ingt ost artwrit
ingt hecodef rom scratch.This
l
eadst osav i
ngofdev el
opmentt imeandhi gherproduct iv
ity
.
3. Thisprinci pleofdat ahidinghelpst hepr ogr ammert obui ldsecur eprogramst hat
can’tbei nv adedbycodei notherpar tsoft hepr ogram.
4. Iti
spossi bletohav emul tipl
einstancesofanobj ecttoco- existwi t
houtany
i
nterference.
5. Iti
seasyt opar titiont heworkinapr ojectbasedonobj ects.
6. Object-orientedsy stemscanbeeasi lyupgr adedfrom smal lt
ol argesystems.
7. Messagepassi ngt echniquesforcommuni cati
onbet weenobj ectsmakest he
i
nterfacedescr iptionwi thexternalsy stemsmuchsi mpl er
.
8. Softwar ecompl exi t
ycanbeeasi lymanaged.

APPLI
CATI
ONOFOOP:

Themostpopularappli
cat
ionofoopsupt onow,hasbeeni
ntheareaofuser
i
nterf
ace desi
gn such aswi ndows.There ar
e hundr
edsofwi ndowi
ng syst
ems
devel
opedusingooptechniques.

Real
busi
nesssystemsareoftenmuchmor
ecomplexandcont
ainmanymore
obj
ectswi t
hcompl i
catedatt
ri
butesandmethods.Oopisusefuli
nt hi
st y
peof
appl
icati
onsbecauseitcansimplif
yacomplexprobl
em.Thepromi
singareasf
or
appl
icati
onofoopincl
udes.

1.Real –Ti mesy stems.


2.Si
mul ati
onandmodel ing
3.Obj ectori
enteddat abases.
4.Hy pertext
,hy
per mediaandex pertext
.
5.Alandexper tsy stems.
6.Neur alnetworksandpar al
lel
programming.
7.Dicisionsuppor tandof f
iceautomati
onsyst
ems.
8.CIM /CAM /CADsy stem.

1 P.
T.
1 O
LECTURE-
5

Basi
csofC++

C++i sanobjectori
entedprogr
ammi nglanguage,C++wasdev
elopedby
Jar
neyStr
oustrupatAT&TBel ll
ab,USAinearl
yeight
ies.C++wasdevel
opedf
rom cand
si
mula67language.C++wasearl
ycalled‘
Cwithcl
asses’.

C++Comment
s:

C++i ntr
oducesanew commentsy mbol/ /
(doubleslash)
.Comment sst ar
t
wit
hadoubl esl ashsy mbolandtermi
nateattheendofl i
ne.Acommentmayst artany
whereinthelineandwhatev erfol
lowsti
llt
heendoflineisi gnor
ed.Notethatther
eisno
cl
osingsy
mbol .
Thedoubl eslashcommenti sbasi
cal
lyasingl
elinecomment .Mul
til
inecomment s
canbewritt
enasf oll
ows:

//thi
sisanexampl
eof
//c++program
//thankyou
Theccommentsy mbol
s/*….
*/ar
est
il
lval
i
dandmor
esui
tabl
eformul
til
i
necomment
s.

/
*thi
sisanexampl
eofc++pr
ogr
am *
/

Out
putOper
at :
or

Thest atementcout<<” Hell


o,wor l
d”displayedt hestri
ngwi t
hi nquotesont hescr een.The
i
dent i
fi
ercoutcanbeusedt odisplayi
ndividualcharacters,str
ingsandev ennumber s.Iti
sa
predefinedobjectthatcorrespondst othest andardout putstream.St ream justreferstoa
fl
owofdat aandt hestandar dOutputstr
eam nor mal l
yflowst ot hescreendisplay
.Thecout
object,whosepr operti
esar edef i
nedini ostream.hr epresentst hatstream.Thei nsert
ion
operator<<alsocal l
edthe‘ putto’oper
atordi r
ectsthei nformationoni t
sr i
ghttot heobject
onitsleft.

Ret
urnSt
atement
:

InC++main()r
etur
nsanintegerty
peval
uet otheoper
atingsyst
em.Theref
oreevery
main(
)i
nC++shoul
dendwit
har et
urn(
0)statement
,otherwiseawarningoraner
rormightoccur
.

I
nputOper
ator
:

Thest atement
ci
n>> number
1;
i
saninputstatementandcauses.Theprogram t
owaitfortheusert
otypeinanumber.The
numberkeyedi nisplacedi
nthevari
abl
enumber 1.Theidenti
fi
erci
nisapredefi
nedobject
i
nC++t hatcorrespondstothest
andardinputst
ream.Herethisstr
eam r
epresent
sthekey
boar
d.

Theoper
ator>>i
sknownasgetf
rom oper
ator
.Itext
ract
sval
uef
rom t
he
1 P.
T.
1 O
key
boar
dandassi
gnsi
ttot
hev
ari
abl
eoni
tsr
ight
.

1 P.
T.
1 O
Cascadi
ngOfI
/OOper
ator
:

cout
<<”sum=”
<<sum<<”
\n”;
cout
<<”sum=”
<<sum<<”
\n”<<”
aver
age=”
<<av
erage<<”
\n”
;ci
n>>number
1>>number2;

St
ruct
ureOfAPr
ogr
am :

Probabl
yt hebestwaytost ar
tlearni
ngapr
ogr
ammi
ngl
anguagei
sbywr
it
ingapr
ogr
am.
Theref
ore, her
eisourfi
rstprogram:
//myf i
rstprogram i
nC++

#incl
ude
<i
ostream>usi
ng
namespacestd;

i
ntmai n( )
{
cout<<" HelloWor l
d! "
;
return0;
}
Out put:-Hel l
oWor ld!
Thef i
rstpanelshowst hesour cecodef orourf ir
stpr ogr am.Thesecondoneshowst he
resultoft hepr ogr am oncecompi ledandexecut ed.Thewayt oedi tandcompi leapr ogram
dependsont hecompi l
ery ouar eusi ng.Dependi ngonwhet heri thasaDev elopment
Interf
aceornotandoni tsv ersion.Consul tthecompi ler ssect i
onandt hemanualorhel p
i
ncl udedwi t
hy ourcompi lerify ouhav edoubt sonhowt ocompi leaC++consol epr ogram.
Thepr eviouspr ogr am i st het ypical progr am thatpr ogr ammerappr enti
ceswr itef ort hefi
rst
time,andi t
sr esulti st hepr intingonscr eenoft he" Hel l
oWor l
d!"sent ence.I tisoneoft he
simpl estpr ogramst hatcanbewr i
tteni nC++,buti tal readycont ainst hef undament al
component sthatev er yC++pr ogr am has.Wear egoi ngt ol ookl inebyl i
neatt hecodewe
hav ejustwr it
ten:
//myf irstpr ogr am i nC++
Thi sisacommentl i
ne.Al ll inesbegi nni
ng wi t
ht wo sl ashsi gns( /
/)ar econsi dered
comment sanddonothav eanyef fectont hebehav i
oroft hepr ogr am.Thepr ogrammercan
uset hem t oincl udeshor texpl anat ionsorobser v at
ionswi thint hesour cecodei tsel f
.Inthi s
case, thel ineisabr i
efdescr iptionofwhatourpr ogram i s.
#include<i ost ream>
Linesbegi nningwi t
hahashsi gn( #)ar edi rect i
vesf ort hepr eprocessor .Theyar enot
regularcodel ineswi thexpr essi onsbuti ndi
cat ionsf ort hecompi l
er'spreprocessor .Inthi s
case t he di r
ect iv
e #i nclude<i ost ream> t el
lst he pr epr ocessort oi ncl
ude t he i ostream
standar df i
le.Thi sspeci f
icf i
le( i
ost r
eam)i ncludest hedecl arationsoft hebasi cst andard
i
nput -out putl i
br aryi nC++,andi tisi ncludedbecausei tsf unct ionalityisgoi ngt obeused
l
at erint hepr ogr am.
usingnamespacest d;
All t
heel ement soft hest andar dC++l ibraryar edecl ar edwi thinwhati scalledanamespace,
thenamespacewi tht henamest d.Soi nor dert oaccessi tsf unctionalitywedecl ar ewi th
thisexpr essi ont hatwewi llbeusi ngt heseent i
ties.Thi sl i
nei sv eryf r
equenti nC++
programst hatuset hest andar dl i
br ary,andi nf actitwi l
l bei ncludedi nmostoft hesour ce
codesi ncludedi ntheset utor ials.
i
ntmai n( )
Thi slinecor respondst ot hebegi nningoft hedef initionoft hemai nfunction.Themai n
1 P.
T.
1 O
funct
ionisthepointbywhereallC++pr ogramsst ar
tthei
rexecut
ion,i
ndependentl
yofi t
s
l
ocationwit
hinthesourcecode.Itdoesnotmat terwhethert
hereareotherfunct
ionswi t
h
othernamesdef i
nedbeforeoraf t
erit–t heinstr
ucti
onscontai
nedwithi
nt hi
sf unct
ion'
s
defi
niti
onwil
lal
way sbethefi
rstonestobe

1 P.
T.
1 O
execut edi nanyC++pr ogr am.Fort hatsamer eason,i ti sessent i
alt hatal lC++pr ograms
hav eamai nf unct i
on.
Thewor dmai ni sf ol l
owedi nt hecodebyapai rofpar ent heses( ()).Thati sbecausei ti
sa
funct i
ondecl ar ati
on:I nC++,whatdi ffer ent i
at esaf unct iondecl arationf rom ot hert ypesof
expr essi onsar et hesepar enthesest hatf ollowi tsname.Opt i
onal ly,thesepar ent hesesmay
encloseal istofpar amet er swi thinthem.
Rightaf tert hesepar ent heseswecanf i
ndt hebodyoft hemai nf unct ionencl osedi nbr aces
({}
).Whati scont ainedwi thint hesebr acesi swhatt hef unct iondoeswheni tisexecut ed.
cout<<" Hel loWor l
d! ";
Thisl inei saC++st atement .Ast at ementi sasi mpl eorcompoundexpr essi ont hatcan
actual l
ypr oduce some ef f
ect .I nf act ,t his st atementper forms t he onl yact ion that
gener at esav i
sibleef fecti nourf irstpr ogr am.
coutr epr esent st he st andar d out putst ream i n C++,and t he meani ng oft he ent ir
e
statementi st oi nser tasequenceofchar act ers( i
nt hiscaset heHel loWor ldsequenceof
char acter s)i ntot hest andar dout putst r
eam ( whi chusual l
yist hescr een) .
couti sdecl aredi nt hei ost ream st andar df ilewi thint hest dnamespace,sot hat '
swhywe
neededt oi ncl udet hatspeci ficf il
eandt odecl ar et hatwewer egoi ngt ouset hi sspeci fi
c
namespaceear li
eri nourcode.
Not i
cet hatt hest at ementendswi thasemi col onchar act er( ;
) .Thi schar act eri susedt o
mar kt heendoft hest atementandi nf acti tmustbei ncl udedatt heendofal lexpr ession
statement si nal lC++pr ogr ams( oneoft hemostcommonsy ntaxer ror sisi ndeedt of orget
toincl udesomesemi col onaf terast atement )
.
return0;
Ther etur nst atementcausest hemai nf unct i
ont of i
nish.r eturnmaybef oll
owedbyar eturn
code( inourexampl ei sf ollowedbyt her et urncode0) .Ar eturncodeof0f ort hemai n
funct i
oni sgener al l
yi nt erpret edast hepr ogr am wor kedasexpect edwi thoutanyer r
ors
duringi tsexecut ion.Thi si st hemostusual wayt oendaC++consol epr ogram.
Youmayhav enot icedt hatnotal lthel inesoft hi spr ogr am per f orm act ionswhent hecode
i
sexecut ed.Ther ewer el inescont ai ningonl ycomment s( thosebegi nningby/ /
).Ther e
wer el ineswi thdi rectivesf ort hecompi l
er '
spr eprocessor( thosebegi nningby#) .Then
therewer el inest hatbegant hedecl ar at i
onofaf unct ion( int hi scase,t hemai nf unct i
on)
and, final l
yl i
neswi thst at ement s( li
ket hei nser tioni ntocout ),whi chwer eal lincl udedwi thi
n
thebl ockdel imi t
edbyt hebr aces( {})oft hemai nf unct i
on.
Thepr ogr am hasbeenst ructur edi ndi ff erentl inesi nor dert obemor er eadabl e, butinC++,
wedonothav est rictr ulesonhowt osepar atei nstruct ionsi ndi fferentl i
nes.Forexampl e,
i
nst eadof
i
ntmai n( )
{
cout<<"Hel loWor l
d!";
retur n0;
}

Wecoul
dhav
ewr
it
ten:

i
ntmai n()
{
cout<<"Hell
oWor l
d!"
;
ret
urn0;
}
Alli
njustoneli
neandt hi
swouldhav ehadexact
lythesamemeani ngasthepr evi
ouscode.
InC++,theseparat
ionbetweenstatementsisspecif
iedwithanendingsemi col
on( ;
)atthe
endofeachone,sot heseparat
ioni ndi
ff
erentcodel i
nesdoesnotmat t
eratal lfort
his
purpose.Wecanwr i
temanyst atementsperlineorwr it
easinglestatementt hattakes
1 P.
T.
1 O
manycodel
i
nes.Thedi
vi
sionof

1 P.
T.
1 O
codeindi
ff
erentl
inesser
vesonl
ytomakei
tmor
elegi
bleandschemat
icf
ort
hehumans
thatmayr
eadit.

Letusaddanaddi t
ional
inst
ruct
iont
oourf
ir
stpr
ogr
am:
//mysecondpr ogr
am inC++
#incl
ude<i
ostream>
usingnamespacestd;

i
ntmai n(
)
{
cout<<"Hel
loWorl
d!";
cout<<"I
'm aC++pr
ogram"
;
ret
urn0;
}

Out
put
:-
Hel
l
oWor
ld!I
'
m aC++pr
ogr
am

Int hi
scase, weper
formedt woinser
ti
onsint
ocoutint
wodi f
fer
entst
atements.Onceagain,
theseparationindi
ffer
entli
nesofcodehasbeendonejusttogivegr
eaterr
eadabil
it
ytothe
pr ogr
am,sincemaincoul dhavebeenper
fectl
yval
i
ddefinedthi
sway:
i
ntmai n(
)
{
cout<<"Hel loWor
ld!";
cout<<"I '
m aC++pr ogram ";
retur
n0;
}

Wewer ealsof r
eetodivi
det hecodei nt
omor eli
nesifweconsideredi
tmor e
convenient:i
ntmai n()
{
cout<<" HelloWor ld!
";
cout<<" I
'
m aC++
program";return0;
}
Andt heresultwouldagainhav ebeenexact lythesameasi ntheprevi
ousexampl es.
Preprocessordi r
ecti
ves(thoset hatbeginby#)ar eoutofthisgeneralrulesi
ncet heyare
notstatement s.Theyareli
nesr eadandpr ocessedbyt heprepr
ocessoranddonotpr oduce
anycodebyt hemselves.Preprocessordirecti
vesmustbespeci f
iedintheirownlineanddo
nothav etoendwi thasemi colon(;)
.

STRUCTUREOFC++PROGRAM

 I
ncl
udefil
es
 Cl
assdeclarat
ion
 Cl
assfuncti
ons,def
ini
ti
on
 Mainf
unction

pr
ogr
am Exampl
e:-

#i
ncl
ude<i
ost
ream.
h>

cl
assper
son
2 P.
T.
2 O
{
charname[30];
i
ntage;
publi
c:
voi
d
get
dat
a( v
oid);
voi
ddisplay
(voi
d);
};

v
oidperson::get
dat
a(void)
{
cout
<<”ent
ername”;
ci
n>>name;
cout
<<”ent
erage”
;
ci
n>>age;
}

v
oiddi
spl
ay()
{
cout
<<”\nname:”<<name;
cout
<<”\nage:
”<<age;
}

i
ntmai
n()
{

personp;
p.getdata(
);
p.displ
ay()
;
return(
0);

2 P.
T.
2 O
LECTURE-
6

TOKENS:

Thesmall
esti
ndi
vi
dual
uni
tsi
npr
ogr
am ar
eknownast
okens.C++hast
he
fol
l
owing
t
okens.

i
. Keywor ds
ii
. I
dentif
iers
i
i
i. Constants
i
v. Str
ings
v. Operators

KEYWORDS:

Thekeywor
dsimplementspeci
fi
cC++l anguagefeat
ure.Theyareexpli
cit
ly
reservedi
denti
fi
ersandcan’
tbeusedasnamesf ortheprogr
am vari
ablesorotheruser
definedpr
ogram el
ement
s.Thekeywor
dsnotfoundinANSICareshowni nredl
ett
er.

C++KEYWORDS:

Asm doubl
e new swi
tch

Aut
o el
se oper
ator t
empl
at
e
Br
eak enum pr
ivat
e t
his

Case ext
ern pr
otect
ed t
hrow

Cat
ch f
loat publ
i
c t
ry

Char f
or r
egi
ster t
ypedef

Cl
ass f
ri
end r
etur
n uni
on

Const got
o shor
t unsi
gne
d
Cont
inue i
f si
gned v
irt
ual

Def
aul
t i
nli
ne si
zeof v
oid

Del
ete l
ong st
ruet whi
l
e

I
DENTI
FIERS:

I
denti
fi
ersr
efer
stot
henameofvar
iabl
e,funct
ions,ar
ray,cl
asset
c.cr
eat
edbypr
ogr
ammer
.
Eachl
anguagehasi
tsownr
ulef
ornamingtheident
ifi
ers.

2 P.
T.
2 O
Thef
oll
owi
ngr
ulesar
ecommonf
orbot
hCandC++.

2 P.
T.
2 O
1.Onl
yalphabet
icchars,
digi
tsandunderscoreareper
mit
ted.
2.Thenamecan’tstar
twithadigit
.
3.Uppercaseandlowercaselet
tersar
edist
inct
.
4.Adeclar
edkeywordcan’tbeusedasav ar
iabl
ename.

I
nANSICt
hemaxi
mum l
engt
hofav
ari
abl
eis32char
sbuti
nc++t
her
eisnobar
.

2 P.
T.
2 O
Lect
ure-
7

BASI
CDATATYPESI
NC++

C++Dat
aTy
pes

Userdef i
ned Bui
l
tint
ypes Deri
vedty
pe
ty
pe Arr
ay
Struct
ure Funct
io
Union n
Class poi
nter
enumer ati
on

v
oid
I
ntegr
alt
ype Fl
oat
ingpoi
nt

i
nt char f
loat doubl
e

BothCandC++compi l
erssupportal
lthebuilti
nt y
pes.Wi
ththeexceptionofvoi
dthebasic
datat
ypesmayhav esev er
almodi f
ier
spr eceding t
hem to ser
vet heneedsofv ar
ious
si
tuati
ons.Themodif
ierssi
gned,unsigned,longandshortmayappl iedtocharact
erand
i
ntegerbasi
cdat
atypes.Howeverthemodi f
ierlongmayal
sobeappl i
edt odoubl
e.

Dat
aty
pesi
nC++canbecl
assi
fi
edunderv
ari
ouscat
egor
ies.

2 P.
T.
2 O
TYPE BYTES RANGE

char 1 -
128t
o–127

usi
gned 1 0t
o265

sgnedchar 1 -
128t
o127

i
nt 2 -
32768to
32768
unsi
gnedi
nt 2 0t
o65535

si
ngedi
nt 2 -
32768to
32768
shor
tint 2 -
32768to
32768

2 P.
T.
2 O
l
ongi
nt 4 -
2147483648to
2147483648
si
gnedl
ongi
nt 4 -
2147483648to
2147483648
unsi
gnedl
ongi
nt 4 0t
o4294967295

f
loat 4 3.
4E-
38t
o3.
4E+38

doubl
e 8 1.
7E-
308t
o1.
7E+308

l
ongdoubl
e 10 3.
4E-
4932t
o1.
1E+4932

Thet
ypev
oidnormal
l
yused
for
:

1)Tospeci
fyther
etur
ntypeoff
uncti
onwheniti
snotr
etur
ninganyv
alue.
2)Toi
ndicat
eanempt yar
gumentl
istt
oafuncti
on.

Exampl
e:

Voi
dfunct
ion(
voi
d);

Anot
heri
nter
est
inguseofv
oidi
sint
hedecl
arat
ionofgenet
icpoi
nter

Exampl
e:

Voi
d*gp;

Assigni
nganypoi
nterty
pet oav oidpoi
nterwit
houtusi
ngacastisal
l
owedinbot hCand
ANSIC.I nANSICwecanal soassignavoidpoi
ntert
oanon-
voidpoi
nterwi
thoutusi
nga
casttononvoi
dpoi
ntertype.Thi
sisnotal
lowedinC++.

Exampl
e:

v
oid*
ptr
1;

v
oid*
ptr
2;

Ar
eval
i
dst
atementi
nANSICbutnoti
nC++.Weneedt
ouseacastoper
ator
.

pt
r2=(
char*)pt
r1;

USERDEFI
NEDDATATYPES:

STRUCTERSANDCLASSES

2 P.
T.
2 O
Wehav euseduserdef
ineddat
atypessuchasstruct
,andunioninC.Whil
ethesemore
featur
eshavebeenaddedtomakethem sui
tabl
eforobjectori
entedpr
ogramming.C++
alsopermi
tsustodefi
ne

2 P.
T.
2 O
anotheruserdefineddatatypeknownasclasswhichcanbeusedjustl
ikeanyotherbasi
c
datat y
pet odecl
areav ar
iable.Thecl
assv
ariabl
esareknownasobject
s,whicharethe
centralfocusofoops.

ENUMERATEDDATATYPE:

Anenumerateddatatypeisanotheruserdefi
nedt ypewhichprovi
desaway
foratt
achingnamest onumber ,t
hesebyi ncr
easingcompr ehensi
bil
it
yoft hecode.The
enum keywordautomat
ical
lyenumerat
esalistofwordsbyassi gni
ngthem v
alues0,
1,2and
soon.Thi
sf aci
l
itypr
ovi
desanalter
nati
vemeansf orcr
eati
ngsy mbolic.

Exampl
e:

enum shape

{ ci
rcl
e,squar
e,t
ri
angl
e} enum

col
our
{red,
blue,
green,
yel
low}

enum posi
ti
on{
off
,on}

Theenumerat
eddatat
ypesdif
fersl
ight
lyi
nC++whencompar
edwithANSIC.I
nC++,
thet
agnamesshape,colour
,andpositi
onbecomenew t
ypenames.Thatmeanswecan
decl
arenewvar
iabl
esusi
ngthetagnames.

Exampl
e:

Shapeel
li
pse;
//el
li
psei
soft
ypeshape

col
ourbackgr
ound;
//backgr
oundi
soft
ypecol
our

ANSICdefi
nesthetypesofenumst
obeints.I
nC++,
eachenumer
ateddat
at y
pe
ret
ainsi
tsownseparat
etype.Thi
smeansthatC++doesnotall
ow ani
ntval
uet obe
automat
ical
l
yconv
ert
edtoanenum.

Exampl
e:

col
ourbackgr
ound=bl
ue;
//v
aid

col
ourbackgr
ound=7;
//er
rori
nc++

col
ourbackgr
ound=(
col
our
)7;
//ok

Howev
eranenumer
atedv
aluecanbeusedi
npl
aceofani
ntv
alue.

Exampl
e:

i
ntc=r
ed;
//v
ali
d,col
ourt
ypepr
omot
edt
oint

Bydefault
,theenumerator
sareassi
gnedi
ntegerval
uesst
art
ingwi
th0f
ort
hef
ir
st
enumerat
or,
1f orthesecondandsoon.Wecanal
sowr i
te

enum col
or{
red,
blue=4,
green=8};
2 P.
T.
2 O
enum col
or{
red=5,
blue,
green}
;

2 P.
T.
3 O
C++al
soper
mit
sthecr
eat
ionofanony
mousenums(i
.e,
enumswi
thoutt
ag

names)Exampl
e:

enum{
off
,on}
;

Hereoffi
s0andoni
s1.
theseconst
ant
smayber
efer
encedi
nthesamemannerasr
egul
ar
const
ants.

Exampl
e:

i
ntswi
tch-
1=of
f;

i
ntswi
tch-
2=on;

ANSICpermi
tsanenum defi
nedwit
hinastruct
ureoraclass,butt
heenum
i
sgl
obal
l
yvi
sibl
e.I
nC++anenum def
inedwit
hinaclassi
slocalt
othatclass.

3 P.
T.
3 O
LECTURE-
8

SYMBOLI
CCONSTANT:

Ther
ear
etwoway
sofcr
eat
ingsy
mbol
i
cconst
ant
sinc++.

1.usi
ngthequal
i
fierconst.
2.def
ini
ngasetofintegerconst
ant
susi
ngenum key
wor
ds.

I
nbothCandC++,anyv
aluedeclar
edasconstcan’tbemodi
fi
edbyt
hepr
ogr
am i
nany
way
.
I
nC++,
wecanuseconsti
naconstantexpressi
on.Suchas

consti
ntsi
ze=10
;charname(si
ze)
;

Thi
swouldbei
l
legali
nC.constal
lowsustocr
eatetypedconstant
sinst
eadofhav
ingt
o
use#def
metocreat
econst
antsthathav
enotypeinf
ormation.

constsi
ze=10;

Means

consti
ntsi
ze=10;

C++requir
esaconsttobei
nit
ial
i
zed.ANSICdoesnotr
equi
reani
nit
ial
i
zer
,ifnonei
s
gi
ven,
iti
nit
ial
i
zestheconstt
o0.

I
nC++constv aluesarelocalandi nANSICconstv al
uesar
egl
obal.
Howev
erthey
canbemadelocalmadel ocalbydeclar
ingthem asstat
ic.
InC++i
fwewantt
omakeconst
val
ueasgl
obalthendeclareasexter
nstorageclass.

Ex:exter
nalconstt
otal=100; Anot
her
met
hodofnamingint
egerconstantsi
sasfoll
ows:
-
enum {
x,y
,z}
;

DECLARATI
ONOFVARI
ABLES:

I
nANSICCal lthevari
ablewhichistobeusedi npr
ogramsmustbedecl aredatthe
beginni
ngoft heprogram .ButinC++wecandecl arethevari
abl
esanywhosei nthe
program wher
eitrequir
es.Thismakest hepr
ogram mucheasiertowrit
eandr educesthe
errorst
hatmaybecausedbyhav i
ngt oscanbackandf ort
h.Ital
somakest hepr ogr
am
easiert
ounderst
andbecauset hevar
iabl
esaredecl
aredinthecont
extofthei
ruse.

Exampl
e:
main(
)
3 P.
T.
3 O
{
f
loatx,
aver
age;
f
loatsum=0;

3 P.
T.
3 O
f
or(
inti
=1;i<5;
i++)
{
cin>>x;
sum=sum+x
}
floataverage;
average=sum/ x;
cout<<average;
}

REFERENCEVARI ABLES:
C++interfacesanewki ndofv ar
iableknownast hereferencevar
iabl
e.Aref
erences
vari
ableprovi
desanal i
as.(alternati
vename)f orapreviousl
ydef i
nedvari
abl
e.Forexample
,
i
fwemaket hev ari
ablesum ar ef
erencet ot hevari
abletot
al,thensum andtot
alcanbe
usedinter
changeabl ytorepr esentthevariuble.
Areferencev ari
ablei screatedasf oll
ows:
Synatx:Dat at
ype&r eference–name=v ariabl
ename;

3 P.
T.
3 O
Exampl
e: f
loattot
al=1500;
f
loat&sum=t ot
al;

3 P.
T.
3 O
Heresum isthealter
nati
venamef orv
ariablestotal,
boththev
ariabl
esref
ert
othesamedat
a
obj
ectinthememor y.
Areferencevari
ablemustbeini
ti
alizedatthet i
meofdeclarat
ion.
Not et
hatC++assignsaddit
ional meaningtothesymbol&here&isnotan
addressoperator
.
Thenotat
ionf oat&meansr
l efer
encetofloat.
Example:
intn[10];
int&x=n[10];
char&a=’\ n’
;

3 P.
T.
3 O
LECTURE-
9

OPERATORSI
NC++:

C++hasari
chsetofoper
ator
s.Al
lCoper
ator
sar
eval
i
dinC++al
so.I
naddi
ti
on.C++
i
ntr
oducessomenewoperat
ors.

<< i
nser
ti
onoper
ator

>> ext
ract
ionoper
ator

:
: scoper
esol
uti
onoper
ator

:
:* poi
ntert
omemberdecl
arat
or

* poi
ntert
omemberoper
ator

.
* poi
ntert
omemberoper
ator

Del
ete memor
yrel
easeoper
ator

Endl l
i
nef
eedoper
ator

New memor
yal
l
ocat
ionoper
ator

Set
w f
iel
dwi
dthoper
ator

SCOPERESOLUTI
ONOPERATOR:

LikeC,C++i salsoabl ock-str


uctur
edlanguage.Bl
ock-st
ruct
uredl anguage.
Blocksandscopescanbeusedi nconstructi
ngprogr
ams.Weknowsamev ari
ablescanbe
declar
edindiffer
entblocksbecauset hev ari
abl
esdeclaredinbl
ocksarel ocaltot hat
functi
on.
Blocks in C++ are of t
en
nested.Example:
-
--
--
---
--
--
--
--
-
--
--
--
---
--
--
--
{
I
ntx=10;
-
--
--
--
--
--
---
-
-
--
--
--
--
--
---
-
{

Intx=1; Bl
ock2
---
--
--
--
--
--
-- Bl
ock1
---
--
--
--
--
--
--
}
-
--
--
--
--
--
---
--
-
--
--
--
--
--
---
--

}
Block2cont ai
nedinblockl.
Notethatdeclarat
ioni
naninnerblockhi
desadeclar
ationoft
he
samev ar
iablei
nanout erbl
ockandthereforeeachdecl
arat
ionofxcausesi
ttorefertoa
diff
erentdataobject.Withi
ntheinnerblockthevar
iabl
exwi l
lref
ert
othedataobject
3 P.
T.
3 O
decl
aredt
her
ein.

3 P.
T.
3 O
I
nC,theglobalversi
onofav ar
iablecan'
tbeaccessedfrom wit
hinthe
i
nnerbl
ock.C++resolv
est hi
spr obl
em byintr
oducinganew operator::cal
ledthescope
r
esol
uti
onoperat
or.Thi
scanbeusedt ouncov
erahi ddenvar
iabl
e.

Sy
ntax: ::v
ari
abl
e–name;

Exampl
e:
#i
ncl
ude
<iostrcam. h>
i
ntm=10;
mai n()
{
i
ntm=20;
{
i
ntk=m;
i
ntm=30;
cout <<”wear eini nner
block” ;
cout <<"k="<<k<<endl;
cout <<"m=" <<m<<endl ;
cout <<":
:m=" <<::m<<endl ;
}
cout <<”\nwear einout erblock
\n”;cout <<"m=" <<m<<endl ;
cout <<":
:m=" <<::m<<endl ;
}

Memor
yManagementOper
ator
Cusesmall
ocandcallocfuncti
onstoall
ocatememor ydynamical
l
yatrunt
ime.Si
milar
lyi
t
uses t
he f
uncti
ons Free()t ofree dynamical
l
y all
ocated memory
.We use dynamic
al
locat
iont
echni
queswheni ti
snotknowni nadvancehow muchofmemor yspaceas
needed.

C++al
sosupportthosef
uncti
onsital
sodef
inest
wounar
yoper
ator
snew
anddel
etet
hatper
for
mt hetaskofall
ocat
ingandfr
eei
ngthememoryi
nabett
erand
easi
erway.

Thenewoper
atorcanbeusedt
ocr
eat
eobj
ect
sofanyt
ype.

Sy
ntax: poi
nter

-v
ari
abl
e=newdat
aty
pe;

Exampl
e:
p=newi
nt;
q=newi
nt;

Wher
epi
sapoi
nteroft
ypei
ntandqi
sapoi
nteroft
ypef
loat
.

i
nt*
p=newi
nt;

3 P.
T.
3 O
f
loat

*
p=newf
loat
;

Subsequent
ly,
thest
atement
s

*
p=25;

3 P.
T.
4 O
*
q=7.5;
Assign25t
othenewlycr
eat
edi
ntobjectand7.
5tot
hef
loatobj
ect
.Wecanal
so
i
nit
ial
i
zethememoryusi
ngthenewoper
ator.

Sy
ntax:
int*p=ne\vint(
25);
fl
oat* q=newfloat(
7.5)
;
newcanbeusedt ocreat
eamemor yspaceforanydatatypeincl
udi
nguser
def
inedsuchasarray
s,st
ructures,
andclasses.Thegener
al f
ormforaone-
di
mensionalar
rayi
s:

poi
nter
-var
iabl
e=newdat
aty
pes[
size]
;

cr
eat
esamemor
yspacef
oranar
rayof10i
nteger
s.

I
fadat
aobj
ecti
snol
ongerneeded,
iti
sdestroy
edt
orel
easet
hememor
yspace
f
orreuse.

Sy
ntax:del
etepoi
nter
-var
iabl
e;

Exampl
e:
del
etep;
del
eteq;

4 P.
T.
4 O
I
fwewantt
ofr
eeady
nami
cal
l
yal
l
ocat
edar
ray,
wemustuset
hef
oll
owi
ng
for
m of
del
ete.
del
ete[
size]poi
nter
-
var
iabl
e;or

del
ete[]poi
nterv
ari
abl
e;

4 P.
T.
4 O
MANI
PULATERS:

Manipul
ator
sareoper atort hatar
eusedt
ofor
matthedatadi
spl
ay.Themost
commonl
ymanipulat
orsareendl andsetw.
Theendl manipulator ,
whenusedi
nanout
putstat
ement,
causesal
inefeedt
o
beinser
t.(
justli
ke\ n)

Exampl
e:
cout <<”
m=” <<m<<endl
;
cout <<”
n=”<<n<<endl
;
cout <<”
p=”<<p<<endl
;
Ifweassumethev al
uesoft hev ar
iablesas2597,
14and
175r espectiv
elym=2597; n=14;
p=175
Itwaswanttopr
intallnosinr ightjusti
fi
edwayusesetwwhi
chspeci
fya
commonf i
eldwi
dthforal lthenos.

Exampl
e: cout
<<setw(5)<<sum<<endl;
cout
<<setw(10)<<”
basic”
<<setw(10<<basic<<endl
;
Cout<<set
w(10)<<”al
lowance”<<setw(10<<al
lowance<<endl
;
cout
<<setw(10)<<”t
otal
=”<<setw(10)<<t
otal;

4 P.
T.
4 O
LECTURE-
10

CONTROLSTRUCTURES:

Li
kec,c++,suppor
tsal
lthebasi
ccont
rol
str
uct
uresandi
mpl
ement
sthem v
ari
ouscont
rol
st
atements.

Thei
fst
atement
:

Thei
fst
atementi
simpkl
ement
edi
ntwof
orms:

1. si
mpl
eifst
atement

2. i
f…el
sest
atement

Si
mpl
eifst
atement
:

i
f(condi
ti
on)

Act
ion;

I
f.
.el
sest
atement

I
f

(
condi
ti
on)

St
atment
1

El
se

St
atement

4 P.
T.
4 O
Theswi
tchst
atement

Thisi
samul
tipl
e-br
anchi
ngst
atementwhere,basedonacondi
ti
on,
thecont
rol
is
tr
ansf
err
edt
ooneoft hemanypossi
blepoi
nts;

4 P.
T.
4 O
Swi
tch(
expr
)

case

1:

act
ion

1;

br
eak;

case

2:

act
ion

2;

br
eak;

.
.

.
.

def
aul
t:

messa

ge

Thewhi
le

st
atement
:Sy
n:

Whi
l
e(condi
ti
on)

St
ement
s
4 P.
T.
4 O
}

4 P.
T.
4 O
Thedo-
whi
lest
atement
:

Sy
n:

do

St
ement
s

}whi
l
e(condi
ti
on)
;

Thef
orl
oop:

f
or(
expr
essi
on1;
expr
essi
on2;
expr
essi
on3)

St
ateme

nt
s;

St
ateme

nt
s;

4 P.
T.
4 O
LECTURE-
11

FUNCTI
ONI
NC++:

Themain()Funct
on;
ANSIdoesnotspeci
fyanyret
urntypef
orthemain()funct
ionwhi
chi
sthest
art
ing
poi
ntf
ortheexecuti
onofaprogram .Thedef
ini
ti
onofmain()is:
-

mai
n()
{
/
/mainpr
ogr
am st
atement
s
}

Thisispropert
yvali
dbecauset
hemain()inANSICdoesnotreturnanyv al
ue.I
nC++,the
mai n()r
etur
nsav al
ueoftypei
nttot
heoperati
ngsyst
em.Thefuncti
onsthathavear
eturn
valueshoulduset heret
urnstat
ementfortermi
nati
ng.Themain( )functi
oninC++i s
theref
oredefi
nedasfol
lows.

i
ntmain()
{
-
--
--
--
--
--
--
-
-
--
--
--
--
--
--
-
r
etur
n(0)
}
Si
ncetheret
urnt
ypeoffuncti
onsi
sintbydef
aul
t,t
hekeywor
dinti
nthemai
n()headeri
s
opt
ional
.

I
NLI
NEFUNCTI
ON:

Toeliminatet
hecostofcal lstosmallfunctionsC++pr oposesanewf eatur
ecalledinl
ine
funct
ion.Aninli
nefuncti
oni safunct
iont hatisexpandedinli
newhenitisinvoked.Thatis
thecompilerr
eplacesthefunct
ioncal
lwitht hecorr
espondingfunct
ioncode.
Theinli
nefuncti
onsaredefinedasf ol
lows:
-

inli
nef unct i
on-header
{
functionbody ;
}
Exampl
e: i nli
nedoubl ecube( doublea)
{
return(a*a* a);
}
Theaboveinl
inefunctioncanbei nvokedbystatements
li
kec=cube( 3.0);
d=cube(2.5+1.5) ;
rememberthattheinli
nekey wor dmer el
ysendsar equest
,notacommandtot
hecompli
l
er.
The compil
ermay i gnoret hisr equestift he f
uncti
on def
ini
ti
on i
stoo l
ong ort
oo
compli
catedandcompi l
ethef uncti
onasanor mal f
uncti
on.
4 P.
T.
4 O
Someoft
hesi
tuat
ionswhereinl
ineexpansionmaynotwor
kare:
1.Forf
unctionsr
etur
ningvaluesifaloop,
aswit
choragotoexi
sts.

4 P.
T.
5 O
f
orfuncti
onsnotr et
urningvalues,i
far
etur
nst
atementex
ist
s.
3.i
ffuncti
onscontai
nstaticvari
ables.
4.i
finl
inefunct
ionsarerecursi
ve,.
Exampl
e:
#i
nclude<i
ostream.h>
2.
#i
nclude<st
dio.h>
i
nli
nefloatmul(fl
oatx,f
loaty
)
{

5 P.
T.
5 O
r
etur
n(x*
y);
}
i
nli
nedoubl
ediv(doubl
ep.
doubl
eq)
{

5 P.
T.
5 O
r
etur
n(p/
q);
}

mai
n()
{
fl
oat
a=12.345;
fl
oatb=9.82;
cout<<mul(
a,b)
<<endl
;
} cout<<di
v(a,
b)<<endl
;

5 P.
T.
5 O
5 P.
T.
5 O
out
put
:-
121.
227898
1.
257128
DEFAULTARGUMENT:
-

5 P.
T.
5 O
C++al lowsust ocal laf unct i
onwi thoutspeci fyi
ngal litsar guments.Insuchcases,
thef unct i
onassi gnsadef aul tv aluet ot hepar amet erwhi chdoesnothav eamat ching
agument si nt hef unctioncal l.
Def aultv aluesar especi fi
edwhent hefunctioni sdeclared
.Thecompi lerl ooksatt hepr ot ot ypet oseehow manyar gument saf uncti
onusesand
alertsthepr ogr am f orpossi bledef aultv alues.
Exampl e: f
loatamount( floatpr i
ncipl e,intper i
od, fl
oatr at e=0.15);
Thedef aultv aluei sspeci fi
edi namannersy nt act i
call
ysimilartoav ariable
i
nitiali
zation. Theabov epr ot otypedecl aresadef aultv alueof0. 15t otheargumentr ate.A
subsequentf unct ioncal l l
i
ke
value=amount (5000, 7) ;//onear gumentmi ssing
passest hev al ueof5000t opr incipl eand7t oper i
odandt henl et
st hefunction,usedef aul
t
valueof
0.15f orrate.
Thecal l:-val ue=amount (
5000, 5,0.12);
//nomi ssingar gumentpassesanexpl i
citevalueof0. 12rate.
Onei mpor tantpoi ntt onot ei st hatonl ythet rail
ingar gument scanhav edefaultvalues.That
i
s,wemustadddef aultfr om r ightt ol ef t. Wecannotpr ov ideadef aulttoapar t
icular
argumenti nt hemi ddleofanar gumentl i
st .
Exampl e:- int mul (i
nt i ,i nt j =5,int
k=10) ;//i
llegali ntmul (
inti =0,int
j
,int k=10) ;
//il
legal i nt mul (
int
i
=5, intj );
//ill
egal
i
ntmul (i
nti=2, i
ntj =5,intk=10) ;//
ill
egal
Def aultar gument sar eusef uli nsi tuat i
onwhosesomear gument sal way shav et he
somev alue.
Forexampl e,banki nterestmayr etaint hesamef orallcust omer sforapar t
icularper i
odof
deposi t.

5 P.
T.
5 O
Exampl
e:
#include<i ostream. h
>#i nclude<st dio.h>
mai nQ
{
fl
oatamount ;
fl
oatv alue(f
loatp, i
ntn,fl
oatr=0.15)
;
voidpr intli
ne(charch=’ *’
,i
ntlen=40)
;
printli
ne() ;
amount =v al
ue( 5000.00,5);
cout <<”\nf i
nalv alue=”<<amount<<endl
;pr
int
li
ne(
‘=’
);
//funct i
ondef initi
ons
fl
oatv alue(fl
oatp, intn,fl
oatr)
{

5 P.
T.
5 O
fl
oatsi ;
si=(p*n*r
)/100;
return(si
);
}
voi
dprintl
ine( charch,i
ntl en)
{
for(i
nt i
=l;
i<=l
en;i++)
cout <<ch<<endl;
}
out
put:-
****************f i
nal
val
ue=10056. 71613
===============
Adv
ant
ageofprov idi
ngt hedef aultar
gument
sare:
1.Wecanusedef aultargument stoaddnewparameter
stotheexi
sti
ngfunct
ions.
2.Def
aultargumentscanbeusedt ocombinesimi
l
arfunct
ionsi
ntoone.

CONSTARGUMENT: -
In C++, an argumentt oaf unct
ion canbe decl
aredas unitas constasshown
below.
intstr
len(constchar*p);
int l
engt h(
constst ri
ng
&s);
The qual
if
ierconstt ell
st he compilerthatt
he f
uncti
on shoul
d notmodi f
ythe
argument.thecompi lerwil
lgener ateanerrorwhenthi
scondit
ionisvi
olated.Thi
sty
peof
declar
ati
onissignif
icantonlywhenwepassar gument
sbyrefer
enceorpointer
s.

5 P.
T.
5 O
LECTURE-
12

FUNCTI
ONOVERLOADI
NG:

Overl
oadingreferst otheuseoft hesamet hingf ordif
fer
entpur poses.C++
alsopermitsover
loadingfunctions.Thi
smeanst hatwecanuset hesamef unct i
onnamet o
creat
esf uncti
onst hatperform av ar
iet
yofdi ff
erenttasks.Thi si sknownasf uncti
on
polymorphi
sm inoops.
Usingtheconcept soff uncti
onov er
loadi
ng,af ami l
yoff unctionswi t
hone
functi
onnamebutwi thdi
fferentargumentl i
stsinthefunct i
onscall.Thecorrectfuncti
onto
beinvokedisdeterminedbychecki ngthenumberandt y
peoft heargument sbutnotont he
functi
ontype.
Forexampl eanov erl
oadedadd( )functi
onhandl esdiffer
enttypesofdat aasshown

5 P.
T.
5 O
bel
ow.
/
/Decl
arat
ion
intadd(i
nta,i
ntb) ;
/ /
prototype1
intadd(inta,
intb,intc);//
pr ototype2
doubleadd(doublex, doubl
ey )
; /
/prot
oty
pe
3doubl eadd(doublep, doubleq) ;
//prot
otype4

6 P.
T.
6 O
//f
unct i
oncall
cout<<add(5,
10) ;
//usespr ototype1
cout<<add(15,10.
0);//usespr ototype4
cout<<add(12.5,
7.5);//usespr ototype3
cout<<add(5,
10,15);//usespr ototype2
cout<<add(0.75,
5);//usespr ototype5
Afunct
ioncall
firstmatchesthepr ototypehav ingthesamenoandt
ypeofar
gument
sand
t
hencallst
heappr opri
atefuncti
onf orexecut i
on.
Thef uncti
onselecti
oni nvokest hefoll
owingsteps:
-

a)The compi lerfirstt ri


es t of i
nd an exactmat chinwhichthetypesofactual
argument sarethesameanduset hatfuncti
on.
b)Ifanexactmat chi snotf oundthecompi l
erusest heintegr
alpromotionst
ot he
actualargumentssuchas:
chart oint
floatto
doubl eto
findamat ch
c) Wheneitheroft hem t ai
ls,t
hecompi lertri
estouset hebuil
tinconver
sionstothe
act
ualargument sandt hem usest hefuncti
onwhosemat chisunique.Iftheconversi
onis
possi
bletohavemul ti
plemat ches,thenthecompi lerwi
llgiv
eer r
ormessage.
Exampl e:
l
ongsquare( l
ongn) ;
doublesquare(double
x);
Af unct
ioncallsuchas: -square(l
O)

Wil
lcauseanerr
orbecauseintar
gumentcanbeconver
tedt
oei
ther
l
ongordoubl
e.Ther
ebycreat
inganambiguoussit
uat
ionastowhi
chversi
onof
squar
e()
shoul
dbeused.

6 P.
T.
6 O
PROGRAM

#include<i ostream. h
>int
volume( doubl e,i
nt) ;
doubl ev olume(doubl e,int);
doubl ev olume( longint,i
nt
,i
nt );
mai n()
{
cout <<vol
ume( 10)<<endl
;
cout <<vol
ume( 10)<<endl
;cout
<<v
olume(
10)
<<endl
;
}
i
ntv olume(i nis)
{
retur
n( s*s*s);//cube
}
doubl ev olume(doubl er,inth)
{
r
et urn(3.1416* r*
r*h);/
/cyli
nder
}
l
ongv olume( l
ongi nt1,intb,inth)
{
r
et urn(1*b* h);/
/cyli
nder
}

out
put
:-1000
157.
2595
112500

6 P.
T.
6 O
Modul
e-2:

LECTURE-
13

CLASS:-
Classisagr oupofobject sthatshar ecommonpr oper t
iesandr el
ationshi
ps.InC++,
aclassisanew dat at y
pet hatcont ai
nsmemberv ar i
ablesandmemberf unct
ionsthat
oper
atesont hevari
ables.Aclassisdef i
nedwi ththekey wor dclass.Ital
l
owst hedatatobe
hi
dden,ifnecessaryfrom externaluse.Whenwedef iningacl ass,wear ecreati
nganew
abst
ractdatatypethatcanbet reat
edl i
keanyot herbui ltindatat ype.
General
lyaclassspeci fi
cationhast wopar ts:-
a) Cl assdeclaration
b) Cl assfunctiondef ini
ti
on
theclassdecl arat
iondescr ibest het ypeandscopeofi t
smember s.Thecl ass
funct
iondefini
tiondescri
beshowt heclassf unctionsar eimpl emented.

Syntax:-
cl
asscl ass-name
{
priv
at e:
variable
declarations;
function
declaration;
public:
variabledeclarati
ons;
functiondecl ar
ation;
};
Themember sthathav ebeendecl aredaspr ivatecanbeaccessedonly
from withinthecl ass.Ont heot herhand,publ i
cmember scanbeaccessedf r
om outside
theclassalso.Thedat ahidingi st hekeyf eatur
eofoops.Theuseofkey wordsprivat
ei s
optionalbydefault,t
hemember sofacl assar eprivate.
Thev ariablesdecl aredi nsidet heclassar eknownasdat amember sandt he
functi
onsar eknownasmember smi dt hefunctions.Onl ythememberfuncti
onscanhav e
accesst othepr i
vat edat amember sandpr i
vatef uncti
ons.However,t
hepubl i
cmember s
canbeaccessedf rom t heout sidet hecl ass.Thebi ndingofdataandf unct
ionstogether
i
nt oasingleclasst y
pev ar
iableisr eferredt oasencapsul ati
on.

Sy
ntax:
-
cl
assi
tem
{

6 P.
T.
6 O
i
nt
member ;
publ
i
c:f
loatcost;

voi
dgetl
data(
inta,f
loat
b);
voi
dputdat
a( v
oid);

6 P.
T.
6 O
Theclassit
em containstwodatamember sandtwof uncti
onmember s,the
datamember sarepri
vatebydefaul
twhi l
ebotht
hef uncti
onsarepubl i
cbydecl
arat
ion.The
funct
iongetdat
a()canbeusedt oassignval
uest
ot hememberv ar
iablesmemberandcost,
andputdata()f
ordispl
ayingthei
rvalues.Thesefunctionspr
ovidet heonl
yaccesst othe
datamember sfr
om outsi
detheclass.

6 P.
T.
6 O
CREATINGOBJECTS:
Once a classhas been decl
aredwe can createvari
abl
esof t
hat
ty
pebyusi ngt hecl
assname.
Example:
item x;
createsav ari
ablesxoftypeit
em.InC++,t
hecl
assv
ariablesar
eknownasobj
ect
s.
Ther
eforexi scall
edanobj ectoft
ypeit
em.

item x,
y, zalso
possible.cl
assi t
em
{
--
--
---
---
-
--
--
---
---
-
--
--
---
---
-
}x,y,z;
wouldcr eatetheobj
ect
sx,
y,zoft
ypei
tem.

ACCESSI NGCLASSMEMBER:
Thepr i
vatedat aofacl asscanbeaccessedonl ythroughthememberf unct
ions
ofthatclass.Themai n(
)cannotcont ainsstatement sthatt heaccessnumberandcost
di
rectl
y.
Syntax:
objectname. functi
on-name( act ual
argument s);Exampl e:
-x.get data(100,75.5);
Itassignsv alue100t onumber ,and75. 5tocostoft heobj
ectx
byimplement i
ngt heget data()function.
si
mi l
arl
yt hest atement
x.putdat a();//woulddi splaythev aluesofdat amember s.
x.number=100i sil
legal .
Alt
houghxi sanobj ectoft hetypeitem towhi
chnumber
bel
ongs, t
henumbercanbeaccessedonl ythroughamemberf uncti
onandnotbyt he
obj
ectdi r
ectl
y.
Exampl e:
classxy z
{

6 P.
T.
6 O
I
ntx;
I
nty;
publ
i
c:
i
ntz;
};

6 P.
T.
6 O
--
--
--
--
-
--
--
--
--
--
xyzp;
p.x=0; er
ror.xi
spri
vat
e
p,z=10; ok,zi
spubl
i
c

6 P.
T.
6 O
LECTURE-
14

DEFI
NINGMEMBERFUNCTION:
Membercanbedefi
nedintwoplaces
• Outsidet
heclassdefi
nit
ion
•I nsi
detheclassfunct
ion

OUTSI
DETHECLASSDEFl
NAT1ON;

Memberf
unct
ionthatar
edeclar
edi
nsi
deaclasshav
et obedefi
ned
separ
atel
yout
sidet
hecl
ass.
Thei
rdefi
nit
ionarev
erymuchl
iket
henormalfunct
ions.

Animport
antdi
fferencebet weenamemberf unct
ionandanormal
funct
ioni
sthatamemberfuncti
oni ncorporat
esamember shi
p.I
denti
fyl
abel
int
heheader
.
The‘l
abel
’tel
l
sthecompil
erwhichcl assthefunct
ionbel
ongsto.

Sy
ntax:

r
etur
ntypecl
ass- name: :
functi
on-
name(argumentdecl
arati
on)
{
f unction-body
}
Themembershi plabelcl ass-name: :tel
l
st hecompilerthatthefuncti
on
f
uncti
on-namebel ongstothecl asscl ass-name.Thatist hescopeoft hefunct
ionis
r
estr
ict
edt otheclass-namespeci fi
edi nt heheaderli
ne.The::symboli scal
ledscope
r
esol
utionoperat
or.

Exampl
e:
voidit
em ::getdata(i
nta, f
loatb)
{
number =
a;cost=b;
}
voidit
em ::putdata(void)
{
cout<<”number=:”<<number <<endl;
cout<<”cost
=”<<cost <<endl
;
}
Thememberf uncti
onhav esomespeci alchar acteri
sti
csthatareoftenusedinthe
pr
ogr
am dev
elopment.
•Sever
al di
fferentclassescanuset hesamef uncti
onname.The
"
member shiplabel"willr
esolvetheirscope, memberf uncti
onscanaccess
t
hepriv
atedat aoft heclass
.
Anonmemberf unctioncan'tdoso.
•Amemberf unct i
oncancal lanothermemberf unctiondir
ectly
,wit
houtusi
ng
t
hedotoper ator.
6 P.
T.
6 O
INSI
DETHECLASSDEF1NATI ON:
Anot
hermethodofdefi
ningamemberf unct
ioni
storepl
acet
hef
unct
ion
decl
arati
onbytheactual
functi
ondefini
ti
oni
nsidet
heclass.
Example:
classit
em
{

7 P.
T.
7 O
Int
numbe
r;f
loat
publ
i
c:cost;

voi
dgetdat
a(i
nta,fl
oat
b);
voi
dputdat
a(v
oid)
{

7 P.
T.
7 O
cout
<<number
<<endl
;cout
<<cost
<<endl
;
}
}
;
A C++ PROGRAM WI
THCLASS:
#include<iost
ream.h>
classitem
{

7 P.
T.
7 O
i
nt
number;
publ
i
c:fl
oatcost
;

v
oidgetdat
a(inta,floatb)
;
v
oidputdal
a(void)
{
cout
<<“
number :”
<<number<<endl
;
cout
<<”
cost:”<<cost
<<endl
;
}
};

7 P.
T.
7 O
v
oidi
tem :
:get
data(inta, f
loatb)
{
number =
a;cost=b;
}
main()
{
it
em x;
cout<<”\nobjectx”<<endl;
x.getdata(100, 299.95);
x
.
putdata();
it
em y ;
cout<<”\nobjecty ”<<endl;
y.getdata(200,175.5);
y.putdata();
}

Out
put
: obj
ectx
number100

7 P.
T.
7 O
cost=299.
950012
object-
4
cost=175.
5

Q.
Writ
easi mplepr ogr am usi ngcl assinC++toinputsubj
ectmar
kand
pr
intsi
t.ans:
classmar ks
{
private:
intml ,
m2;
publ i
c:
voidget data(
);
void
display data()
;
};
voidmar ks: :get data()
{
cout <<” enter1stsubj ect
mar k:”; cin>>ml ;
cout <<” enter2ndsubj ect
mar k:”; cin>>m2;
}
voidmar ks: :display data()
{
cout <<” Istsubj ect
mar k:”<<ml <<endl ;cout<<”
2nd
subjectmar k:”<<m2;
}
voidmai n( )
{
clrscr(
);
mar ksx;
x.getdata()
;
x.displ
ay dat a() ;

7 P.
T.
7 O
LECTURE-
15

NESTI
NGOFMEMBERFUNCTI
ON;

Amemberf
unct
ioncanbecall
edbyusi
ngi
tsnameinsi
deanot
hermember
f
unct
ionoft
hesamecl
ass.Thi
sisknownasnest
ingofmemberf
unct
ions.

#incl
ude<iostream.h>
cl
assset
{
i
ntm, n;
publ
ic:
v
oidinput(voi
d);
v
oiddisplay(void)
;
v
oidlargest(v
oid);
};
i
ntset::
lar
gest( v
oid)
{
i
f(m>n)
r
eturnm;

7 P.
T.
7 O
el
se
r
etur
nn;
}

7 P.
T.
7 O
voi
dset:
:i
nput (
voi
d)
{
cout<<”i
nputvaluesofm and
n:
”;cin>>m>>n;
}
voi
dset:
:displ
ay(v
oid)
{
cout
<<”l
argestval
ue=”<<lar
gest
()<<”
\n”
;
}
voi
dmain()
{

7 P.
T.
7 O
setA;
A.i
nput
();
A.di
spl
ay()
;
}

outpu
t:

7 P.
T.
7 O
I
nputv
aluesofm andn:

3017

l
argestv
alue=30

8 P.
T.
8 O
Pr
ivat
ememberf
unct
ions:

Al
thoughi
tisanor
malpr
act
icet
opl
aceal
lthedat
ait
emsi
napr
ivat
esect
ionandal
lthe
f
unct
ionsi
npubl
i
c,somesi
tuat
ionsmayr
equi
recont
ainf
unct
ionst
obehi
ddenf
rom t
he
out
sidecal
l
s.Taskssuchasdel
eti
nganaccounti
nacust
omerf
il
eorpr
ovi
dingi
ncr
ement
t
oandempl
oyeear
eev
ent
sofser
iousconsequencesandt
her
efor
ethef
unct
ionshandl
i
ng
sucht
asksshoul
dhav
erest
ri
ctedaccess.Wecanpl
acet
hesef
unct
ionsi
nthepr
ivat
e
sect
ion.

Apr
ivat
ememberf
unct
ioncanonl
ybecal
l
edbyanot
herf
unct
iont
hati
samemberofi
ts
cl
ass.Ev
enanobj
ectcannoti
nvokeapr
ivat
efunct
ionusi
ngt
hedotoper
ator
.

Cl
asssampl
e
{
i
ntm;
v
oidr
ead(
voi
d);
v
oidwr
it
e(v
oid)
;
}
;
i
fsi
isanobj
ectofsampl
e,
t
hens.
read(
);
i
sil
l
egal
.Howev
ert
hef
unct
ionr
ead(
)canbecal
l
edbyt
hef
unct
ionupdat
e()
t
oupdat
ethev
alueofm.
v
oidsampl
e::
updat
e(v
oid)
{
r
ead()
;
}

8 P.
T.
8 O
#i
ncl
ude<i
ost
ream.
h>
classpart
{
pr
ivat
e:
intmodelnum,
par
tnum;
floatcost
;

8 P.
T.
8 O
publ
i
c:
v
oidset
par
t(i
ntmn,
intpn,
fl
oatc)
{

8 P.
T.
8 O
model mi
m=mn;
part
num=pn;
cost=e;
}
v
oidshowpar
t()
{
Cout<<endl <<”model :
”<<modelnum<<end
1;Cout <<”num:”<<par tnum <<endl
Cout<<” cost:
”<<”$”<cost;
}
};
voi
dmai n(
)
{
partpl,
p2;
p1.setpar t
(644,
73,217.5
5);
p2.setpar t
(567,
89,789.5
5);pl.
showpar t
();
pl.
showpar t(
);
}

out
put
:-model
:
644
num:
73
cost
:
$217550003
model
:567
num:
89
cost
:$759.
549988

8 P.
T.
8 O
#i
ndude<i
ostr
eam. h>
cl
assdistance
{
pri
vat
e:
intfeet
;
float
inches;

8 P.
T.
8 O
publ
i
c:
v
oidset
dist(i
ntf
t,f
loati
n)
{

8 P.
T.
8 O
f
eet=f
t;
i
nches=i
n;
}
void get dist()
{
cout <<”enterf eet:”;
ci
n>>f eet ;
cout <<”enter
i
nches: ”
; ci
n>>i nches;
}
voidshowdi st(
)
{
cout <<f eet<<”_”inches«endl
;
}
};
voidmai n()
{
distancedl ,
d2;
d1.set dist(
1
1,
6.25) ;
d2.get data();
cout <<endl <<”dist:
”<<d1
.showdi st();cout<<”\n”
<<”di
st2:
”;
d2.showdi st();
}

out
put
:- ent
erf
eet
:12
ent
eri
nches:
6.
25
di
st1:
”11’
-6.
1.5”
di
st2:12’
-6.
25”

8 P.
T.
8 O
LECTURE-
16

ARRAYWI
THCLASSES:

#i
ncl
ude<i
ost
ream.
h>
#i
ncl
ude<coni
o.h>
cl
assempl
oyee
{
pr
ivat
e:
char
name[
20]
;i
nt
age,
sal
;

8 P.
T.
8 O
publ
i
c:
v
oid
get
dat
a()
;
}
; v
oid
put
dat
a()
;

8 P.
T.
8 O
v
oidempl
oyee:
:get
dat
a()
{
cout
<<”
ent
ername
:
”;ci
n>>name;
cout
<<”
ent
erage:
”;
ci
n>>age;
cout
<<”
ent
er
sal
ary
:”;
cin>>sal
;
r
etur
n(0)
;
}
v
oidempl
oyee:
:put
dat
a()
{
cout
<<name
<<endl
;
cout
<<age<<endl
;
cout
<<sal
<<endl
;
r
etur
n(0)
;
}
i
ntmai
n()
{

9 P.
T.
9 O
empl
oyeeemp[
5]:
f
or(i
nti
=0;
i
<5;
i
++)
{
emp[
i]
.get
dat
a()
;
}
cout
<<endl
;
f
or(
i=0;
i
<5;
i
++)
{
emp[
i]
.put
dat
a()
;
}
get
ch(
);
r
etur
n(0)
;
}

ARRAYOFOBJECTS:
-
#i
ncl
ude<i
ost
ream.
h>
#i
ncl
ude<coni
o.h>
cl
assemp
{
pr
ivat
e:
char
name[
20]
;i
nt
age,
sal
;
publ
i
c:
v
oid
get
dat
a()
;voi
d
put
dat
a()
;
}
;
v
oid emp:
:get
dat
a()
{
coul
<<”
ent
erempname”
:.
ci
n>>name;
cout
<<”
ent
er

9 P.
T.
9 O
age:
”<<endl
;ci
n>>age;
cout
<<”
ent
ersal
un:
”;

9 P.
T.
9 O
ci
n>>sal
;
}
v
oid emp:
:put
dat
a()
{
cout
<<”
emp
name:
”<<name<<endl
;
cout
<<”
empage:
”<<age<<endl
;
cout
<<”
empsal
ary
:”<<sal
;
}

v
oid mai
n()
{
emp f
oreman[
5];
emp engi
neer
[5]
;
f
or(
inti
=0;
i
<5;
i++)
{
cout
<<”f
or
f
oreman:
”;f
oreman[
i]
.get
dat
a()
;
}
cout
<<endl
;
f
or(
i=0;
i
<5;
i
++)
{
For
eman[
i]
.put
dat
a()
;.
}
f
or(
inti
=0;
i
<5;
i++)
{
cout
<<”f
or
engi
neer
:”
;
i
ngi
neer
[i
].
get
dat
a()
;
}
f
or(
i=0;
i
<5;
i
++)
{
i
ngi
neer
[i
].
put
dat
a()
;

9 P.
T.
9 O
}
get
ch(
);
r
etur
n(0)
;
}

9 P.
T.
9 O
REPLACEANDSORTUSI
NGCLASS:
-
#i
ncl
ude<i
ost
ream.
h>
#i
ncl
ude<const
ream.
h>
cl
asssor
t
{
pr
ivat
e:
i
ntnm[
30]
;

9 P.
T.
9 O
publ
i
c;

v
oid
get
dat
a()
;
}
:
voi
d
v
oidsor
t::
get
dat
a()
put
dat
a()
;
{

9 P.
T.
9 O
i
nti
,
j,
k;
cout
<<”
ent
er10nos:

;
for
(i
=0;
i
<10;
i
++)
{
ci
n>>nm[
i]
;
}
f
or(
i=0;
i
<9;
i
++)
{
f
or(
j=i
+l:
j
<10:
j
++)
{
i
f(
nm[
i]
>nm[
j]
)
{

9 P.
T.
9 O
k=nm[
i]
;nm[
i]
=nm[
j]
;
nm[
j]
=k;
}

v
oidsort:
:put
dat
a()
{
i
ntk;
f
or(
k=0;
k<10;
k++)
{

9 P.
T.
9 O
cout
<<num [
k]<<endl
;

9 P.
T.
9 O
}
}
i
ntmai n()
{
cl
rscr(
);
sorts;
s.
getdata()
;
s.
putdata()
;r
eturn(0)
;
}
ARRAYOFMEMBERS:
#i
ncl
ude<i
ost
ream.
h>
#i
ncl
ude<const
ream.
h>
consti
ntm=50;
cl
assi
tems
{

1 P.
T.
1 O
0
i
nti
tem_
code[
m];
f
loat
i
tem_
pri
ce[
m];i
nt

publ
i
c:count
;

v
oidcnt
(voi
d){count
=0;
}
v
oidget
_it
em(
voi
d);
v
oid
di
spl
ay_
sum(
voi
d);

}
; v
oidr
emov
e(v
oid)
;
v
oiddi
spl
ay_
item(
voi
d);

1 P.
T.
1 O
1
v
oidi
tems:
:get_i
tem (void)
{
cout<<”ent
er
i
temcode: ”
; ci
n>>
i
tem_ code[code]
;
cout<<”ent
eritem
cost:
”;
ci
n>>item_pr i
ce[
count
];
count++;
}

v
oidi
tems:
:di
splay_sum(void)
{
f
loatsum=0;
f
or(inti
=0;
i<count;
i
++)
{

1 P.
T.
1 O
2
sum=sum+item_pri
ce[
i]
;
}
cout
<<“
\nt
otalval
ue:
”<<sum<<endl
;
}
i
ntmai
n()
{

1 P.
T.
1 O
3
i
tems
order
;
order
.cnt(
);
i
ntx;
do
{
cout<<”\ny
oucandot hefoll
owing:”;
cout<<”ent
erappr opriateno:”;
cout<<endl<<”1:addani tem’’;
cout<<endl<<”2:displaytotalvalue:”
;
cout<<endl<<”3:displayani tem” ;
cout<<endl<<”4:displayallit
em:” ;
cout<<endl<<”5:qui t
:”;
cout<<endl<<endl<<”whati syour
opti
on:”;ci
n>>x;

switch(x)
{
case1: order.
get_item( );
break;
case2: order.
display_ sum();
break;cose3: order .
remov e(
);
break;
case4: order.
display_ i
tem();
break;
case5: break;
default:cout<<”er
r orininput;t
ryagai
n”;
}
}whi
l
e(x!
=5) ;
}

1 P.
T.
1 O
4
LECTURE-
17

STATI
CDATAMEMBER:

Adatamemberofacl asscanbequal i
fi
edasst atic.The
pr
oper
ti
esofast at
icmemberv ariablear esi mi lart othatofast aticv ar
iabl
e.A st ati
c
membervari
ablehascont ainspeci al characteristics.
Variabl
ehascont ainspeci al characteristics:-
1) I tisini t
ializedt ozer owhent hef i
rstobjectofitsclassi screated.No
otheri ni
tializationisper mi t
ted.
2) Onlyonecopyoft hatmemberi screatedf ort
heent i
recl
assandi s
sharedbyal ltheobj ect soft hatclass,nomat terhow manyobj ects
arecr eated.
3) I
tisv isibleonl ywi t
hi nthecl assbuti tsli
fet i
meist heentir
epr ogram.
Staticv ariablesar enor mal l
yusedt omai ntainvaluescommont othe
enti
recl ass.Forexampl east at
icdatamembercanbeusedasa
count erthatr ecordst heoccur r
enceofal ltheobjects.

i
nti
tem :
:count
;//def
ini
ti
onofst
ati
cdat
amember

Notethatthety
peandscopeofeachst at
icmembervar
iabl
emustbedef
ined
outsi
detheclassdefini
ti
on.Thisisnecessarybecausethest
ati
cdatamembersarest
ored
separat
elyr
atherthanasapar tofanobject.
Example:-
#i
nclude<iost
ream.h>
cl
assitem
{

1 P.
T.
1 O
5
stati
cintcount;//
counti
s
stati
cintnumber ;
publ
i
c:
voidgetdata(
inta)

1 P.
T.
1 O
6
. {
number=
a;
count
++;
}
v
oidgetcount(v
oid)
{
cout<<”count:
”;
cout<<count<<end
l;
}
};
i
nti
tem :
:count;//countdefined
i
ntmai n()
{
i
tem a, b,
c;
a.get_count()
;
b.get_count()
;
c.get_count()
:a.getdata():
b.getdata();

1 P.
T.
1 O
7
c.
getdata();
cout«
"afterreadingdata:

endl;a.get_
count
();
b.gel
_count();
c.
getcount ();
r
etur
n(0);
}

Theoutputwoul
d
becount:
0
count:
0
count:
0
Aft
erreadi
ngdata
count:
3
count:
3
count:
3

Thestat
icVari
ablecountisi
nit
iali
zedtoZerowhent heobject
scr eat
ed.The
countisincr
ementedwhenev erthedatai
sreadi nt
oanobj ect
.Sincet
hedat aisreadinto
object
sthreetimesthev ar
iabl
ecountisincrementedthreeti
mes.Becauset hereisonly
onecopyofcountshar edbyallthethr
eeobject,al
lthet
hreeoutputst
atementscauset he
val
ue3t obedispl
ayed.

STATI
CMEMBERFUNCTI
ONS:
-

Amemberf
uncti
onthatisdecl
aredst
ati
chasfol
lowi
ngproper
ties:-
1. Astat
icfunct
ioncanhaveaccesst
oonlyot
herstati
cmember
sdecl
ared
i
nthe

1 P.
T.
1 O
8
same
cl
ass. 2. Astati
cmemberf unct
ioncanbecalledusi
ngt
hecl
assnameas
f
oll
ows:-cl
ass-name::funct
ion-name;
Exampl
e:-

1 P.
T.
1 O
9
#i
ncl
ude<iost
ream.
h>
cl
asstest
{

1 P.
T.
1 O
0
i
ntcode;
stati
cintcount;//st
ati
cmemberv ari
abl
e
publ
i
c:
voidset(void)
{
code=++count ;
}
voidshowcode( voi
d)
{
cout<<”objectmember:“<<code<<end;
}

1 P.
T.
1 O
1
st
ati
cvoidshowcount(
void)
{cout
<<”count
=”<<count
<<endl
;}
};
i
nttest:
:
count;
int
main()
{

1 P.
T.
1 O
2
testt1,t2;
t1.setcode();
t2.setcode();
test::showcount()
; '
testt3;
t3.setcode();
test::
showcount ()
;
t1.showcode() ;
t2.showcode() ;
t3.showcode() ;
return(0);

out
put
:-count:2
count:
3
objectnumber1
objectnumber2
objectnumber3

OBJECTSASFUNCTI
ONARGUMENTS

Likeanyot herdat atype,anobjectmaybeusedasAf unctionar gument.Thiscanconei nt


wo
way s
1.Acopyoft heenti
reobjectispassedt othef uncti
on.
2.Onl ytheaddr essoftheobjectist ransf erredtothefunct i
on
Thef i
rstmet hodi scal l
edpass- by-value.Si nceacopyoft heobj ectispassedt ot he
function,anychangemadet ot heobj ecti nsidet hefuncti
ondonotef fecttheobjectusedt o
callthefunction.
Thesecondmet hodiscall
edpass- by-refer ence.Whenanaddr essoftheobj ectispassed,
thecal l
edf uncti
onwor ksdirectl
yont heact ualobjectusedi nthecall.Thismeanst hatany
changesmadet otheobjectinsi
det hef unct i
onswi llr
eflectint heactualobject.Thepass
byr eferencemet hodismor eeffi
cientsi ncei trequir
est opassonl yt headdr essoft he
objectandnott heentir
eobject.

Exampl
e:-
#i
ncl
ude<iost
ream.
h>
cl
asstime
{

1 P.
T.
1 O
3
i
nthours;
i
nt
c:mi
publ
i nut
es;

v
oidget
ti
me(
inth,
intm)
{

1 P.
T.
1 O
4
hours=h;
minutes=
} m;
voi
d
put
ti
me(voi
d)
{

1 P.
T.
1 O
5
cout
<<hour
s<<”
hour
sand:
”;

cout
<<mi
nut
es<<”
minut
es:
”<<end;
}

1 P.
T.
1 O
6
v
oidsum(t
ime,
ti
me)
;
};
v
oidt
ime: :sum ( ti
met 1,
ti
met2).
{
mi nut es=t 1.
mi nutes+
t2.mi nut es;
hour s=mi nutes%60;
mi nut es=mi nut es%60;
hour s=hour s+t
1.hour s+t2.hour s;
}

i
ntmai n()
{
ti
meT1, T2,T3;
T1.gett
ime(2,45)
;
T2.gett
ime(3,30)
;T3.sum(T1,T2);
cout<<”T1=”;
T1.putt
ime()
;
cout<<”T2=”;
T2.putt
ime()
;
cout<<”T3=”;
T3.putt
ime()
;ret
urn(0);
}

1 P.
T.
1 O
7
LECTURE-
18

FRIENDLYFUNCTI ONS:-
Weknowpr i
vatemember scannotbeaccessedf rom outsi
det heclass.Thati sanon
-memberf unct ioncan'thaveanaccesstothepr i
vatedat aofaclass.Howev ertherecould
beacasewher et woclassesmanagerandsci enti
st,hav ebeendef i
nedweshoul dliketo
useafuncti
oni ncome-t axtooper at
eontheobjectsofbot htheseclasses.
Insuchsituations,c++al lowst hecommonf unct i
onl obemadef riendlywi thbotht he
cl
asses,therebyf ol
lowingthefuncti
ontohaveaccesst ot hepri
vatedat aoft heseclasses
.Suchafunctionneednotbeamemberofanyoft hesecl asses.
Tomakeanout sidefuncti
on"fr
iendl
y"toacl
ass,wehav et osimplydecl arethisfuncti
onas
afri
endofthecl assesasshownbel ow:

cl
assABC
{
--
--
--
--
-
--
--
--
--
-
publi
c:
-
--
--
--
-
-
--
--
--
--
-
f
ri
endv oi
dxy
z(v
oid)
;
};

Thefuncti
ondeclarati
onshoul dbepr ecededbyt hekeywordfri
end, Thefunctionisdefi
ned
elsewhereintheprogram li
keanor malC++f uncti
on.Thef uncti
ondef i
nit
iondoesnotuse
thei
rthekeywordfriendort hescopeoper at
or: :.Thefuncti
onst hataredeclaredwiththe
keywordfri
endareknownasf ri
endfunctions.Af uncti
oncanbedecl ar
edasaf r
iendinany
noofclasses.Afri
endf uncti
on, ast
houghnotamemberf uncti
on, hasfullaccessri
ghtsto
thepri
vatemember soft heclass.

Af
riendfunctionprocessescer t
ainspecialcharact
eri
sti
cs:
a.Itisnoti nthescopeoft heclasst owhichithasbeendecl
aredasfri
end.
b.Si nceitisnotinthescopeoft heclass,
itcannotbecal
l
edusingtheobjectof
thatclass.I
tcanbei nvokedlikeamemberf uncti
onwit
houtthehel
pofany
object.
c.Unl ikememberf unctions.

Exampl
e:

#i
ncl
ude<iost
ream.
h>
cl
asssample
{

1 P.
T.
1 O
8
i
nta;
i
ntb;
publ
i
c:
v
oidset
val
ue(){a=25;
b=40;
}
f
ri
endfl
oatmean(samples)
;
}

1 P.
T.
1 O
9
f
loat mean(
samples)
{
r
etur
n(fl
oat
(s.
a+s.
b)/
2.0)
;
}
i
ntmain()
{

1 P.
T.
1 O
0
samplex;
x.setv
alue()
;
cout
<<”mean
val
ue=”<<mean(
x)<<endl
;ret
urn(
0);

out
put
:
meanval
ue:
32.
5

Af
unct
ionf
ri
endlytot woclasses
#i
nclude<iost
ream.h>
cl
ass
abc;
cl
ass
xyz
{

1 P.
T.
1 O
1
i
ntx;
publ
i
c:
v
oidset
val
ue(
intx){x-=I
;}
f
ri
endvoi
dmax( xyz,
abc)
;
};

1 P.
T.
1 O
2
cl
assabc
{

1 P.
T.
1 O
3
i
nta;
publ
i
c:
v
oidset
val
ue(i
nti
){a=i;
}
f
ri
endvoi
dmax(xy
z,abc);
};

1 P.
T.
1 O
4
v
oidmax(xyzm, abcn)
{
i
f(m .x>=n.a)
cout
<<m.x;

1 P.
T.
1 O
5
el
se
cout
<<n.
a;
}

1 P.
T.
1 O
6
i
ntmai n()
{
abcj;
j.
setval
ue(10) ;
xyzs;
s.setv
alue(20);
max(s, j
);
retur
n(0);
}
SWAPPI
NGPRI
VATEDATAOFCLASSES:

#i
ncl
ude<i
ost
ream.
h>

cl
assclass-
2;cl
ass
cl
ass-1
{

1 P.
T.
1 O
7
i
ntvalue1;
publ
i
c:
v
oidindata(i
nta){val
ue=a;}
v
oiddispl
ay (
voi
d){cout<<v
alue<<endl;
}
f
ri
endv oi
dexchange(class-1&,class-
2&)
;
};

1 P.
T.
1 O
8
cl
asscl
ass-
2
{

1 P.
T.
1 O
9
i
ntvalue2;
publ
i
c:
voi
dindata(i
nta){value2=a;
}
voi
ddisplay(
voi
d){cout<<val
ue2<<endl
;
}fr
iendv oi
dexchange(cl
ass-
l&, cl
ass-
2&);
}
;

1 P.
T.
1 O
0
v
oidexchange(cl ass-
1&x,class-
2&y
)
{
inttemp=x.value1;
x.v alueI
=y.
val
uo2;
y.value2=t
emp;
}

1 P.
T.
1 O
1
i
ntmai n()
{
class-1c1;
class-2c2;
c1.indata(l00)
;
c2.indata(20
0);
cout <<”val
uesbefor
eexchange:
”<<endl
;
c1.display();
c2.display();
exchange
(c1,c2);
cout <<”val
uesaft
erexchange:
”<<endl;
c1.di spl
ay() ;
outpu c2.di spl
ay
t: ();return(0);
}

v
aluesbefor
eexchange
100
200
v
aluesaft
erexchange
200
100

1 P.
T.
1 O
2
PROGRAM FORI
LLUSTRATI
NGTHEUSEOFFRI
ENDFUNCTI
ON:

#include<
i
ost ream.h>class
account 1;
cl
assaccount 2
{
private:
i
ntbalance;
publ i
c:
account 2(){balance=567;
}v oidshowacc2()
{
cout <<”
balanceinaccount
2is:
”<<bal
ance<<endl;
fr
iendinttransfer(account2&acc2,account
1&acc1,intamount
);
};
cl
assacount 1
{
pri
vate:
i
ntbal ance;

1 P.
T.
1 O
3
publ
i
c:
account
1(){bal
ance=345;
}

v
oidshowacc1()
{

1 P.
T.
1 O
4
cout<<”bal
ancei
naccount
1:”<<bal
ance<<endl
;
}
f
ri
endi
nttr
ansfer(account
2&acc2,
account1&acc1,i
ntamount
);
};

i
ntt
ransfer(account2&acc2,account1&acc1,
intamount
)
{
i
f(
amount<=accl .bval
ance)
{
acc2.bal
ance+=
amount;acc1.balance-
=amount ;
}

1 P.
T.
1 O
5
el
s
e r
etur
n(0)
;
}
i
ntmai n(
)
{
account1aa;
account2bb;

1 P.
T.
1 O
6
cout<<“balanceint heaccountsbefore
tr
ansfer
:”;aa.showacc1() ;
bb.showacc2() ;
cout<<“amtt ransferr
edf r
om account1to
account
2is:”;cout<<transf
er(bb,aa,
100)<<endl
;

1 P.
T.
1 O
7
cout<<“bal anceint
heaccount
saf
tert
he
tr
ansf er:
”;aa.showacc1();
bb.showacc
2();return(0)
;
}
out
put
:

1 P.
T.
1 O
8
bal
ancei ntheaccountsbefor
e
transferbalancei
naccount
1i s345bal ancei
n
account 2is567
andtr
ansf err
edfrom account
!toaccount
2
is100bal anceinaccount1is245
balancein account2is667

1 P.
T.
1 O
9
LECTURE-
19

RETURNI
NGOBJECTS:
#incl
ude<i
ostr
eam,h>
cl
asscomplex
{

1 P.
T.
1 O
0
f
loatx;
f
loaty;
publ
i
c:
v
oidinput
(fl
oatr
eal
,fl
oati
mag)
{

1 P.
T.
1 O
1
x=r
eal
;
y=i
mag;
}
f
ri
endcompl
exsum(complex,
compl
ex);v
oid show
(complex)
;
};
compl
exsum (complexc1, compl
exc2)
{
compl exc3;
c3.x=c1.x+c2.
x;
c3.y=c1.y+c2.
y;
returnc3;}

voi
dcomplex::show(compl exc)
{
cout
<<c.
x<<”+j“<<c.
y<<endl
;
}

1 P.
T.
1 O
2
i
ntmai n()
{
compl exa, b,c;
a.input
(3.1,5.
65)
;
b.input(
2.75,1.2)
;c=sum( a,b);
cout<<”a=” ;
a.show(a);
cout<<”b=“ ;b.show(b)
;
cout<<”c=”;
c.show(c);return(0)
;
outpu }
t:
a=3.
1+j5.65
b=2.
75+j1.2
c=5.
55+j6.85

1 P.
T.
1 O
3
POINTERTOMEMBERS;
Iti
spossi
blet
otaketheaddr
essofamemberofaclassandassi
gni
ttoapoi
nt er
.
Theaddressofamembercanbeobtai
nedbyappl
yi
ngtheoperat
or&toa“f
ull
yqual
i
fied”
cl
assmembername.

Acl
assmemberpoint
ercanbedecl
aredusi
ngt
heoper
ator:
:*wi
tht
hecl
assname.
ForExampl
e:
cl
assA
{
pri
vat
e:
intm;

1 P.
T.
1 O
4
publ
i
c:
v
oidshow()
;
};

1 P.
T.
1 O
5
Wecandef i
neapoi ntertot
hememberm as
fol
l
ows: intA::*ip=&A: :m
Theippointercr
eatedthusact sl
i
keacl assmemberi
nthati
tmustbei nv
okedwit
haclass
obj
ect.I
nt heabovestatement.ThephraseA::*means“poi
nter-to-memberofacl
ass”.
Thephrase&A: :m meansthe“Addr essofthem memberofaclass”

The f
oll
owing st
atementis not
val
id :int *ip=&m ;/ /
i
nvali
d
Thisisbecausem i snotsimplyani ntty
pedata.I
thasmeani ngonl
ywheniti
s
associ
ated wit
htheclasstowhichitbel
ongs.Thescopeoper
atormustbeappl
iedt
obot
h
thepoi
nterandthemember .

The point
eri
pcannow beusedt
oaccesst
he m i
nsi
det
hemember
f
unct
ion(
orf
riendf
uncti
on)
.

Letusassumet hat“a”i sanobj ectof“A”decl aredinamemberf unct


ion.
Wecanaccess" m"usi ngt hepoi nteripasf ol
lows.
cout<<a.*i p;
cout<<a. m;
ap=&a;
cout<<ap- >*i p;
cout<<ap- >a;
Thedef erencingoper ator->*isusedast oacceptamemberwhenweuse
point
erstobot htheobj ectandt hemember .Theder eferencingoperat
or..
*isusedwhen
theobjecti
tselfi
susedwi ththememberpoi nter.Notethat*i pisusedli
keamembername.
Wecanal sodesi gnpoi nterstomemberf uncti
onswhi ch,t
hencanbei nv
oked
usingthedeferenci
ngoper atorint hemai nasshownbel ow.
(object-name. * poi nter-t
o-member f unct i
on)
(pointer-t
o - object - > * poi nter-
to-
member
function)
The precedence of()i s higherthant hatof. * and - >*,sothepar
enthesi
sare
necessary.

1 P.
T.
1 O
6
DEREFERENCI NGOPERATOR:
#i
nclude<iost
ream.
h>classM
{

1 P.
T.
1 O
7
i
ntx;
i
nty;
publ
i
c:
v
oidset
_xy
(inta,
i
ntb)
{

1 P.
T.
1 O
8
x=a;
y=b;
}
fr
iendi
nt
sum(M);
};

i
ntsum (
M m)
{

1 P.
T.
1 O
9
i
ntM :
:*px=&M :
:x;
//poi
ntert
omemberx

1 P.
T.
1 O
0
i
ntM :
:*py-&m :
:
y;/
/poi
ntert
o
yM *pm=&m;
i
nts=m.*px+pm
-
>py;r
etur
n(s)
;

}
i
ntmai
n()
{
M m;

1 P.
T.
1 O
1
voi
d(M::*pf )
(i
nt,int)=&M::set-xy;
//poi
ntert
ofunct
ionset
-xy(
n*pf
)(10,
20)
;
//i
nvokesset -xy
cout<<”
sum=: ”<<sum( n)<<cncil
;
n*op=&n; //
poi nttoobj ectn
(op->*pf)(30,40) ;//invokesset -
xycout<<” sum=” <<sum( n)<<end
1;retur
n( 0);
}
outpu
t: sum=
30
sum=7
0

1 P.
T.
1 O
2
LECTURE-
20

CONSTRUCTOR:
Aconstructori
saspeci almemberf uncti
onwhosetaskist
oini
ti
ali
zetheobjectsof
i
tsclass.Itisspecialbecauseitsnameist hesameastheclassname.Theconstr
uct oris
i
nvokedwhenev eranobj ectofitsassociatedcl
assiscreat
ed.Iti
scalledconstructor
becauseitconstructt
hev al
uesofdatamember soft
hecl
ass.

Aconst
ruct
ori
sdecl
aredanddefinedasf
oll
ows:
/
/'
cl
asswitha
const
ructor
cl
assinteger
{

1 P.
T.
1 O
3
i
ntm, n:
publ
i
c:
i
nteger!voi
d);
//const
ruct
ordecl
ared
-
--
---
--
---
-
-
--
---
--
---
-
};

1 P.
T.
1 O
4
i
nteger:
:int
eger(
voi
d)
{
m=0;
n=0;
}

Whenaclasscontai
nsaconst
ructorl
i
ket
heonedefi
nedabov
eiti
sguar
ant
eed
t
hatanobj
ectcr
eat
edbytheclasswi
ll
beini
tial
i
zedaut
omati
cal
l
y.

Forexample:
-
Int
egerint
1;/
/ objectint1cr
eat
ed
Thisdeclar
ati
onnotonlycreatest heobj
ecti
nt1oft
ypei
ntegerbutal
so
i
nit
ial
i
zesi
tsdat
amember sm andntozer o.

Aconstructorthatacceptnopar ameteriscall
edthedefaul
t
constr
uctor
.ThedefaultconstructorforclassA i sA ::A() .Ifnosuch
const
ruct
orisdefined,t
hent hecompi l
ersuppl
iesadef aul
tconstructor.
Ther
eforeastatementsuchas: -
A a; /
/invokesthedefaul
tconstructorofthecompil
erof

t
hecompi
l
ert
ocr
eat
etheobj
ect"
a";

I
nvokesthedefaultconst
ructoroft hecompi l
ertocreatet
he
objecta.Theconst r
uct orfuncti
onshav esome
characteri
sti
cs:-
 Theyshoul dbedecl aredinthepubl i
csection.
 Theyar einvokedaut omat i
callywhent heobjectsar
ecreat
ed.
 Theydon' thavereturnt y
pes, notev envoidand
theref
oretheycannotr eturnv alues.
 Theycannotbei nher i
ted,thoughader iv
edclasscancall

1 P.
T.
1 O
5
thebaseclassconstructor.
 Likeot
herC++f uncti
on, t
heycanhavedefaul
tar
gument
s,
 Constr
uctorcan'
tbev i
rtual.
 Anobjectwit
haconst ructorcan'
tbeusedasa
memberofuni on.
Exampleofdefaul
tconstructor:

#i
ncl
ude<i
ostr
eam.h>
#i
ncl
ude<coni
o.h>

cl
assabc
{
pr
ivat
e:
charnm[
];

1 P.
T.
1 O
6
publ
i
c:
abc()
{
cout
<<”ent
ery
ourname:
”;
ci
n>>nm;
}

1 P.
T.
1 O
7
v
oiddi
spl
ay()

{
cout
<<nm;
}

}
;

i
ntmai n()
{
clrscr();
abcd;
d.display()
;
get ch();
return(0);
}
PARAMETERI ZEDCONSTRUCTOR: -
theconstruct
or st hatcant akeargumentsarecal
ledpar
amet
eri
zed
constr
uctors.Usi
ngparameteri
zedconst r
uctorwecani ni
ti
ali
zet
hevari
ousdat
ael
ements
ofdif
ferentobj
ectswit
hdif
ferentvalueswhent heyarecreat
ed.
Exampl e:-
classi nt
eger
{

1 P.
T.
1 O
8
i
ntm,n;
publ
i
c:
i
nteger
(intx,i
nty
);
--
--
--
--
--
--
--
--
-

1 P.
T.
1 O
9
}
;

1 P.
T.
1 O
0
i
nteger
::i
nteger(
intx,
int
y
)
{ m=x;
n=y
;

1 P.
T.
1 O
1
t
hear
gumentcanbepassedt
otheconst
ruct
orbycal
l
ingt
heconst
ruct
or
i
mpl
i
cit
ly.
i
ntegeri
nt1=int
eger(0,100)
;//expli
cit
cal
lint
egeri
nt1(
0,100);//i
mplici
tecall

1 P.
T.
1 O
2
CLASSWI
THCONSTRUCTOR:
-

#i
ncl
ude<iost
ream.
h>
cl
assi
nteger
{

1 P.
T.
1 O
3
i
ntm,n;
publ
i
c:
i
nteger
(i
nt,
int
);
v
oiddispl
ay(voi
d)

1 P.
T.
1 O
4
{
cout
<<”
m=:”
<<m ;
cout
<<”
n=”
<<n;
}
}
;
i
nteger:
:i
nteger
(intx,
i
nty
)//const
ruct
ordef
ined
{
m=x;
n=y;
}
i
ntmain()
{

1 P.
T.
1 O
5
i
ntegeri nt1(0, 100);//implici
t
cal
lintegeri nt2=integer
(25,75);
cout<<”\ nobjectl
“<<endl ;
int1.display();
cout <<”\ nobject
2“ <<endl;
int2.display();
outpu }
t: obj
ect
1m=0
n=100
obj
ect
2
m=25
n=25

1 P.
T.
1 O
6
Ex
ampl
e:-
#i
nclude<iostream.
h
>#include<conio.
h>
cl
assabc
{
pr
ivate:
charnm
[30]
;intage;
publ
i
c:
abc(){}/
/def ault
abc(charx[],
inty);
voi
dget()
{
cout
<<”enteryour
name:”
;cin>>nm;
cout
<<”entery ourage:
”;
ci
n>>age;
}
v
oiddi
splay()
{
cout<<nm«end
l;cout«
age;
}
}
;
abc:
:abc(
charx[
],
inty
)
{
str
cpy(
nm,
x)
;age=y
;
}
voi
dmain()
{
abc1;
abc
m=abc( "comput
er"
,20000)
;
l
.get()
;
l
.di
spalay ()
;
m.display();
getch();
}

OVERLOADEDCONSTRUCTOR:
-
#i
ncl
ude<iostream.h>
#i
ncl
ude<conio. h>
cl
asssum
{
pri
vate;
i
nta;
i
ntb;
i
ntc;
floatd;
doublee;
publi
c:
sum ()
{
cout
<<”entera;
”;
ci
n>>a;
cout
<<”enterb;
”;
ci
n>>b;
cout
<<”sum=“ <<a+b<<endl ;
}
sum( i
nta,intb) ;
sum( i
nta, floatd,doublec);
};
sum ::sum( i
ntx,inty)
{
a=x;
b=y ;
}
sum ::sum( intp,floatq,doubler
)
{
a=p;
d=q;
e=r;
}
voidmai n()
{
clr
scr();
sum 1;
sum m=sum( 20,50);
sum n=
sum( 3,
3.2,4.55);
getch();
}

out
put:
ent
era:3
ent
erb:8
sum=11
sum=70
sum=10.
7
5

COPYCONSTRUCTOR:
Acopyconstructorisusedt odecl areandiniti
ali
zeanobj ectfr
om anotherobj
ect.
Exampl e:-
thestat
ement
i
nteger12(11);
woul
ddefinetheobj ect12andatt hesamet imeinit
iali
zeittotheval
uesof11.
Anotherform ofthisstatementi s:i
nteger12=11;
Thepr
ocessofi nit
iali
zati
ont hroughacopyconst ructorisknownascopyi ni
ti
ali
zat
ion.
Exampl e:-
#incli
ide<iostr
eam. h>
classcode
{
i
ntid;
publ
i
c
code(){}//const
ruct
or
code(i
nta){id=a;
}//const
ruct
or
code(
code&x )
{
Id=x.
id;
}
voi
ddisplay
()
{
cout
<<id;
}
};
i
ntmai n()
{
code
A(100);
codeB( A);
codeC=A;
codeD;
D=A;
cout<<”\nidofA:
”;A.display()
;
cout<<”\ni
dofB:”;B.
display();
cout<<”\nidofC:
”;C.
display();
cout<<”\nidofD:
”;D.
display();
}

out
put:-
i
d of
A:100 i d
of B: 100
i
d of
C:100 i d
ofD:100

DYNAMI CCONSTRUCTOR: -
Theconst r
uctorscanal sobeusedt oallocatememor ywhil
ecreat
ing
object
s.Thi swi llenablethesystem toall
ocatetheri
ghtamountofmemor yforeachobj
ect
whent heobject sar enotofthesamesi ze,thusresul
ti
nginthesav i
ngofmemor y.
Allocat eofmemor yt oobjectsatt heti
meoft heirconstr
ucti
onisknownas
dynami cconstruct orsofobject
s.Thememor yisall
ocatedwit
ht hehelpofnewoperat
or.
Exampl e:-
#include<iostr
eam. h
>#i nclude<str
ing.
h>
classst ri
ng
{
char*name;
i
nt l
engt
h;
publ
i
c:
st
ri
ng()
{
lengt h=0;
name=newchar[ l
ength+1];/
*oneextrafor\0*
/
}
str
ing(char* s)/ /const ructor2
{
lengt h=st r
len( s) ;
name=newchar
[lengt h+1] ;
st rcpy (name, s);
}
voi
ddi spl ay (
v oid)
{
cout <<name<<endl ;
}
voi
dj oi
n( st ri
ng&a. string&b)
{
lengt h=a.l engt h+b.l ength;
del etename;
name=newchar [
length+l]
;/*dynamic
al l
ocat ion* /st rcpy (
name, a.
name);
st rcat(name, b. name) ;
}
};
i
ntmai n()
{
char*f i
r st=“ Joseph”;
str
ing
name1( first),name2( “louis”),
nai
ne3(“LaGrange”
),sl
,
s2;
sl
.j
oin(name1, name2) ;
s2.j
oin(s1, name
3);
namel .
di splay ();
name2. di splay ();
name3. di splay ();
s1.di
splay ();
s2.di
splay ();
}
output:-
Joseph
Loui s
language
Joseph
Loui s
JosephLoui sLanguage
LECTURE-
21

DESTRUCTOR:
-

Adest
ruct
or,usthenamei mpl
iesisusedt odest
r oytheobj
ect
sthathavebeen
creat
edbyaconst r
uctor
.Likeaconst
ruct
or,thedestr
uct
ori samemberfunct
ionwhose
namei st
hesameast hecl
assnamebutisprecededbyati
lde.

ForExampl e:-
~i nt
eger(){}
Adestructornev ertakesanyar gumentnordoesi tr
eturnanyvalue.I
twillbei
nvoked
i
mpl i
cit
lybythecompi l
eruponexitfrom theprogram tocl
eanupst oragethatisno l
onger
accessi
ble.I
ti sagoodpr act
iceto declaredestr
uctorinapr ogr
am si nceitrel
eases
memor yspacef orfut ur
euse.
Deleteisusedt ofreememor ywhichiscreat
edbynew.
Exampl e:-
mat ri
x:: ~matrix()
{
for(i
nti
=0; i
<11;
i++)
deletep[
i]
;
deletep;
}

I
MPLEMENTEDOFDESTRUCTORS: -
#incl
ude<iostream.h>
i
nt
count=0;
cl
ass
al
pha
{
publi
c:
alpha()
{
count++;
cout<<”
\nnoofobj
ectcr
eat
ed:
”<<endl
;
}
~alpha()
{
cout<<”
\nnoofobj
ectdest
roy
ed:

<<endl;
cout
nt-
-;
}
}
;

i
ntmai
n()
{
cout<<”\n\nentermain
\n:
”;alphaA1,
A2,A3,
A4;
{
cout
<<”\nenterbl
ock1:
\n”
;
al
phaA5;
}
{
cout<<”\n\ nent
erbl
ock2
\n”
;alphaA6;
}
cout
<<\nre-entermain
\n:
”;return(
0);
}

output :
-entermai n
no of obj ect
created 1 no of
objectcr eat ed2no
ofobj ectcr eat ed3
no of obj ect
created 4 ent er
block1
noofobj ectcr eated
5noofobj ect
destroy ed5ent er
block2
noofobj ectcr eated
5noofobj ect
destroy ed5r e-
enter
mai n
noofobj ect
destroy ed4noof
objectcr eated3no
ofobj ectcr eated2
noofobj ectcr eated
1

Example:-
#include<i
ost
ream.
h>i ntx=l
;
classabc
{
publ i
c:
abc()
{
x-
-;
cout
<<”
const
ructt
heno”
<<x<<endl
;
}
~abc(
)
{
cout
<<”destr
uctthe
no:”
<<x<<endl;x-
-;
}
}
;
intmain()
{
abcI1,I
2,I
3,I
4;
cout«l
l«12«13«l
4«endl
;
retur
n(0);
}
LECTURE-
22&23

OPERATOROVERLOADI NG:-
Oper
atorov
erl
oadingprov
idesaf
lexi
bleopt
ionfort
hecreat
ionofnew def
inat
ions
f
ormostoftheC++operator
s.Wecanov
erloadal
ltheC++oper
ator
sexceptt
hefol
lowing:

 Classmember saccessoper at
or(.,.
*)
 Scoper esoluti
onoper ator(:
:)
 Sizeoperator(sizeof)
 Conditi
onoper ator(?:
)
Althought hesemant i
csofanoper atorcanbeext ended,wecan'tchangei tssyntax,
thegrammat i
calr ul
esthatgover
ni tsusesuchast henoofoper andspr ecedenceand
associ
ati
v ety.Forexampl ethemultipl
i
cationoper at
orwi l
lenjoyhigherprecedencet han
theaddit
ionoper ator.
Whenanoper atorisov erl
oaded,i t
sor i
ginalmeaningisnotl ost
.For
example,theoper ator+,
whichhasbeenov erl
oadedt oaddt wov ect
ors,canstil
lbeusedt o
addtwoint egers.

DEFININGOPERATOROVERLOADI NG:
Todef i
neanaddi ti
onalt askt oanoper at
or ,wemustspeci f
ywhati t
meansi nrelat
iont otheclasst owhichtheoper atorisapplied.Thi sisdonewi t
ht hehelp
ofaspecialfunctioncall
edoper at
orfunction,whi chdescribest hetask.
Synt
ax:-
r
eturn-t
ypeclass-name: : operat
orop(ar g-l
ist)
{
funct i
onbody
}
Wherer eturntype ist he t ype ofv alue r et
ur ned byt he specif
ied
operati
onandopi stheoper atorbeingov erloaded.Theopi spr ecededbyt hekey word
operator
,operatoropi st
hef uncti
onname.
oper
atorfuncti
onsmustbeei t
hermemberf unction,orfri
end
functi
on.Abasi cdef fer
encebet weent hem i st hataf r
iendf unct i
onwi l
lhav eonlyone
argumentforunar yoperatorsandtwof orbinar yoper at
ors,Thisi sbecauset heobj ectused
toinvoket hememberf unctionispassedi mpl i
cit
lyandt hereforei sav ail
ablef orthe
memberf unctions.Argument smaybeei therbyv alueorbyr eference.

operatorfunct
ionsar edecl aredin.t hecl assusi ngpr ototypesas
foll
ows: -v ectoroper at or+( vector );/
./v ector
addi ti
on
v ectoroper at
or -
(); /
/ unarymi nus
friendv ect oroper ator+( vuelor,v ector);//
v ectoraddf ri
endv ect oroper ator- (
vect or)
;//
unar ymi nusv ectoroper ator-(v ector&a) ;//
subst r
act i
on
intoper ator==( vect or);/ /compar i
sion
friendi ntoper ator==( v
ect or,vrctor);//compar i
sion
vectorisadatat ypeofcl assandmayr epresentbot hmagni t
udeanddirect
ion
oraser i
esofpoi nt scalledel ement s.
Thepr ocessofov erl
oadi nginv ol
v est hef oll
owi ngst eps:-
1.Cr eateacl asst hatdef i
nest hedat atypet hatisusedi ntheover
loadi
ngoper
ati
on.
2.Decl
aret
heoper
atorf
unct
ionoper
atorop(
)int
hepubl
i
cpar
toft
hecl
ass
3.I
tmaybeei
theramemberf
unct
ionorf
ri
endf
unct
ion.
4.Def
inet
heoper
atorf
unct
iont
oimpl
ementt
her
equi
redoper
ati
ons.
Ov
erl
oadedoper
atorf
unct
ionscanbei
nvokedbyexpr
essi
ons
suchasopxorxop;
f
orunar
yoper
ator
s
andxopy
f
orbi
nar
y
opear
ator
s.
oper
atorop(
x);
f
orunar
yoper
atorusi
ngf
ri
end
f
unct
ionoper
atorop(
x,y
);
f
orbi
nar
yoper
atorusi
nff
ri
endf
unct
ion.

Unar
y–oper
atorov
erl
oadi
ng(
usi
ngmemberf
unct
ion)
:
cl
assabc
{
i
ntm,
n;
publ
i
c:
abc(
)
{m=
8;
n=9;
}
v
oidshow(
)
{
cout
<<m<<n;
}
oper
ator-
-()
{
-
-m;
-
-n;
}
}
;
v
oidmai
n()
{
abcx;
x.
show(
);
-
-x;
x.
show(
);
}

Unar
y–-oper
atorov
erl
oadi
ng(
usi
ngf
ri
endf
unct
ion)
:
cl
assabc
{
i
ntm,
n;
publ
i
c:
abc(
)
{m=
8;
n=9;
}
v
oidshow(
)
{
cout
<<m<<n;
}
f
ri
endoper
ator-
-(
abc&p)
;
}
;
oper
ator-
-(abc&p)
{
-
-p.
m;
-
-p.
n;
}
}
;
v
oidmai
n()
{
abcx;
x.
show(
);
oper
ator
--
(x)
;
x.
show(
);
}
Unar
yoper
ator
+foraddi
ngt
wocompl
exnumber
s(usi
ngmemberf
unct
ion)

classcompl ex
{
fl
oat
real,i
mg;
publ i
c:
compl ex()
{
real=0;
img=0;
}
compl ex(f
loatr,fl
oati)
{
real=r;
i
mg=i ;
}
voidshow( )
{
cout <<real<<”+i”
<<img;
}
compl exoper ator+(complex&p)
{
compl exw;
w.real=real+q.rea
l;
w.img=i mg+q. im
g;returnw;
}
};
voidmai n()
{
compl ex
s(3,4);
compl ex
t(4,5);
compl exm;
m=s+t ;
s.show( );
t.
show( );
m. show( );
}
Unar
yoper
ator
+foraddi
ngt
wocompl
exnumber
s(usi
ngf
ri
endf
unct
ion)
classcompl ex
{
fl
oat
real,
i
mg;
public:
compl ex()
{
real=0;
img=0;
}
compl ex(f
loatr,
fl
oati
)
{
r
eal
=r;
i
mg=i;
}
voidshow( )
{
cout<<real<<” +i
”<<i
mg;
}
fr
iendcompl exoperator+(
compl
ex&p,
compl
ex&q)
;
};
compl exoper at
or+(complex&p,
compl
ex&q)
{
compl exw;
w.real =p.
real
+q. r
ea
l;
w.img=p. i
mg+q. i
m
g;ret urnw;
}
};
voidmai n()
{
compl exs( 3,4);
compl ex
t(
4,5);compl exm;
m=oper ator +(s,
t)
;
s.show();t
.show
()
; m.show( );
}

Ov erloadi nganoper atordoesnotchangei t


sbasicmeani ng.Forexampl eassume
the+oper atorcanbeov er
loadedt osubtractt
woobj ects.Butt hecodebecomes
unr eachabl e.
classi nt eger
{
i
nt x,y;
publ i
c:
i
ntoper ator+();
}
i
nti nteger : :operator+()
{
return( x-
y);
}
Unar yoper ators,ov erloaded bymeansofa memberf unct i
on,take no expli
cit
argumentandr eturnnoexpl i
citvalues.But,t
hoseov erloadedbymeansofaf r
iend
funct i
ont akeoner eferencear gument( t
heobjectofther elevantclass)
.
Binar yoper atorsov erl
oadedt hroughamemberf unctiont akeoneexpl ici
tar
gument
and t hose whi ch ar e ov erl
oaded t hrough a fr
iend f uncti
on t ake two expli
cit
argument s.

Tabl
e7.
2
Operatort
o Ar
gument
spassedto Ar
gument
spassedt
othe
Overl
oad t
he Fri
end
MemberFunct
ion Functi
on
UnaryOperat
or No 1
Bi
nary 1 2
Oper
ator
LECTURE-
24

Ty
peConv
ersi
ons
I
nami xedexpressi
onconst
antsandv
ari
ablesareofdi
ff
erentdat
atypes.Theassi
gnment
oper
ati
onscausesautomati
cty
peconver
sionbet
weentheoperandaspercert
ainr
ules.

Thety
peofdatatotheri
ghtofanassi
gnmentoper
atori
saut
omat
ical
l
yconv
ert
edt
othe
dat
atypeofv
ari
abl
eonthelef
t.

Consi
derthef
oll
owing
exampl
e:i
ntx;
fl
oaty=20.123;
x=y;

Thisconv ertsfl
oatvari
ableyt o anintegerbef oreitsv alueassigned t
o x.Thet ype
conv er
sionisaut
omaticasfarasdatatypesinvolv
edar ebuiltinty
pes.Wecanalsouset he
assignmentoperatori
ncaseofobj ect
st ocopyv aluesofal ldatamember sofrighthand
objecttot heobj
ectonlefthand.Theobj ect
si nthiscasear eofsamedat aty
pe.Butof
objectsareofdif
fer
entdataty
peswemustappl yconv er
sionr ul
esforassi
gnment.

Ther
earet
hreetypesofsit
uati
onsthatari
sewheredat
aconv
ersi
onar
ebet
weeni
ncompat
ibl
e
ty
pes.
1. Conv ersi
onfrom bui
lti
ntypetoclasst
ype.
2. Conv ersi
onfrom cl
asstypetobuil
tint
ype.
3. Conv ersi
onfrom onecl
asstypetoanother
.

Basi
ctoCl
assTy
pe
Aconstructorwasusedt obui
ldamatr
ixobjectfrom anintt
ypearray
.Simil
arly
,weused
anotherconstr
uctortobuil
dast r
ingtypeobj ectfr
om achar *typevari
able.Inthese
examplesconstructor
sperf
ormedadefact
ot ypeconversi
onfrom t
heargument '
sty
pet o
theconstr
uctor
'sclassty
pe

Consi
dert
hef
oll
owi
ng

const
ruct
or:
str
ing:
:

st
ri
ng(
char*a)
{
l
ength=st rl
en(a)
;
name=new
char[
len+1];
str
cpy
(name,a);
}

Thisconstr
uctorbui
ldsastri
ngtypeobj
ectf
rom achar*typevar
iabl
ea.Thevari
ables
l
engthandnamear edat
amember soft
hecl
assstri
ng.Onceyoudefinethe
constr
uctori
nt hecl
assstr
ing,i
tcanbeusedforconver
sionfr
om char*t
y pet
ostri
ngtype.

Example
str
ingsi,s2;
char* namel = “ Good
Mor ni
ng”
; char
* name2 =
“ STUDENTS” ; s1 =
st
ri
ng(
namel
);
s2=name2;
Thepr
ogr
am st
atement

si
=st
ri
ng(
namel
);

f
ir
stconvert
sname1f rom char
*ty
petost
ri
ngt
ypeandt
henassi
gnst
hest
ri
ngt
ype
v
aluestotheobj
ects1.Thestat
ement

s2=name2;

per
for
mst hesamejobbyi nv
oki
ngtheconst
ruct
ori
mpl i
cit
ly.
Consi
derthef
oll
owing
exampl
eclassti
me
{
i
nthours;
i
nt
minut
es;
publi
c:
ti
me(intt
)//constr
uctor
{
hours=t/60; /
/ti
sinputt
edin
minutesminut
es=t%60;
}
};

I
nthef
oll
owi
ngconv
ersi
onst
atement
s:

ti
meTl ; //obj
ect Tl
creat
edintper
iod=160;
Tl=per i
od; //i
nttocl
asst
ype
TheobjectTli
screated.Thevari
abl
eper i
odofdat
atypei nt
egeri
sconver
tedi
ntocl
asstype
ti
mebyi nv
oki
ngt heconstruct
or.Aft
ert hi
sconver
sion,thedatamemberhoursofTlwil
l
havevalue2ari
dmi nuteswil
lhaveavalueof40denoting2hoursand40minut
es.

Not
ethatt
heconstruct
orsusedf
ort
het
ypeconv
ersi
ont
akeasi
ngl
ear
gumentwhoset
ype
i
stobeconver
ted.

I
nboththeexamples,thel
eft
-handoperandof=oper
atori
sal
waysacl assobj
ect
.Hence,
wecanalsoaccompli
shthi
sconv er
sionusi
nganov
erl
oaded=oper
ator
.
LECTURE-
25
Cl
asst
oBasi
cTy
pe
Theconst ructorf
unct i
onsdonotsupportconversi
onfrom aclasst obasi
cty
pe.C++all
ows
ustodef i
neaov erl
oadedcast i
ngoperat
orthatconver
tacl asstypedatatobasi
cty
pe.The
generalform ofanov erl
oadedcastingoper
atorfunct
ion,alsoreferr
edtoasaconv er
sion
funct
ion,is:
operatortypename()
{
//Program stat
merit.
}

Thisfuncti
onconv ertsaclasstypedatatotypename.Forexample,
theoperat
ordoubl
e()
convert
sacl assobj ectt
ot y
pedouble,i
nthef oll
owi
ngconversi
onfunct
ion:
vect
or::operatordouble()
{
doublesum =0;
for
(i
ntI=0; ioi
ze;
sum =sum +v [i
]*v [
i]; //scalar
magni t
udereturnsqrt
(sum);
}

Thecasti
ngoper at
orshouldsati
sfythefol
lowingcondit
ions.
 I tmustbeacl assmember .
 I tmustnotspecifyaretur
nt ype.
 I tmustnot hav e any ar guments. Since iti s a member f unct
ion, i
ti s
i
nv oked by t he object and t heref
ore, the v al
ues used for, Conver
sion
i
nside t he functi
on belongst otheobj ectthat invoked t
he f
uncti
on. As a
resultfuncti
on doesnotneedanar gument.

I
nthestr
ingexampl ediscussedearl
ier
,wecanconv
ertt
heobj
ectst
ri
ngt
ochar
*as
f
oll
ows: str
ing::
operatorchar
*()
{
return(str
);
}

OneCl
asst
oAnot
herCl
assTy
pe
Wehavejustseendat
aconv
ersi
ontechni
quesf
rom abasi
ctoclassty
peandaclassto
basi
cty
pe.Butsometi
meswewouldliket
oconver
toneclassdat
atypetoanot
hercl
ass
ty
pe.

Exampl e
Obj1=Obj 2; /
/Obj1andObj 2ar eobj
ectsofdif
ferentcl
asses.
Objlisanobj ectofcl assoneandObj 2isanobjectofclasstwo.Theclasstwot ypedatais
convertedt ocl assonet y
pedat aandt heconvert
edvalueisassignedtotheObj l
.Sincethe
conversiont akespl acef r
om classt wotoclassone,twoisknownast hesour ceandonei s
knownast hedest i
nat i
onclass.
Suchconv ersi
onbet weenobj ectsofdif
fer
entclassescanbecar ri
edoutbyei thera
constructororaconv ersi
onf unct
ion.Whichformt ouse,dependsuponwher ewewantt he
type-conv ersionf unctiontobel ocated,whetherinthesourceclassorint hedest i
nati
on
cl
ass.
We st udied thatt he casting oper
ator
f
unct
ionOper
atort
ypename()
Conv ert
st heclassobjectofwhichi tisamembert oty pename.Thet y
penamemaybea
buil
t-i
nt ypeorauserdef i
nedone( anotherclasst ype).Int hecaseofconv er
sionsbetween
objects,
typenamer eferstot hedest inati
oncl ass.Ther efore,whenacl assneedst obe
converted,acast i
ngoper at
orf unctioncanbeused.Theconv ersi
ontakespl aceinthe
sourcecl assandtheresulti
sgivent othedest i
nationclassobj ect
.
Letus consi dera si ngle-ar
gumentconst ructorf uncti
on which serves as an
i
nst r
uctionforconvert
ingtheargument 'stypetot heclasst ypeofwhichitisamember .The
argumentbel ongs t
o t he sour ce class and i s passed t othe desti
nati
on class f
or
conversion.Theref
oretheconv er
sionconst ructormustbepl acedinthedesti
nationcl
ass.
Tabl e7.3

Conv
ersi
on Conversiont
akespl
acei
n
Sour
ceclass Desti
nati
onclass
Basi
ctoclass Notappl
icabl
e Constr
uctor
Cl
asstoBasic Cast
ingoperator Notappli
cabl
e
Cl
assto cl
ass Cast
ingoperator Constr
uctor

Whenaconv er
sionusi
ngaconst r
uctori
sper f
ormedi nthedestinat
ionclass,wemustbe
abletoaccessthedatamember softheobjectsent(bythesourceclass)asanar gument
.
Sincedat
amember softhesour
ceclassareprivat
e,wemustusespeci alaccessf
uncti
ons
i
nt hesourceclasstof
acil
it
atei
tsdatafl
owt othedesti
nati
onclass.

Considerthefol
l
owingexampl eofaninventor
yofproductsinastor
e.Onewayofkeepi ng
recor
doft hedetai
l
soft hepr
oductsistorecordt
hei
rcodenumber ,t
otali
temsi
nthest ock
andthecostofeachi t
em.Alt
ernati
vel
ywecoul dj
ustspecif
ythei
tem codeandt
hev alueof
theit
em inthestock.Thefol
lowingprogr
am usesclassesandshowshowt oconvertdata
ofonet y
petoanother.

#include<iostream.
h>
#include<coni o.h>
cl
assst ock2;
cl
assst ock1
{
i
ntcode,
i
tem; fl
oat
price;public:
stockl (i
nta,intb, f
loatc)
{
code=a;
i
tem=b;
price=c;
}
voiddi sp()
{
cout <<”code”<<code<<” \
n”;
cout <<”It
ems” <<it
em <<”\n”
;
cout <<”Pri
ceperi tem Rs.“<<pr
ice<<”
\n”
;
}
i
ntget code()
{r
et urncode; }
i
ntget i
tem()
{r
et urnitem;}
i
ntget pri
ce()
{
ret
urnpr
ice;
}
operat
orfl
oat
()
{
ret
urn(it
em*pri
ce)
;
}
};

classstock2
{
i
ntcode;
fl
oatv al;
public:
stock2()
{
code=0; val=0;
}
stock2(intx,fl
oaty)
{
code=x; val=y;
}
voiddisp()
{
cout<<“ code”<<code<<“\
n”;
cout<<“ TotalValueRs.“<<v
al<<”
\n”
}
stock2( stocklp)
{
code=p.get code();
val=p.geti
tem()*p.getpri
ce()
;
}
};

voidmai n()
{ '
Stockl il
(101,10,125.0);
Stock212;
fl
oatt ot_val
;
tot_val=i
1;
i
2=il ;
cout<<”St ockDet ail
s-st
ockl
-t
ype”
<<”\n”;i1.di sp();
cout<<”St ockv alue”<<”
\n”
;
cout<<t ot_val<<”\n”
;
cout<<”St ockDet ail
s-st
ock2-
type”
<<“
\n”
;
i
2. disp();
getch();
}

Youshoul
dgett
hef
oll
owi
ngout
put
.
St
ockDet
ail
s-st
ock1-
t
ypecode101
I
tems10
Pr
iceperi
tem Rs.
125St
ockv
alue
1250

StockDetai
l
s-st
ock2-
ty
pecode101
TotalVal
ueRs.1250
LECTURE-
26

I
nher
it
ance:

Reaccessabili
tyisy etanotherfeat
ureofOOP' s.C++st r
ongl
ysuppor tstheconceptof
reusabil
it
y.TheC++cl assescanbeusedagai ni nseveralway s.Onceaclasshasbeen
writ
tenandt ested,itcanbeadopt edbyanot herpr ogr
ammer s.Thisi
sbasicall
ycreat
edby
defi
ningthenewcl asses,reusi
ngthepr opert
iesofexi sti
ngones.Themechani sm of
deri
vinganewcl assf r
om anol doneiscalled'INHERTTENCE' .Thi
sisoftenrefer
redtoas
IS-
A'relat
ionshipbecausev er
yobjectofthecl assbeingdefined" i
s"al
soanobj ectof
i
nheritedclass.Theol dclassiscall
ed'BASE' classandt henewonei s
call
ed'DERIEVED'class.

Def
ini
ngDer
ivedCl
asses
Aderi
vedclassi
sspecif
iedbydefi
ningi
tsrel
ati
onshi
pwit
hthebasecl
assi
naddi
ti
ont
o
i
tsowndetail
s.Thegeneral
synt
axofdefini
ngaderiv
edcl
assisasfol
l
ows:

cl
assd_
classname:
Accessspeci
fi
erbasecl
assname
{

/
/member
sofder
ivedcl
ass
}
;
Thecolonindicat
est hatthea-classnameisderivedfrom t
hebaseclassname.Theaccess
speci
fi
erorthev i
sibi
lit
ymodei sopti
onal
and, i
fpresent,maybepubli
c,pr
ivat
eorprot
ected.
Bydefaul
titispri
vate.Visibi
l
itymodedescribesthestatusofder
ivedfeat
urese.
g.

cl
assxyz / /baseclass
{
membersofxyz
};
cl
assABC:publi
cxyz/ /publ
icderi
vat
ion
{
membersofABC
};
cl
assABC:XYZ / /pr
ivatederi
vat
ion(
bydef
aul
t)
{
membersofABC
};
Int heinheri
tance,someoft hebasecl assdataelementsandmemberf uncti
onsar e
i
nher i
tedint
ot hederi
vedcl
ass.Wecanaddourowndat aandmemberf uncti
onsandt hus
extendthefunct i
onal
i
tyoft
hebaseclass.Inher
it
ance,whenusedtomodifyandext endthe
capabili
ti
esoft heexi
sti
ngcl
asses,becomesav erypowerf
ultoolf
ori
ncrement alprogr
am
development.

Si
ngl
eInher
it
ance
Whenaclassi
nheri
tsfrom asi
nglebaseclass,i
tisknownassi
ngl
einher
it
ance.Fol
l
owi
ng
pr
ogr
am showsthesinglei
nher
it
anceusingpubli
cderiv
ati
on.

#i
ncl
ude<iost
ream.
h>
#i
ncl
ude<conio.
h>
cl
assworker
{
i
ntage;
charname
[10]
;publ
ic:
voidget();
};
voidworker::get()
{
cout<<”youtnamepl ease”
ci
n>>name;
cout<<”yourageplease”
;cin>>age;
}
voidworker::show()
{
cout<<”I
nMynamei s:”
<<name<<”InMyagei s:”<<age;
}
classmanager: :publi
cworker//deri
vedclass(publi
cly
)
{
i
ntnow;
publi
c:
voi
dget();
voi
dshow()
;
};
voidmanager: :get()
{
worker::get();/ /t
hecal l
ingofbaseclass
i
nputfn.cout<<“ numberofwor ker
sundery ou”;
ci
n>>now;
ci
n>>name>>age;
} (i
ftheywer epubl
ic)
voidmanager: :show()
{
worker::show() ;//cal
li
ngofbasecl asso/pfn.
cout<<“i
nNo.ofwor ker
sundermear e:“<<now;
}
main()
{
cl
rscr();
workerW1;
manager
M1; M1.get
();
M1.show();
}
I
fyoui
nputthefoll
owingt othispr
ogram:
Yournamepl
ease
Rav
inder
Yourage
pl
ease27
numberofwor
ker
sunder
y
ou30
Thent
heout
putwi
l
lbeasf
oll
ows:
Mynamei
s:Rav
inder
Myagei
s:27
No.ofwor
ker
sundermear
e:30
Thef
oll
owi
ngpr
ogr
am showst
hesi
ngl
einher
it
ancebypr
ivat
eder
ivat
ion.
#i
ncl
ude<i
ost
ream.
h>
#i
ncl
ude<coni
o.h>
cl
asswor
ker/
/Basecl
assdecl
arat
ion
{
i
ntage;
charname[
10]
;publi
c:
voi
dget();
voi
dshow()
;
};
voi
dworker: :get()
{
cout<<“ yournamepl ease”
;cin>>name;
cout<<“ yourage
please”;cin>>age;
}
voi
dworker: show()
{
cout<<“ inmynamei s:“<<name<<“ i
n”<<“myageis:“<<age;
}
cl
assmanager: worker//Derivedclass(
pri
vatel
ybydefaul
t)
{
i
ntnow;
public:
voidget();
voidshow()
;
};
voi
dmanager: :get()
{
wor ker::get();//
calli
ngt hegetf
uncti
onofbase
cout<<“ numberofwor kerunderyou”;
class
whichi scin>>now;
}
voi
dmanager: :show()
{
wor ker::show();
cout<<“ inno.ofwor kerundermear e:“<<now;
}
main()
{
cl
rscr();
wor kerwl
;
managerml ;
ml.get();
ml.show();
}
Thef
oll
owi
ngpr
ogr
am showst
hesi
ngl
einher
it
anceusi
ngpr
otect
edder
ivat
ion
#incl
ude<coni o. h>
#incl
ude<i ostr
eam. h>
cl
asswor ker //
Basecl assdeclaration
{prot
ect ed:
i
ntage; charname
[20];publ i
c:
voidget() ;
voidshow
();
};
voidwor ker::get()
{
cout>>“ y ourname
please”; cin>>name;
cout<<“ y ourage
please”; cin>>age;
}
voidwor ker::show()
{
cout<<“ inmynamei s:“<<name<<“ i
nmyagei s“<<age;
}
cl
assmanager ::pr otectedwor ker/
/pr otectedinher
it
ance
{
i
ntnow;
publ i
c:
voidget() ;
voidshow();
};
voidmanager: :get()
{
cout<<“ pl easeent erthename
In”;cin>>name;
cout <<“pl easeent ertheageI n”;//Dir
ectl
yinput
ti
ngthe
dataci n>>age;member sofbasecl ass
cout<<“pl easeent ertheno.ofwor kersunder
you:”;cin>>now;
}
voidmanager: :show()

{
cout«"yournamei
s:"
«name«"andagei
s:"«age;
cout«"I
nno.ofwor
ker
sunderyourar
e:"
«now;
mai
n()
{
cl
rscr();
managerml ;
ml.get();
cout«"\n\
n";
ml.show()
;
}

Maki
ngaPr
ivat
eMemberI
nher
it
abl
e
Basi
cal
lywehavev
isi
bil
i
tymodest ospeci
fyt
hatinwhichmodey
ouar
eder
ivi
ngt
he
anot
hercl
assfr
om t
healreadyexi
sti
ngbasecl
ass.Theyar
e:

a. Private:when a base cl ass is privatelyinherit


ed by a der iv
ed class, ' publi
c
member s'oft he base cl ass become pr i
vate member s oft he der i
ved class
and t hereforet he publ i
c member s oft he base cl ass can be accessed by
i
ts own obj ects usi ng t he dotoper ator.The r esulti s t hat we hav e no
memberof basecl asst hatisaccessi bletotheobj ectsoftheder ivedclass.
b. Publ i
c:On t he ot herhand,when t he base cl ass is publicl
yi nher
ited, 'publi
c
member s'oft hebasecl ass become ' publi
c member s'of der ived cl ass and
thereforetheyar eaccessi bletotheobj ectsoft heder i
vedclass.
c. Protected:C++pr ovides a t hi
rdv i
sibili
ty modi f
ier,protected,whi ch ser vea
l
ittl
e pur pose i n t he i nher i
tance. A member decl ared as pr otected is
accessibleby t he member f unctions wi thi
n i ts cl ass and any cl ass
i
mmedi ately der i
vedf rom i t
.Itcannotbeaccessedbyf unctionsout si
det heset wo
classes.

Thebelowmenti
onedtabl
esummari
zeshowt
hev
isi
bil
i
tyofmember
sunder
go
modif
icat
ionswhent
heyarei
nher
it
ed

BaseClassVi
sibi
l
ity Deri
vedClassVisi
bil
i
ty
Publi
c Pr
ivat
e Pr
otect
ed
Pri
vate X X X
Publi
c Publi
c Pr
ivat
e Pr
otect
ed
Prot
ected Prot
ected Privat
e Pr
otect
ed

Thepr
ivat
eandpr
otect
edmember
sofacl
asscanbeaccessedby
:
a. Af
unct
ioni
.e.f
ri
endofacl
ass.
b. Amemberf
unct
ionofacl
asst
hati
sthef
ri
endoft
hecl
ass.
c. Amemberf
unct
ionofader
ivedcl
ass.
St
udentAct
ivi
ty
1.
Def
ineI
nher
it
ance.Whati
sthei
nher
it
ancemechani
sm i
nC++?
2.
Whatar
etheadv
ant
ageofI
nher
it
ance?
3.
Whatshoul
dbet
hest
ruct
ureofacl
asswheni
thast
obeabasef
orot
her
LECTURE-
27

Mul
ti
lev
elI
nher
it
ance
Whenthei nheri
tanceissucht hat,theclassAservesasabasecl assforaderi
vedclassB
whichi
nt ur
nser vesasabasecl assforthederivedclassC.Thistypeofinher
it
anceis
cal
led‘
MULTI LEVELINHERI TENCE’ .Thecl assBisknownast he‘INTERMEDIATEBASE
CLASS’sinceitprovi
desalinkf ortheinheri
tancebetweenAandC.ThechainABCi scall
ed

ITNHERITENCE* PATH’ f
ore.g.

A Basecl
ass

C
I
nheri
tance I
ntermedi
ate
pat
h basecl
ass
Der
ivedcl
ass

Thedecl
arat
ionfort
hesamewoul
dbe:
Cl
assA
{
//
body
}
Cl
assB: publ
icA
{
//
body
}
Cl
assC: publ
icB
{
//
body
}

Thi
sdecl
arat
ionwi
l
lfor
mthedi
ff
erentl
evel
sof

i
nher
it
ance.Fol
l
owi
ngpr
ogr
am exhi
bit
sthemul
ti
lev
el

i
nher
it
ance.

#i
ncl
ude<iost
ream. h>
#i
ncl
ude<conio.h>
cl
assworker / /Basecl
assdecl
arat
ion
{
i
ntage;
charname[ 20]
;publi
c;
voi
dget ();
v
oidshow();
}

v
oidworker
:get()
{
cout<<“yournameplease”
;
cin>>name;
cout<<“youragepl
ease”;
}
voi
dworker::show()
{
cout<<“ Inmynamei s:“<<name<<“Inmyageis:“<<age;
}
cl
assmanager: publ
icworker//
Int
ermedi
atebasecl
assder
ived
{ //publi
clyf
rom t
hebase
classintnow;
public:
voidget();
voidshow()
;
};
v
oidmanager:
:get()
{
worker:
:get(); / /
call
ingget()fn.ofbase
cl
asscout<<“ no.ofworkersunderyou:”
;
ci
n>>now;
}
v
oidmanager:
:show()
{
worker:
:show(); / /call
i
ngshow()f n.ofbase
cl
asscout<<“ I
nno.ofwor kersundermear e:
“<<
now;
}
cl
assceo:publ
i
cmanager/ /decl
arat
ionofder
ivedcl
ass
{ //
publi
clyi
nheri
tedf
rom the
i
ntnom; //i
nter
mediat
ebase
cl
asspubli
c:
voi
dget();
voi
dshow()
;
};
v
oidceo: :get()
{
manager: :
get();
cout<<“no.ofmanager
sundery
ouar
e:”
;ci
n>>nom;
}
v
oidmanager:
:show()
{
cout<<“I
ntheno.ofmanager
sundermear
e:
In”
;cout<<“
nom;
}
mai
n()
{
cl
rscr();
ceocl;
cl.
get();
cout<<“
\n\n”
;
cl.
show();
}
Worker

Pr
ivat
e:
intage;
charname[
20]
;

Pr
otect
ed:

Pr
ivat
e:
intage;
charname[
20]
;

Manager
:Wor
ker

Pr
ivat
e:
intnow;

Pr
otect
ed:

Publ
i
c:
voi
dget (
)
voi
dshow( )
worker
::
get()
worker::
get
()

Ceo:Manager

Publ
i
c:

Pr
otect
ed:

Publ
i
c:
Al
lthei
nher
it
ed
members
Mul
ti
pleI
nher
it
ances
Acl
asscaninher
ittheat
tri
but
esoft woormorecl
asses.Thi
smechanism i
sknownas

MULTI
PLEINHERITENCE’
.Mult
ipl
einher
it
anceal
l
owsustocombinet
hefeat
ures

ofseveralexi
sti
ngcl assesasastar
ri
ngpointf
ordef
ini
ngnew classes.I
tisliket
hechi
ld
i
nheri
ti
ngt hephysicalfeatur
eofonepar
entandthei
ntel
li
genceofanother.Thesynt
axof
thederi
vedclassisasf ol
lows:

Cl
assbase1 Cl
assbase2
{ {
/
/body1 /
/body2
} }

Classderiv
ed: v
isibi
li
tybasel
,vi
sibi
li
ty
base2
{
//body3
}
Wher
ethevisi
bil
i
tyr ef
erstotheaccessspecifi
ersi.
e.publ
i
c,pr
ivat
eorpr
otect
ed.Fol
l
owi
ng
pr
ogr
am showsthemul t
ipl
einher
itance.

#incl
ude<iost r
eam. h>
#incl
ude<coni o.h>
cl
assf ather //Decl
arati
onofbasecl assl
{
intage;
charf l
ame[ 20];
public:
voidget();
voidshow()
;
};
voidfather: :
get()
{
cout<<“ yourfathername
please”;ci
n>>name;
cout<<“ Entertheage”;
cin>>age;
}
voidfather: :
show()
{
cout<<“ I
nmyf at
her ’
snamei s:‘<<name<<“Inmyf ather
’sagei
s:<<age;
}
cl
assmot her //Declarat
ionofbaseclass2
{
charname[ 20]
;i
ntage;
publi
c:
voi
dget()
{
cout<<“ mot her’snamepl ease”<<“I
n”;
cin>>name;
cout<<“ mot her’sagepl ease”<<“in”
;
cin>>age;
}
v
oidshow()
{
cout<<“ I
nmymot her’snamei s:“<<name;
cout<<“ I
nmymot her’sagei s:“<<age;
}
cl
assdaught er: publ icf at
her,publicmother//der
ivedcl
assi
nher
it
ing
{ /
/ publi
cly
charname[ 20];/ /thef eaturesofbot hthebase
cl
assintst d;
publi
c:
voidget();
voidshow()
;
};
voi
ddaught er:: get()
{
father::get();
mot her: :get();
cout<<“ child'sname: “;
cin>>name;
cout<<“ child'sst andard”;
cin>>st d;
}
voi
ddaught er:: show()
{
father::show() ;
nfather: :show();
cout<<“ Inchi ld’snamei s:
“<<name; cout<<“ Inchild'
s
standar d: “<<st d;
}
main()
{
cl
rscr();
daught er
d1; d1.get
();
d1.show();
}
Di
agr
ammat
icRepr
esent
ati
onofMul
ti
pleI
nher
it
ancei
sas

f
oll
ows:
Fat
her Mot
her

Pr
ivat
e: Pr
ivat
e:
intage; intage;
charname[
20]
; charname[
20]
;

Pr
otect
ed: Pr
otect
ed:

Publ
i
c: Publ
i
c:
voi
dget(
) voi
dget(
)
voi
d voi
d
show(
) show(
)

Cl
assdaught
er:
publ
i
cFat
her
,publ
i
cMot
her
Pr
ivat
e:charname[
20]
;i
ntage;

Pr
otect
ed:

Publi
c:
//
self
v
oidget
();
voi
dshowQ;
//
from Fat
her
v
oidget
();
voi
dshow(
);
//
from Mother
v
oidget
();
voi
dshow(
);
LECTURE-
28

Hi
erar
chi
cal
Inher
it
ance
Anotherint
erest
ingappli
cati
onofi nher
it
anceistousei sasasuppor tt
oahi erar
chi
cal
desi
gnofacl assprogr
am.Manypr ogrammingproblemscanbecastint
oahier
archywhere
cert
ainfeat
uresofonelevel
aresharedbymanyot hersbel
owthatl
evelf
ore.
g.

Account
s

Sav
ingAccount
s Curr
ent
Account
s

Fi
xeddeposi
t

Shor
tter
m Longt
erm

Mi
dter
m

I
ngener
alt
hesy
ntaxi
sgi
venas

Cl
assA
{
/
/bodyA
}

Cl
assB:publ
i
cA Cl
assC:publ
i
cA
{ {
/
/bodyB /
/bodyB
} }

InC++, suchproblemscanbeeasil
yconver
tedi
ntohier
archi
es.Thebasecl
asswi
lli
ncl
ude
allt
hef eatur
est hatarecommont othesubcl
asses.Asub-cl
asscanbeconstr
uctedby
i
nherit
ingthefeaturesofbasecl
assandsoon.

//Pr ogram toshowt hehierar


chi
calinher
it
ance
#include<iostream.h>
#i nclude<conio.h>
classf ather /
/Baseclassdeclar
ati
on
{
intage;
charname
[15];
public:
voidget()
{
cout<<“f
athernameplease”;ci
n>>name;
cout
<<“
fat
her
’sagepl
ease”
;ci
n>>age;
}
v
oidshow()
{
cout<<“
Inf
ather
’snameis‘:“
<<name;
cout<<“
Inf
ather
’sagei
s:“<<age;
}
};
cl
assson: publ
icfat
her /
/der
ivedcl
ass1
{
charname[20]
;intage;
publi
c;
voidget();
voidshow()
;
};
voi
dson: :get()

{
fat
her::
get();
cout<<“your(son)nameplease”<<“i
n”;ci
n>>name;
cout<<“yourageplease”<<“l
n”;ci
n>>age;
}
voi
dson: :show()
{
father: :show();
cout<<“ Inmynamei s: “<<name;
cout<<“ Inmyagei s:“<<age;
}
cl
assdaught er: publi
cfather / /deri
vedclass2.
{
charname[ 15]
; i
ntage;
public:
voidget()
{
father::get();
cout<<“ your(daughter’
s)namepl easeIn”
cin>>name; cout<<“ y
ouragepl easeIn”
;ci
n>>age;
}
voidshow()
{
father::show();
cout<<“ i
nmyf athernamei s:
“<<name<<
“Inandhi sagei s:“<<age;
}
};
main()
{
clr
scr();
sonS1;
daughterD1;
S1.get();
D1.get();
S1.show();
D1.show();
}
Hy
bri
dInher
it
ance
Ther
ecouldbesi t
uati
onswhereweneedt oapplytwoormor etypesofi
nheri
tanceto
desi
gnaprogram.Basi
cal
lyHybri
dInheri
tancei
sthecombinat
ionofoneormoretypesof
thei
nher
it
ance.Her
eisoneimplementat
ionofhybr
idi
nher
it
ance.

/
/Pr
ogr
am toshowt hesimplehybrid
i
nheri
tance#i ncl
ude<isostr eam.h>
#i
ncl
ude<coni o.h>
cl
assstudent //basecl assdeclarati
on
{
protected:
intr
_ no;
publ
ic:
voidget_ n( i
nta)
{
r_no=a;
}
voidput_n( v
oid)
{
cout<<“ Rol lNo.:“<<r_no;
cout<<“ In”;
}
};
cl
asstest:publicst udent
{ //Intermediatebase
cl
assprotected: intparti
,par2;

publ
ic:
voi
dget_m( i
ntx, inty)
{parti
=x; part2=y ;
}
voi
dput_m( void){
cout<<“ mar ksobtained:“<<“I
n”
<<“ Part1=“<<par t
1<<“in”
<<“ Part2=“<<par t
2<<“In”
;
}
};
cl
asssport
s //basef orr
esult
{
prot
ect
ed:int
scor
e;publ
ic:
voi
dget_s(i
nts){
score=s}
voi
dput_s(void){
cout<<“spor tswt.:“<<score<<“\n\
n”;
}
};
cl
assr
esult:publictest,
publ
i
cspor
ts/
/Der
ived
fr
om test&sport
s
{
inttotal;
public:
voiddi spl
ay(void);
};

v
oidr
esul
t::
displ
ay(
voi
d)
{
tot
al =part1+part2+
score;put_n();.
put_
m () ;
put_
S () ;
cout<<“ Total
score:
“<<t
otal
<<“
\n”
}
mai
n()
{
clr
scr();
resul
tS1;
S1.get
_n(347);
S1.get
_m( 30,
35);
S1.get
_s(7);
S1.dci
play();
}

St
udentAct
ivi
ty
1. Whati
sthemaj oruseofmulti
levelInheri
tance?
2. Howareargumentssenttothebaseconst ruct
orsi
nmulti
ple
i
nher
it
ance?Whoser esponsi
bili
tyisit.
3. Whati
sthediff
erencebetweenhi er
archicalandhybr
idI
nheri
tance.
LECTURE-
29

Vi
rt
ualBase
Cl
asses
Wehavejustdiscussedasi tuati
onwhi chwouldrequi
ret
heuseofbothmult
ipl
eandmult
i
l
evel
inher
itance.Considerasituat
ion,whereal
lthethr
eeki
ndsofi
nher
it
ance,
namelymul
ti
-
l
evel
,mult
ipleandhierarchi
calareinvol
v ed.

Letussayt he'chi l
d'hast wodi r
ectbaseclasses‘par
ent1’and‘parent2’whichthemsel ves
hasacommonbasecl ass‘grandparent
’.Thechil
dinheri
tsthetr
aitsof‘grandparent’v
iatwo
separatepaths.Itcanal sobei nheri
tdi
rectl
yasshownbyt hebrokenline.Thegr andparent
i
ssomet i
mesr eferr
edt oas‘ INDIRECTBASECLASS’ .Now,thei nheri
tancebyt hechild
mightcausesomepr oblems.Al lt
hepubl i
candpr otect
edmember sof‘ grandparent’are
i
nheritedint
o‘ child’twice,f
irstv i
a‘parent
1’andagai nv i
a‘parent2’
.So,t hereoccur sa
dupli
cacywhi chshoul dbeav oided.

Thedupli
cati
onoft heinheri
tedmemberscanbeav
oidedbymaki
ngcommonbasecl
ass
asthevi
rtual
basecl ass:fore.g.
cl
assg_ parent
{
/
/Body
};
cl
asspar ent1:vi
rt
ual publ
icg_
par
ent
{
/
/Body
};

cl
assparent
2:publi
cvir
tualg_
parent
{
//Body
};
cl
asschil
d:publi
cparent1,
publi
cparent
2
{
//body
};

Whenacl ass i
sv i
rt
ualbasecl ass,C++t akesnecessar
ycareto seet hatonlyone
copy ofthatcl
assisinheri
ted,regar
dless of how many inher
itance paths exist
s
between vi
rt
ualbase cl
ass and deri
ved class.Note that key
wor ds ‘vi
rtual
’ and

publi
c’can beusedi
neitherorder
.

/
/Pr
ogr
am toshowt hev i
rtualbase
cl
ass#include<iostream.h>
#i
ncl
ude<coni o.h>
cl
assstudent /
/Baseclassdecl
arat
ion
{
protected:
i
ntr _no;
public:
voidget _
n( inta)
{r_no=a; }
voidput _n(void)
{cout<<“ RollNo.“<<r_
no<<“ln”
;}
};
cl
asstest:v ir
tual publ icstudent/ /Virtuall
ydeclaredcommon
{ //baseclass1
protected:
int
part1;
int
part2;
public:
voidget _m( intx, i
nty )
{part1=x; par t2=y ;
}
voidput m( void)
{
cout<<“ mar ksobt ained:“<<“ \n”;
cout<<“ part1=“<<par t1<<“ \n”;
cout<<“ part2=“ <<par t
2<<“ \n”
;
}
};
cl
asssport
s:publ i
cv irtual student//v ir
tuallydeclaredcommon
{ //basecl ass2
prot
ect
ed:
i
ntscore;
public:
voidget _s( inta)
{scor e=a;
}
voidput _ s(voi d)
{cout<<“ spor tswt .
:“<<scor e<<“ \n”;
}
};
classr esul t
:publ ictest,publicspor ts//deri
vedclass
{
private: i
nttotal
;publ i
c:
voidshow( void);
};
voidr esult: :show( void)
{total =par t1+par t2+scor e;
put _n() ;
put _m () ;
put _s(); cout<<“ \nt ot
al score=“<<total
<<“\n”;
}
mai n()
{
clrscr();
resultS1;
S1. get_n
(345)
S1. get_m( 30,35);
S1. get-S( 7);
S1.show();
}

/
/Pr
ogr
am t
oshowhy bri
dinher
it
anceusi
ngv
irt
ual
basecl
asses
#i
ncl
ude<i
ostr
eam.h>
#i
ncl
ude<coni
o.h>
Cl
assA
{
pr
otect
ed:
i
ntx;
publ
i
c:
v
oidget(
int
);
v
oidshow(voi
d)
}; ;

voidA: :get(i
nta)
{x=a; }v
oid
A: :show( v
oid)
{cout<<X; }
ClassA1: Virt
ualPubl
i
c
A
{
pr
otect
ed:
i
nty;
publ
i
c:
v
oidget(
int
);
v
oidshow(voi
d);
};
voidA1::get(
inta)
{y=a;}
voidA1::show(voi
d)
{
cout<<y;
{
classA2: Vi
rt
ualpubl
i
cA
{
protect
ed:
i
ntz;
publ
i
c:
voi
dget(inta)
{z=a;}
voi
dshow( voi
d)
{cout<<z;}
};
cl
assA12: publi
cA1, publi
cA2
{
i
ntr,t;
publi
c:
voi
dget( i
nta)
{r=a;}
voi
dshow( voi
d)
{t=x+y+z+r;
cout<<“resul
t=”<<t;
}
};
main()
{
cl
rscr();
A12r;
r.
A::get( 3);
r.
A1: :get(
4);
r.
A2: :get(
5);
r.
get(6);
r.show();
}
LECTURE-
30

Pol
ymor
phi
sm:
I
ntr
oduct
ion
Whenanobj ectiscreat
edfr
om itscl
ass,thememberv ari
ablesandmemberf uncti
onsare
al
located memor yspaces.The memor yspaces have unique addr
esses.Pointerisa
mechani sm toaccessthesememor ylocationsusi
ngtheiraddressratherthanthename
assignedtot hem.Youwi l
lstudytheimplicati
onsandappli
cati
onsoft hi
smechani sm i
n
detaili
nthischapter
.

Poi
nteri
sav ari
abl
ewhichcanhol
dtheaddressofamemor
ylocat
ionr
athert
hant
hev
alue
att
helocat
ion.Consi
dert
hefol
l
owingst
atement

i
ntnum =84;

Thisstat
ementinstr
uctsthecompi l
ertor
eser
vea2-byt
eofmemorylocat
ionandputst
he
value84int
hatl
ocation.Assumet hatt
hecompil
eral
l
ocatesmemor
ylocat
ion1001t
onum.
Diagrammati
cal
l
y ,t
heallocat
ioncanbeshownas:

num Var
iabl
ename

84 Val
ue

1001 Addr
essofmemor
ylocat
ion

Fi
gur
e9.
1

Asthememor yaddressesar
ethemsel
vesnumber
s,t
heycanbeassignedtosomeot
her
var
iabl
eForexample,ptrbet
hevari
abl
etohol
dtheaddr
essofvar
iablenum.

Thus,wecanaccessthev
alueofnum byt
hev
ari
abl
ept
r.Wecansay“
ptrpoi
ntst
onum”
asshowninthefi
gurebel
ow.

nu nu

84 1001

100 205
Fi
g9.
2
Poi
nter
stoObj
ect
s
Anobj ectofacl assbehavesidenti
cal
lyasanyothervar
iabl
e.Justaspoi
nter
scanbe
definedincaseofbaseC++v ar
iabl
essoalsopoi
nter
scanbedefinedf
oranobj
ectty
pe.To
createapointerv
ariabl
efort
hefoll
owingcl
ass
cl
assemployee{
i
ntcode;
charname[
20];
publ
i
c:
i
nli
nev
oidget
dat
a()
=
0;
inl
i
nev
oiddi
spl
ay
()
=0;
}
;
Thefol
l
owi ngcodesis
writ
tenempl oy
ee
*abc;
Thi
sdeclarat
ioncreatesapoi
nterv
ari
abl
eabct
hatcanpoi
ntt
oanyobj
ectofempl
oyeet
ype.

t
hisPoi
nter
C++usesauni quekey wor dcal l
ed" t
his"torepresentanobj ectt hati nvokesamember
functi
on.'thi
s'isapoi nterthatpoi ntstotheobjectforwhichthisf unctionwascal led.This
uniquepoi nt
eri scalledandi tpassest othememberf uncti
onaut omat ical
ly.Thepointer
thisactsasani mpl i
citar gumentt oal lt
hememberf unct
ion,
fore.g.
classABC
{
i
nta;
--
---
--
---
}
;
Thepr i
vatevariable‘a’ canbeuseddi rectl
yinsi
deamemberf unction, l
i
ke
a=123;
Wecanal souset hef ollowingst atementtodot hesamej ob.
this→ a=123
e.g.
classstud
{
i
nta;
public:
voidset( inta)
{
this→ a=a; //herethispointisusedtoassignacl assl evel
} ‘
a’ witht heargument

a’ voidshow()
{
cout<<a;
}
};
mai n()
{
studS1, S2;
S1.
bet(
5);
S2.
show()
;
}
o/
p=5

Poi
nter
stoDer
ivedCl
asses
Polymorphi
sm isalsoaccompli
shedusi
ngpoint
ersinC++.Itallowsapoi nt
eri
nabase
classtopointt
oeit
herabaseclassobj
ectort
oanyderivedclassobject
.Wecanhav et
he
foll
owingProgr
am segmentshowhowwecanassi gnapoint
ertopointtotheobj
ectoft
he
deriv
edclass.

cl
assbase
{
/
/DataMembers
/
/MemberFuncti
ons
};
cl
assderi
ved:
publi
cbase
{
/
/DataMembers
/
/Memberfunct
ions
};

v
oidmai
n(){
base*pt
r;//poi
ntertoclass
basederi
vedobj ;
ptr=&obj; / /indir
ectref
erenceobj
tot
hepoi
nter
//
OtherProgram stat
ements

}
Thepoi
nterpt
rpoi
ntst
oanobjectoft
hederiv
edclassobj.But,apoint
ert
oader
ived
cl
assobj
ectmaynotpointt
oabaseclassobj
ectwithoutexpl
i
citcasti
ng.

Forexample,t hefoll
owi ngassignmentstatementsarenot
v al
i
dv oi dmain()
{
baseobj a;
derived*ptr;
ptr=&obj a;//i
nvali
d..
...
expl
ici
tcasti
ngrequi
red
//OtherProgram statements
}
Aderivedclasspoi ntercannotpointtobaseclassobject
s.But,
iti
spossi
blebyusi
ngexpl
i
cit
casting.v oi
dmai n()
{
baseobj ;
derived*ptr; //poi
nterofthederi
ved
classptr= ( deri
ved* )&obj;/ /cor
rect
refer
ence
//OtherProgram statements
}

St
udentActi
vi
ty
1. Def
inePoint
ers.
2. Whatarethevar
iousoperat
orsofpoi
nter
?Descr
ibet
hei
rusage.
3. Howwilly
oudeclareapoint
erinC++?
LECTURE-
31

Vi
rt
ualFunct
ions
Vir
tualfunct
ions,oneofadvancedfeaturesofOOPi sonethatdoesnotreal
l
yexistbutit
«
appearsrealinsomepartsofapr ogr
am.Thi ssect
iondeal
swi t
hthepoly
mor phi
cfeatur
es
whichareincorporat
edusi
ngthevirt
ualfuncti
ons.

Thegener al syntaxoft hev ir


tualfuncti
ondeclaration
i
s: classuse_ detined_ name{
pri
v ate:
publ i
c:
vir
tual return_ t
ype funct
ion_name1
(argument s); vi
rtual retur
n_ t
ype
funct i
on_name2( argument s); vir
tual
return_typef unct ion_name3(ar gument s);
--
--
----
---
---
--
--
};
Tomakeamemberf unctionv ir
tual
,thekey wordv i
rtuali
susedi nthemet hodswhil
eitis
declar
edi nt hecl assdef initi
onbutnoti nthememberf unct
iondefini
ti
on.Thekey word
vir
tualprecedest her eturnty peofthef uncti
onname.Thecompi l
ergetsinfor
mati
onf r
om
thekeywor dv i
rt
ual thati tisav ir
tualf
unctionandnotaconv ent
ionalf
uncti
ondeclar
ati
on.

For.exampl e,thef oll


owi ngdecl
arari
onofthevi
rt
ualfuncti
onis
val
id.cl asspoi nt{
i
ntx;
i
nty;
public:
vi
rtual i
ntl ength() ;
vi
rtual voiddisplay
();
};
Remembert hatthekey wordvir
tualshoul
dnotberepeatedinthedefi
nit
ionift
hedefini
ti
on
occursout sidet heclassdecl ar
ation.Theuseofafuncti
onspecif
iervi
rtuali
nthefuncti
on
defi
niti
onisi nv al
id.

Forexample
classpoint
{intx;
inty;
public:
virt
ualvoiddisplay() ;
};
virt
ualvoidpoint::display()//
err
or
{
Funct i
onBody
}
Avir
tualfuncti
oncannotbeast at
icmembersinceavi
rt
ualmemberi
salway
sa
memberofapar ti
cularobjectinaclassrat
herthanamemberoft
hecl
assasa
whole.
classpoint
{intx;
inty;
public:
v
irt
ual
stat
ici
ntl
engt
h()
;//
err
or
}
;
intpoi nt ::lengt h()
{
Funct i
onbody
}
Av irt
ual functioncannothav eaconst r
uctormemberf uncti
onbutitcanhav et hedestruct
or
memberf unct i
on.
classpoi nt
{intx;
inty;
publ i
c:
virt
ual poi nt(intxx, intyy );//const r
uct ors,
errorvoi ddi spl ay();
intlengt h();
};
Adest r
uct ormemberf unct iondoesnott akeanyar gumentandnor eturnt y
pecanbe
specifiedf oritnotev env oid.
classpoi nt
{intx;
inty;
publ i
c:
virt
ual poi nt(intxx, intyy );//i
nvali
d
voiddispl ay();
intlengt h();
Itisaner r
ortor edef ineav i
rtual methodwi t hachangeofr et
urndatat y
pei nt hederi
v ed
classwi t
ht hesamepar amet ert y
pesast hoseofav i
rt
uallmethodinthebasecl ass.
classbase
{intx,y;
publ i
c:
virt
ual i
ntsum ( i
ntxx, i
nty y); //
error
};
classder ived: publ icbase
{intz;
publ i
c:
virt
ual floatsum ( intxx, i
nty y);
};
Theabov edecl ar ati
onsoft wov ir
tualfunctionsar einvali
d.Eventhought hese
functionst akei dent ical ar gument snotet hatther eturndatatypesaredifferent.
virt
uali ntsum ( intxx, intIT); /
/base
classv irtual floatsum ( intxx,intIT);
//derivedcl ass
Bot htheabov ef unct ionscanbewr it
tenwi thintdat atypesinthebasecl assaswel lasinthe
derivedcl assas
virt
ual i
ntsum ( i
ntxx, i
nty y);//basecl ass
virt
ual i
ntsum ( i
ntxx, i
nty y);//derived
class
Onl yamemberf unct ionofacl asscanbedecl aredasv ir
tual
.Anonmemberf uncti
on
(nonmet hod)ofacl asscannotbedecl aredv i
rtual
.
virt
ual voi ddi splay()/ /
er r
or,nonmemberf unction
{
Funct i
onbody
}
St
udentAct
ivi
ty
1 Whatarevi
rt
ualf
uncti
ons
. Whatarepur
evir
tual
2 f
uncti
onsDefi
neVirt
ual

Lat
eBi
ndi
ng
As we st udi
ed inthe earli
erunit
,late bi
nding means sel
ect i
ng funct
ions dur
ing t
he
executi
on.Thoughl atebindi
ngrequir
essomeov erheaditprovidesincr
easedpowerand
fl
exibi
li
ty.Thelatebindi
ngisimplementedthroughvir
tualf
unctionsasar esul
twehav eto
declar
eanobj ectofaclasseit
herasapointertoaclassorareferencetoaclass.

Forexampl et hef oll


owi ngshowshowal at
ebi ndi
ngorr
unt
imebi
ndi
ngcanbecar
ri
edout
wit
hthehel pofav i
rtualfuncti
on.
classbase
{pr iv
at e:
intx;
floaty ;
publ i
c:
virtual voiddi splay()
;intsum ();
};
classder ivedD: publi
cbaseA
{
pr i
vat e:
intx;
floaty ;
publ i
c:
voi ddi splay() ;
//v i
rtual i
ntsum ();
};
voi dmai n()
{
baseA* ptr;
derivedDobj d;
ptr=&obj d;
OtherPr ogram statements
ptr->di splay(); //
runti
mebi nding
ptr->sum (); //compileti
mebi nding
}

Notethatthekeywordvir
tualisbefol
lowedbyt hereturntypeofamemberf uncti
oni far
un
ti
mei stobebound.Ot herwise,t
hecompi leti
mebi ndingwi llbeeff
ect
edasusual .Int
he
aboveprogram segment,onlythedisplay()functionhasbeendecl ar
edasv ir
tualint
he
baseclass,whereasthesum ()isnonv ir
tual
.Event hought hemessageisgivenfrom t
he
point
erofthebaseclasstotheobject
soft hederi
vedcl ass,i
twi l
lnot

accesst
hesum ()funct
ionoft
hederi
vedclassasi
thasbeendecl
aredasnonv
irt
ual
.The
sum ()f
unct
ioncompil
esonl
ythest
ati
cbinding.

Thef ol
l
owingprogr
am demonstr
atestheruntimebi ndi
ngofthememberf uncti
onsofa
cl
ass.Thesamemessagei sgi
ventoaccessthederi
v edclassmemberfunct
ionsfr
om the
ar
rayofpoi
nter
s.Asfunct
ionaredecl
aredasvir
tual
,theC++compileri
nvokesthedynamic
bi
nding.
#incl
ude
<i
ostream. h>
#incl
ude<coni o.h>
cl
assbaseA{
publi
c:
vi
rtualvoiddi splay( )
{cout<<“ One\ n” ;
}
};
cl
assder ivedB: publ icbaseA
{
public:
vir
tual void
display (
){cout <<
“Two\ n”; }
};
cl
assder ivedC: publ i
cder ivedB
{
public:
vir
tual voiddi splay()
{cout <<“ Thr ee\ n”;}
};
voidmai n(){
//definet hree
objectsbaseA
obja;der ivedBobj b;
derivedCobj c;
baseA* ptr[ 3];//defi
neanarr
ayofpoi
nter
sto
baseApt r[ 0]=&obj a;
ptr[1]=&obj b;
ptr[2]=&obj c;
for(inti =0; i<=2;i++)
ptr[i
]->displ ay() ;//samemessagef
orall
objectsget che();
}
Outpu
tOne
Two
Three

Thepr ogram li
stedbelowill
ustrat
esthestati
cbindingofthememberf uncti
onsofaclass.
Inpr ogram ther
ear etwocl assesstudentandacademi c.Theclassacademicisder i
ved
fr
om cl assstudent.Thetwomemberf uncti
ongetdataanddisplayar
edefinedforboththe
classes.*objisdefi
nedforclassstudent,t
headdressofwhichisstor
edintheobjectofthe
classacademi c.Thefunct
ionsgetdata()anddisplay()ofstudentcl
assareinv
okedbyt he
pointertotheclass.

#include<i ost
ream.
h>
#include<coni o.
h>
classst udent
{private:
i
ntr oll
no;
charname
[20];public:
voidgetdat
a
();voi
d
displ
ay();
};
classacademi c: publ ic
student{pr i
vat e:
char
stream;
public:
voidget dat a() ;
voiddi splay();
};
voidst udent ::get dat a()
{
cout <<
“enter r
ol lno\ n” ;
cin>>r ollno;
cout <<“ ent ername\ n”;
cin>>name;
}
voidst udent ::di spl ay()
{
cout<<“ thest udent ’
sr ollnumberis“ <<r
oll
no<<“andnamei
s”<<name;
cout<<endl ;
}
voidacademi c: : get dat a()
{
cout <<“ ent erst ream ofast udent?
\n”; ci
n>>st ream;
}
voidacademi c: : displ ay()
{cout <<“ st udent sst r
eam
\n”; cout<<st ream<<endl ;
}
voidmai n()
{
student* pt r;
academi c
obj ;
ptr=&obj ;
ptr->get dat a()
; pt r->di spl ay
(); get che() ;
}
output
enterr oll
no
25
enter
name
raghu
thest udent ’sr oll numberi s25andnamei sraghu

Thepr ogram l
istedbelowil
lustr
atest hedynamicbindingofmemberf uncti
onsofacl ass.In
thisprogram therearetwocl assesst udentandacademi c.Theclassacademi cisderived
from student.Studentfuncti
onhast wov i
rt
ualfunctionsgetdata()anddi spl
ay().The
pointerforst
udentcl assi
sdef inedandobj ect.foracademicclassiscreated.Thepoi nt
er
i
sassi gnedtheaddr essoftheobj ectandfuncti
onofder i
vedclassarei
nvokedbypoi nterto
student.
#i
ncl
ude
<i
ost
ream.h>
#i
ncl
ude<conio.h>
cl
assstudent{
private:
i
nt roll
no;
charname
[20];public:
virtualvoidget dat a
(); vi
rtualvoid
display() ;
};
classacademi c: publ ic
student{pr i
v ate:
char
stream[ 10];
publ i
c:
voidget data{} ;
voiddi splay();
};
voidst udent ::get data()
{
cout<<“ ent er
rol
lno\ n” ;cin>>r ollno;
cout<<“ ent ername
\n”;cin>>name;
}
voidst udent :
: displ ay()
{
cout <<“thest udent ’
sr ollnumberis”<<r
oll
no<<“
andname
i
s” <<name; cout <<end1;
}
voidacademi c: :get dat a()
{
cout<<“ ent erst r
eam ofast udent?
\n”;cin>>st ream;
}
voidacademi c:: display()
{
cout<<“ st udent sst ream
\n”;cout <<st r
eam <<endl ;
}
voidmai n()
{
student* pt
r;
academi cobj;
ptr=&obj ;
ptr
->get
dat a();
ptr-
>dlsplay()
;
getch() ;
}
out
pu
t
enterst
ream ofast
udent
?
Btech
student
sstream
Btech
LECTURE-
32

Pur
eVi
rt
ual
Funct
ions
General
lyafuncti
onisdeclar
edvir
tuali
nsi
deabasecl assandweredefi
nei
ttheder
ived
cl
asses.Thefunct
iondecl
aredint
hebaseclasssel
dom per
for
msanytask.

Thef oll
owingpr ogram demonst r
ateshow apur ev i
rt
ualf unct
ionisdefined,declaredand
i
nv okedfrom t heobj ectofader i
vedcl assthrought hepoi nt
erofthebasecl ass.Inthe
exampl ether earet wocl assesempl oyeeandgr ade.Thecl assemployeei sbasecl assand
thegradei sder ivedclass.Thef uncti
onsget data()anddi splay()aredeclaredforboththe
classes.Fort hecl assempl oyeet hef unct
ionsar edefinedwi thempt ybodyornocode
i
nsidet hef unct i
on.Thecodei swr i
tt
enf orthegr adeclass.Themet hodsoft heder i
ved
classareinv okedbyt hepointertothebasecl ass.

#i
ncl
ude<i
ost
ream.
h>
#i
ncl
ude<coni
o.h>
cl
assempl
oyee{
i
ntcode
charname[
20]
;
publ
i
c:
v
irt
ual
voi
dget
dat
a()
;
vir
tual
voi
ddi
spl
ay
();
};
cl
assgrade: publicempl oyee
{
chargr d[90];
fl
oatsal ary;
publ
ic:
voidget data()
;v oiddisplay
();
};
voi
dempl oy ee::getdata()
{
}
voi
dempl oy ee:
:display()
{
}
voi
dgrade: :get
dat a()
{
cout <<“ent eremployee’
sgrade
“;cin>>gr d;
cout <<“\nent erthesal
ary
“;cin>>sal ary;
}
voi
dgrade: :di
splay()
{
cout
«"Gradesal
ary\n"
;
cout
«grd«""«sal
ary
«endl
;
}
v
oidmai
n()
{
employ ee*pt r
;gradeobj ;
ptr=&obj ;
ptr-
>getdata()
; pt r
->display
();getche();
}
Out
put
enterempl oyee’
sgrade
Aent erthesalar
y
250000Gr adesal
ary
A 250000

Obj
ectSl
ici
ng:

I
nC++,ader
ivedclassobj
ectcanbeassi
gnedt
oabasecl
assobj
ect
,butt
heot
her
wayi
snotpossi
ble.

cl
assBase{i
ntx,
y;}
;

cl
assDeri
ved:publ
i
cBase{intz,
w;}
;intmai
n()
{
Deri
vedd;
Baseb=d;//Obj
ectSl
i
cing, zandwofdar
esl
i
cedof
f
}

ObjectSli
cinghappenswhenaderi
vedclassobjectisassi
gnedtoabasecl
assobj
ect
,
addit
ionalatt
ri
butesofader
ivedcl
assobjectar
esl i
cedofftof
ormthebasecl
assobj
ect
.

#incl
ude<i
ost
ream>usi
ng
namespacest
d;

cl
assBase
{
prot
ected:
inti;publi
c:
Base( i
nta) {i=a;}
virt
ual v
oiddispl
ay(
)
{cout<<" Iam Baseclassobj
ect
,i="<<i
<<endl
;}
};

cl
assDerived:publ
icBase
{
i
ntj;publi
c:
Deri
ved(i
nta,intb):Base(
a){j=b;}vi
rt
ual
voi
d
di
splay()
{cout<<"Iam Deriv
edclassobj
ect
, i
="
<<i<<",j="<<j<<endl
; }
};
/
/Globalmethod,Basecl
assobj
ecti
spassedbyv
aluev
oidsomef
unc
(
Baseobj)
{
obj
.di
spl
ay()
;
}

i
ntmai
n()
{
Baseb(33);Deri
ved
d(45,
54);somefunc(b)
;
somefunc(d); //ObjectSl
i
cing,
thememberj
ofdi
ssl
i
cedof
fret
urn0;
}

Out
put
:

Iam Basecl
assobj
ect
,i=33Iam Base
cl
assobject
,i=45

Wecanav oidaboveunexpect
edbehav iorwiththeuseofpoi nt
ersorr
efer
ences.Object
sl
icingdoesn’toccurwhenpoint
ersorr efer
encest oobject
sarepassedasfuncti
on
argument ssinceapoint
erorref
erenceofanyt ypet akessameamountofmemor y.For
example,ifwechanget hegl
obalmet hodmy func()intheaboveprogr
am t
of ol
l
owing,
objectsl
icingdoesn’
thappen.

//r
estofcodeissimi
lart
oabov
evoi
d
somefunc(Base&obj
)
{
obj.
displ
ay(
);
}
//r
estofcodeissimi
lart
oabov
e

Out
put
:

Iam Baseclassobj
ect
,i=33
Iam Deri
vedclassobj
ect
,i=45,
j=54

Wegett
hesameout
puti
fweusepoi
nter
sandchanget
hepr
ogr
am t
ofol
l
owi
ng.

//r
estofcodei ssimilart
oabovev oid
somefunc(Base* objp)
{
objp-
>displ
ay (
);
}
i
ntmain()
{
Base* bp=newBase( 33);
Deriv
ed* dp=newDer iv
ed(45,54);
somefunc(bp)
;
somef unc(
dp); /
/NoObj ectSli
cingr
etur
n
0;
}

Out
put
:

Iam Baseclassobj
ect
,i=33
Iam Deri
vedclassobj
ect
,i=45,
j=54

Obj
ectsl
icingcanbeprevent
edbymaki ngthebaseclassf
unct
ionpur
evir
tual
ther
eby
di
sal
lowi
ngobj ectcr
eati
on.I
tisnotpossi
bletocreat
etheobj
ectofacl
asswhichcont
ains
apur
ev i
rtualmethod.
LECTURE-
33

C++Funct
ionOv
err
idi
ng
Ifbaseclassandder i
vedclasshav ememberf unctionswithsamenameandar guments.I
f
youcreateanobj ectofder
ivedclassandwr i
tecodet oaccessthatmemberfuncti
onthen,
thememberf uncti
oninderi
vedclassisonlyinvoked, i
.e.
,thememberfunct
ionofderiv
ed
classoverri
desthememberf unct
ionofbasecl ass.Thisfeatur
einC++programmingis
knownasf unct
ionoverr
idi
ng.

Accessi
ngt
heOv
err
iddenFunct
ioni
nBaseCl
assFr
om Der
ivedCl
ass

Toaccesstheoverr
iddenfuncti
onofbasecl
assfrom deri
vedclass,
scoperesol
uti
on
operat
or:
:.Forexample:I
fyouwanttoaccessget
_dat
a()f
uncti
onofbaseclassfr
om
deri
vedcl
assinabov eexamplethen,
thef
oll
owingstatementisusedinder
ivedcl
ass.

A:
:
get
_dat
a;/
/Cal
l
ingget
_dat
a()ofcl
assA.

Iti
sbecause,i
fthenameofcl
assi
snotspeci
fi
ed,
thecompi
l
ert
hinksget
_dat
a()f
unct
ioni
s
cal
li
ngit
self.
Abst
ractCl
ass

Abstr
actClassisaclasswhichcontai
nsatleastonePureVir
tual f
uncti
oninit
.Abst
ract
cl
assesareusedt oprovi
deanInter
faceforitssubcl
asses.Classesinher
it
ingan
Abstr
actClassmustpr ovi
dedef
init
iontothepurevir
tualf
unction,ot
herwi
setheywil
lal
so
becomeabst r
actclass.

Char
act
eri
sti
csofAbst
ractCl
ass

1.Abstractclasscannotbeinstanti
ated,butpoint
er sandrefrencesofAbst r
actclass
typecanbecr eated.
2.Abstractclasscanhav enormalfuncti
onsandv ari
ablesalongwi t
hapur ev i
rt
ual
functi
on.
3.Abstractclassesar emai
nlyusedf orUpcasti
ng, sothati
tsder i
vedclasses
canusei tsinterf
ace.
4.Classesinheriti
nganAbstractClassmusti mplemental l
pur evir
tual
f unct
ions,or
elsetheywi l
lbecomeAbst ractt
oo.

Pur
eVi
rt
ualFunct
ions

Pur
evi
rt
ual
Funct
ionsar
ev i
rt
ualf
unct
ionswit
hnodefi
nit
ion.Theyst
artwit
hvi
rt
ual
key
wor
dandendswith=0.Herei
sthesynt
axforapur
ev i
rtual
funct
ion,

v
irt
ual
voi
df(
)=0;

Exampl
eofAbst
ractCl
ass

cl
assBase /
/Abst
ractbasecl
ass
{
publi
c:
vir
tualv
oidshow(
)=0; /
/Pur
eVi
rt
ual
Funct
ion
}
;

cl
assDeri
ved:publ
icBase
{
publi
c:
voidshow()
{cout<<"I
mpl ementat
ionofVi
rt
ual
Funct
ioni
nDer
ivedcl
ass"
;}
};

i
ntmai n(
)
{
Baseobj ; //
Compi
l
eTi
me
ErrorBase*b;
Derivedd;
b=&d;
b->show();
}

Out
put:
Impl
ement
ati
onofVi
rt
ual
Funct
ioni
nDer
ivedcl
ass

IntheaboveexampleBaseclassi
sabst
ract
,wi
thpur
evi
rt
ual
show(
)funct
ion,
hencewe
cannotcreat
eobjectofbasecl
ass.

Whycan'
twecr
eat
eObj
ectofAbst
ractCl
ass?

Whenwecr eateapurev
irt
ualfunct
ioni
nAbstractcl
ass,wereserveaslotforafunct
ioni
nthe
VTABLE(st
udiedinl
astt
opic)
,butdoesn'
tputanyaddressi
nt hatsl
ot.HencetheVTABLEwi l
l
beincompl
ete.

Ast heVTABLEforAbstr
actcl
assi
sincompl
ete,
hencethecompil
erwi
l
lnotletthe
creati
onofobj
ectforsuchcl
assandwil
ldi
spl
ayanerrr
ormessagewhenev
ery outry
todoso.
LECTURE-
34

Except
ionHandl
ing:

Excepti
onrefer
stounexpectedcondit
ioninapr ogram.Theunusualcondi
ti
onscoul
dbe
faul
ts,causi
nganer r
orwhi chinturncausest hepr ogr
am tofail
.Theer r
orhandl
ing
mechanism ofc++i
sgeneral
l
yr ef
err
edt oasexcepti
onhandli
ng.

General
ly,excepti
onsarecl assif
iedintosynchronousandasynchr
onousexcepti
ons..The
excepti
onswhichoccurdur i
ngt heprogram executi
on,duet
osomef aul
tint
heinputdataor
techni
quethatisnotsui tablet ohandlethecur rentcl
assofdata.wit
hinapr ogram is
knownassy nchronousexception.
Example:
error
ssuchasoutofr ange,overfl
ow,under
fl
owandsoon.

Theexcept
ionscausedbyeventsorfaul
t sunr
elatedtot
heprogram andbeyondthecont
rol
ofprogr
am areasynchr
onousexcept
ions.
Forexampl
e,error
ssuchaskeyboardinterr
upt
s, har
dwaremalf
uncti
ons,di
skf ai
l
ureandsoon.

except
ionhandl
ingmodel
:

Whenapr ogram encounter sanabnor malsi tuat


ionforwhi chitinnotdesi gned,theuser
mayt r
ansfercont r
oltosomeot herpartoft hepr ogr
am t hatisdesignedtodealwi t
ht he
problem.Thi sisdonebyt hrowinganexcept i
on.Theexcept i
onhandl i
ngmechani sm uses
threeblocks:try
, t
hrowandcat ch.
Thet ryblockmustbef ollowedi mmedi atel
ybyahandl er,whichisacat chbl ock.Ifan
exceptionist hr
owni nthet ryblockthepr ogram controlistransfer
redtot heappr opri
ate
exceptionhandl er
.Thepr ogr am shouldattemptt ocat chanyexcept ionthatisthrownby
anyf uncti
on.Ther el
ati
onshi poft heset hreeexcept i
onshandl i
ngconstructscalledt he
exceptionhandlingmodel isshowni nfi
gure:

t
rybl
ock

perform oper
ati
onwhichmay
throw
orinvokeet
xh
tr
o
ewb
r
nall
o
uc
fnk
cti
oni
f
needed
i
nvokef
unct
ionhav
ingt
hrowbl
ock

i
f(f
ail
ure)
t
h
cr
ao
t
cwo
hbbl
oj
e
cc
kt
ex
cept
ion

cat
chesal
lexcept
ionsthr
own
fr
om
wit
hintr
yblock
t
hrowconst
ruct
:

Thekeywordthr
owisusedtorai
seanexcept
ionwhenanerrori
sgener
atedi
nthe
comutati
on.t
hethr
owexpressi
onini
ti
ali
zeatempor
aryobj
ectofthet
ypeTusedi
nthor
w
(Targ)
.
synt
ax:
thr
owT;

cat
chconst
ruct
:

Theexcept ionhandleri
sindi
catedbythecat chkeywor
d.Itmustbeusedi mmediat
elyaf
ter
thest at
ement smarkedbyt hetrykeyword.Thecatchhandlercanalsooccurimmediat
ely
aft
eranot hercatchEachhandlerwil
lonl
yev aluat
eanexcept
ionthatmatches.
syn:
catch(T)
{
//errormeassges
}

tryconstr
uct
:
Thet r
ykeyboar
ddef i
nesaboundarywit
hinwhichanexcept
ioncanoccur.Abl ockofcode
i
nwhi chanexcept i
oncanoccurmustbepr efi
xedbythekeywordt r
y.Foll
owingt het
ry
keywordisablockofcodeenclosedbybraces.Thi
sindi
cat
esthattheprepar
edt otestf
or
theexist
enceofexcepti
ons.I
fanexcept
ionoccurs,
thepr
ogram f
lowisint
err
upted.

tr
y
{

i
f( fail
ure)
throwT;
}
catch( T)
{

}
exampl e:
#include<i ost
ream.
h>
voidmai n()
{
i
nta, b;
cout <<”entertwonumber
s:”
;
ci
n>>a>>b;
tr
y
{
i
f( b==0)
throwb;
el
s
e cout
<a/
b;

}
catch(i
ntx)
{
cout<<”2ndoper
andcan’
tbe0”
;
}
}
LECTURE-
35

Arr
ayr ef
erenceoutofbound:
#defi
nemax
5classarray
{
pri
vate:
i
nta[max]
;
publ
i
c:
i
nt&operat
or[
](
inti
)
{
i
f(i
<0||i
>=max)
t
hrowi;
el
s
e r
etur
na[
i]
;

}
}
;
voidmai n(
)
{
arrayx;
tr
y
{
cout <<”tr
yingt
oref
era[1]
…”
x[1]=3;
cout <<”tr
yingt
oref
era[13]…”
x[13]=5;
}
catch( i
nti)
{
cout <<”outofr
angeinarrayr
efer
ences…”
;
}
}

mul tipl
ecat chesinapr ogr
am
voidt est(i
ntx)
{
tr
y {
i
f( x==1)
throwx;
elsei f(x==-1)
throw3.4;
elsei f(x==0)
throw‘s’;
}
catch( inti)
{
cout <<”caughtaninteger…”
;
}
catch( floats)
{
cout <<”caughtaf l
oat…”;
}
catch(charc)
{
cout<<”caughtachar
act
er…”
;
}}
voidmai n(
)
{
test(
1);
test(
-1)
;
test(
0);
}

catchal l
voidt est(i
ntx)
{
tr
y {
i
f( x==1)
throwx;
elsei f(x==-
1)
throw3.4;
elsei f(x==0)
throw‘s’
;
}
catch( …)
{
cout <<”caughtaner
ror
…”;
}
Modul
e-03:
LECTURE-36

Cont
ainer
shi
pinC++

Whenaclasscont
ainsobject
sofanot hercl
assori
tsmember
s, t
hiski
ndof
relat
ionshipi
scal
l
edcontai
nershi
pornest i
ngandt hecl
asswhi
chcont
ainsobject
sofanot
her
classasi t
smembersiscal
l
edascont ainercl
ass.

Sy
ntaxf
ort
hedecl
arat
ionofanot
hercl
assi
s:

Cl
asscl
ass_
name1

——–

——–

}
;

Cl
asscl
ass_
name2

——–

———

}
;

Cl
asscl
ass_
name3

Cl
ass_
name1obj
1; /
/obj
ectof

cl
ass_
name1Cl
ass_
name2obj
2; /
/obj
ectof

cl
ass_
name2

———-

———–

}
;
//Sampl ePr ogram t odemonstrateContai
ner
shi
p
#include<i ostream. h>
#include<coni o. h>
#include<i omani p.h
>#i nclude<st dio.h>
consti ntlen=80;
cl
assempl oy ee
{
priv
at e:
char
name[ l
en];int
number ;
public:
voidget _dat a()
{
cout<<" \nEnt erempl oy
eename:
";ci
n>>name;
cout<<" \nEnt erempl oy
eenumber :
";ci
n>>number ;
}
voidput _dat a()
{
cout<<"\ n\ nEmpl oyeename: "<<name;
cout<<"\ n\ nEmpl oyeenumber :"<<
number ;
}
};
cl
assmanager
{
priv
at e:
chardept [
len];
i
ntnumemp;
empl oyee
emp; public:
voidget _dat a()
{
emp. get_dat a();
cout<<"\ nEnt erdepar t
ment:
";ci
n>>dept ;
cout<<" \nEnt ernumberof
empl oyees: ";cin>>numemp;
}
voidput _dat a()
{
emp. put_dat a();
cout<<"\ n\ nDepar t
ment :
"<<dept ;
cout<<"\ n\ nNumberofempl oyees:"<<numemp;
}
};
cl
asssci entist
{
priv
at e:
i
ntpubs, y ear;
empl oyee
emp; public:
voidget _
dat a()
{
emp. get _data( )
;
cout<<"\ nNumberofpubl ications:
";cin>>pubs;
cout<<"\ nYearofpubl icati
on:
";cin>>y ear;
}
voidput _
dat a()
{
emp. put _data( )
;
cout<<" \n\nNumberofpubl icati
ons:"<<pubs;
cout<<" \n\nYearofpubl i
cation:"<<year
;
}
};
voidmai n()
{
manager
m1;
scient ists1;
i
ntch;
clrscr (
);
do
{
cout<<" \n1. manager \n
2.sci entist\n";cout<<" \nEnt er
yourchoi ce:";
cin>>ch;
swi tch( ch)
{
case1:
cout<<" \ nManagerdat a:\n";
m1. get _data();
cout<<" \ nManagerdat a:\n";
m1. put _data();
break;
case2: cout<<"\ nScient i
st
data:\ n"
; s1.get
_dat a()
;
cout<<"\ nScientist
data:\ n"
; s1.put_
dat a()
;
break;
}
cout<<" \n\nTocont inuePr ess
1- >" ;cin>>ch;
}
whi le(ch==1) ;
get ch();
}
Di
ff
erencebet
weenI
nher
it
anceandCont
ainer
shi
p:

Cont
ainer
shi
p:Cont
ainer
shi
pist
hephenomenonofusi
ngoneormor
ecl
asseswi
thi
nthe
def
ini
ti
onofot
hercl
ass.Whenacl
asscont
ainst
hedef
ini
ti
onofsomeot
hercl
asses,
iti
s
r
efer
redt
oascomposi
ti
on,
cont
ainmentoraggr
egat
ion.Thedat
amemberofanewcl
ass
i
sanobj
ectofsomeot
hercl
ass.Thust
heot
hercl
assi
ssai
dtobecomposedofot
her
cl
assesandhencer
efer
redt
oascont
ainer
shi
p.Composi
ti
oni
sof
tenr
efer
redt
oasa“
has-
a”r
elat
ionshi
pbecauset
heobj
ect
soft
hecomposi
tecl
asshav
eobj
ect
soft
hecomposed
cl
assasmember
s.

I
nher
it
ance:I
nher
it
ancei
sthephenomenonofder
ivi
nganewcl
assf
rom anol
done.
I
nher
it
ancesuppor
tscoder
eusabi
l
ity
.Addi
ti
onal
feat
urescanbeaddedt
oacl
assby
der
ivi
ngacl
assf
rom i
tandt
henbyaddi
ngnewf
eat
urest
oit
.Cl
assoncewr
it
tenort
est
ed
neednotber
ewr
it
tenorr
edef
ined.
I
nher
it
ancei
sal
sor
efer
redt
oasspeci
ali
zat
ionorder
ivat
ion,
asonecl
assi
sinher
it
edor
der
ivedf
rom t
heot
her
.Iti
sal
sot
ermedas“
is-
a”r
elat
ionshi
pbecauseev
eryobj
ectoft
he
cl
assbei
ngdef
inedi
sal
soanobj
ectoft
hei
nher
it
edcl
ass.
LECTURE-
37

Template:
Template suppor
ts gener i
c programmi ng,which al
l
ows dev el
oping reusable sof
twar e
componentssuchasf uncti
ons,classes,etcsupport
ingdiff
erentdatat ypesinasi ngle
fr
amewor k.
Atemplateinc++al l
owst heconst ructi
onofafamilyoftemplatefunct
ionsandcl assest o
perf
ormt hesameoper ati
onodi fferentdataty
pes.Thet emplatesdeclar
edf orfunctions
arecall
edcl asst
empl ates.Theyper f
orm appr
opri
ateoperati
onsdependi ngont hedat a
ty
peofthepar ameterspassedt othem.

Functi
onTempl ates:
Afuncti
ont emplatespeci
fi
eshowanindi
vi
dual
funct
ioncanbe
constr
ucted.templat
e<classT>
ret
urntypefuncti
onnm( Targ1,
Tar
g2)
{
fnbody;
}

Forexampl
e:
I
nputtwonumberandswapt
hei
rval
ues

templ ate<cl assT>


voidswap( T&x,T&y)
{
T z;
z=x;
x=y;
y=z;
}
voidmai n()
{
charch1, ch2;
cout<<” entertwo
charact ers:”
;
cin>>ch1>>ch2;
swap( ch1, ch2);
cout<<ch1<<ch2;
i
nta, b;
cout<<” entera,b:
”;
cin>>a>>b;
swap( a,b);
cout<<a<<b;
fl
oatp, q;
cout<<” enterp,q:
”;
cin>>p>>q;
swap( p,q);
cout<<p<<q;
}

exampl
e2:
fi
ndmaxium bet
weentwodat
a
i
tems.t
emplate<cl
assT>
Tmax(Ta,Tb)
{
i
f( a>b)
returna;
else
returnb;
}
voidmai n()
{
charch1,ch2;
cout<<”entertwo
characters:
”;
cin>>ch1>>ch2;
cout<<max( ch1,ch2)
;
i
nta, b;
cout<<”entera,b:”
;
cin>>a>>b;
cout<<max( a,
b) ;
fl
oatp,q;
cout<<”enterp,q:”
;
cin>>p>>q;
cout<<max( p,
q) ;
}

Ov
erl
oadi
ngoff
unct
iont
empl
ate

#include<i ostream.
h>t empl ate<cl ass
T>v oidpr int(Ta)
{
cout <<a;
}
templ ate<cl assT>
voidpr i
nt(Ta, intn)
{
i
nti ;
for(i=0;i
<n; i
++)
cout <<a;
}
voidmai n( )
{
print(
1) ;
print(
3.4);
print(
455, 3);
print(
“hello”,3);
}

Mult
iplear gumentsfuncti
on
templat
e:f indsum oftwodif
fer
ent
numberst empl at
e<classT,
cl
assU>
Tsum( Ta,Ub)
{
r
etur na+(U)b;
}
voi
dmai n()
{
cout
<<sum(4,5.5)
;
cout
<sum(5.4,3);
}
LECTURE-
38

ClassTemplate
si
mi l
artofuncti
ons,cl
assescanal sobedeclaredtooperateondi
ff
erentdat
at ypes.Such
cl
assesar eclasstemplates.aclasst emplatespeci
fi
eshow indi
vidualcl
assescanbe
constr
uctedsimil
artonormalclassdefini
ti
on.Theseclassesmodelageneri
cclasswhi ch
supportsi
milaroper
ati
onsf ordi
ff
erentdat
aty pes.

syn:
templ at
e<class
T>cl ass
classnm
{
T
member 1;
T
member 2;


public:
Tf un();

.
.
};

obj
ectsf
orclasstemplatei
scr
eat
edl
i
ke:
cl
assnm <dat
atype>obj;
obj
.memberfun(
);

example:
Inputnnumber
sint
oanar
rayandpr
intt
heel
ementi
sascendi
ngor
der
.(
arr
aysor
ti
ng)

templ ate<cl ass


T>cl assar ray
{
T* a;
i
ntn;
public:
voidget dat a( )
{
i
nti ;
cout<<” ent erhowmany
no:”;cin>>n;
a=newT[ n];
for(i
=0; i<n;i++)
{
cout<<ent era
number :”;cin>>a[i
];
}
}
voidput dat a( )
{
for(i
=0;i<n;
i++)
{
cout<<a[i]
<<endl;
}
}
voidsort()
{
Tk;
i
nti,j
;
for(
i=0;
i<n-1;i
++)
{
for(j=0;
j<n;
j
++)
{
i
f(a[
i]
>a[
j]
)
{
k=a[i
];
a[i
]=a[
j]
;
a[j
]=k;
}
}
}
}
}
;
voi
dmai n()
{
arr
ay<int>x;
x.
getdata()
;
x.
sort(
);
x.
putdata()
;

ar
ray<float>y
;
y.
getdata()
:
y.
sort(
);
yput
. dat a(
);
}
LECTURE-
39

Vi
rt
ualdest
ruct
ors:

Justl i
kedecl aringmemberf uncti
onsasv irt
ual,destr
uctor
scanbedecl ar
edasv i
rt
ual,
wher easconst ruct
orscannotbev i
rt
ual.Virt
ualDest r
uctor
sarecontroll
edi nt
hesameway
asv irt
ualf unctions.Whenader i
vedobjectpoi ntedtobythebaseclasspoi nteri
sdeleted,
destruct oroft hederivedcl
assaswel lasdest ruct
orofallit
sbasecl assesareinvoked.If
destruct ori smadeasnonv ir
tualdestructori nthebasecl ass,onlyt hebasecl ass’
s
destruct ori sinvokedwhentheobjectisdeleted.
#icnlude<i ost r
eam.
h>
#include<st ri
ng.h>
classfat her
{
protected:
char
*fname;
public:
father(char* name)
{
fname=new
char(strlen( name) +1)
;
strcpy(fname, name) ;
}
virt
ual ~f ather()
{
deletef name;
cout<<” ~f atheri si
nvoked…”
;
}

vi
rtualv
oidshow()
{
cout<<”
fat
hername…”
<<f
name;
}
};

classson: publi
cf at
her
{
protected:
char
*s_name;
public:
son(char* fname,char*sname):f
ather(
fname)
{
sname=newchar [
strl
en(sname)+1];
strcpy(
s_ name,sname) ;
}
~son( )
{
deletes_name;
cout<<”~son( )i
sinvoked”<<endl
;
}
voidshow( )
{
cout<<”father’
s
name”
<<fname;cout
<<”
son’
s
name:
”<<s_name;
}
};
voi
dmai n()
{
fat
her* basep;
basep=newf ather(“mona”);
cout<<”baseppoi ntstobase
object…”basep->show( )
;
del
et ebasep;
basep=newson( “sona”,
”mona”)
;
cout<<”basepoi ntstoderi
ved
object…”;basep->show();
del
et ebasep;
}

Ov
erl
oadi
ngof>>and<<oper
ator

#def inesi ze
5cl ass
vect or
{
i
ntv [si
ze];
publ ic:
vect or();
fri
endv ect oroper ator*
(inta,vector
b);friendv ectoroper at
or* (vector
b,i
nta) ;
fri
endi stream &oper at
or>>(istr
eam &,v
ect
or
&);fr i
endost ream &oper ator<<(ost
ream
&,vect or&) ;
};
vect or:: v
ect or()
{
for(inti=0; i
<size;i++)
v[i
]=0;
}
vect or::
vect or(int* x)
{
for( i
nti =0;i<size;i
++)
v[i
]=x[ i
];
}
vect oroper ator*(inta,vectorb)
{
vect orc;
for(inti=0; i
<size;i++)
c.v[i
]=a* b.v[i]
;
returnc;
}

v
ect
oroper
ator
*(v
ect
orb,
i
nta)
{
v
ect
orc;
for(i
nti =0;i
<size;
i++)
c.v[i
]=a* b.
v[i]
;
returnc;
}
i
st r
eam &oper ator>>(i
str
eam &di
n,v
ector&b)
{
for(i
nti =0;i
<size;
i++)
din>>b. v[i
];
}
ostream &oper ator<<(
ostr
eam &dout,
vect
or&b)
{
for(i
=0; i
<size;i
++)
dout <<a[i]
;
returndout ;
}
i
ntx[ size]={2,
4,6};
i
ntmai n( )
{
vectorm;
vectorn=x;
cout <<”enterelement sofvect
or
m” ;cin>>m;
cout <<m;
vectorp, q;
p=2* m;
q=n* 2;
cout <<p;
cout <<q;

}
LECTURE-
40

Managi
ngConsol
eI/
O

I
ntr
oduct
ion
Oneoft hemostessential
featur
esofinter
act
iveprogrammingisi
tsabi
l
ityt
o
i
nteract
wit
ht he userst hrough operat
orconsole usuall
y comprisi
ng keyboar
d and monit
or.
Accor
dingl
y,everycomput erl
anguage(andcompiler
)provi
desstandard
i
nput/
outputfunctionsand/ormethodstofaci
li
tat
econsoleoperati
ons.

C++ accompli
shes input/
out
putoperati
ons using conceptofstream.A
st
ream isaser i
esofbyteswhosev al
uedependsonthevariabl
einwhichiti
sstored.Thi
s
way,C++i sabletotreatal
ltheinputandoutputoperat
ionsinauni f
orm manner.Thus,
whetheriti
sr eadi
ngf r
om afil
eorf rom t
hekeyboard,f
oraC++pr ogram i
tissimplya
st
ream.

Wehav eusedt heobjectscinandcout( pre-def


inedi
nthei
ostr
eam.
hfile)f
or
t
heinputandoutputofdataofv ari
oust ypes.Thishasbeenmadepossiblebyov
erl
oading
t
heoperator
s>>and<<t or ecognizeallthebasicC++t y
pes.The>>oper
atori
sover
loaded
i
ntheist
ream cl
assand«isov erl
oadedi nt heost
ream cl
ass.The
f
oll
owingisthegeneralformatf orreadi ngdataf r
om the

key
boar
d:ci
n >> v
ari
abl
e1 >> v
ari
abl
e2 >>… …>>

v
ari
abl
eN;

Wherev ar
iable1,vari
abl
e2,arev al
i
d C++vari
ablenamesthathavebeendeclar
ed
alr
eady.
Thisst
atementwillcausethecomputertohal
ttheexecut
ionandl
ookfori
nputdat
afr
om
thekey
board.Theinputdatafort
hisst
atementwoul
dbe:

dat
a1dat
a2.dat
aN

Theinputdataaresepar
atedbywhi
tespacesandshoul
dmat
cht
het
ypeofv
ari
abl
e
i
nthecinl
ist.Spaces,
newli
nesandtabswi
l
lbeskipped.

Theoperator>>readsthedatacharact
erbychar act
erandassignsi
ttot
heindi
cat
ed
l
ocati
on.Thereadingforavari
abl
ewi l
lbeterminatedattheencount
erofawhit
espaceora
char
actert
hatdoesnotmat chthedesti
nati
onty pe.
Forexample,consi
derthefol
l
owi ngcode:

i
ntcode;
ci
n>>code;

Supposet
hef
oll
owi
ngdat
aisgi
venas
i
nput
:1267E
Theoper at
orwillreadthecharactersupto7andt hevalue1267i
sassignedtocode.
ThecharacterEremainsi ntheinputst
ream andwillbei
nputtothenextci
nstatement
.The
gener
alformatofoutputtingdata:
cout<<iteml <<i
tem2<<<<i t
emN;
Theit
ems, i
tem1t hr
oughi temNmaybev ari
abl
esorconstant
sofanybasicty
pes.
Theput
()andget
()Funct
ions
Thecl assesi stream andost ream def inet womemberf unct i
onsget ()andput ()
respecti
v elytohandl et hesi ngl echar act eri
nput / out putoper ations.Ther ear et wotypesof
get()funct i
ons.Wecanusebot hget (char *
)andget (void)prot ot ypest of et
chachar acter
i
ncludingt hebl ankspace, tabandt henewl i
nechar acter.Theget (char *)versi
onassi gnsthe
i
nputchar actert oitsar gumentandt heget (voi d)v ersionr etur
nst hei nputchar acter.
Sincet hesef unctionsar emember soft hei nput /outputst r
eam cl asses,wemust
i
nv okethem usi nganappr opr iateobj ect .Fori nst ance, l
ookatt hecodesni ppetgi venbel
ow:
charc;
cin.get( c);//getachar act erfrom key boar dandassi gnit
tocwhi le( c!='\n')
{
cout<<C; / /di splaythechar acteronscr eenci n.get( c);
//getanot herchar act er
}
Thi scoder eadsanddi spl aysal i
neoft ext( terminat edbyanewl inecharacter)
.
Remember ,t
heoper ator >>canal sobeusedt or eadachar act
erbuti twi ll
skipt hewhite
spacesandnewl i
nechar act er.Theabov ewhi lel oopwi l
lnotwor kpr operlyifthestatement
cin>>c;
isusedi npl ace
ofci n.get( c);
Tryusi ngbot hoft hem andcompar ether esul ts.Theget (voi d)versionisused
asf ol
l
ows:
charc;
c-ci n.
get l)
;/ /cin.get( c)r eplaced
Thev aluer eturnedbyt hef unct i
onget ()i sassi gnedt othev ariablec.

Thef unct
ionput (
),amemberofost ream cl ass, canbeusedt ooutputali
neoftext
,
characterbycharacter.Forexampl e,
cout<< put( ‘
x’);
displayst hechar act erx
andcout<<put( ch);
displayst hev al
ueofv ari
abl ech.
Thev ari
ablechmustcont ainachar act ervalue.Wecanal souseanumberasan
argumentt othefunctionput( )
.Forexampl e,
cout<<put( 68);
displ
ayst hecharacterD.Thisstatementwi llconver tthei ntv al
ue90t oacharval
ueand
displ
ayt hecharacterwhoseASCI Ivalueis68,
Thef ol
lowingsegmentofapr ogram r eadsal i
neoft extfrom t
hekeyboardand
displ
aysi tonthescreen.
charc;.
cin.
get(c) / /reada
characterwhi l
e(c!=‘ \
n’)
{
cout<<put(c);//displaythechar act eronscreencin.
get(c);
}
Theget
li
ne(
)andwr
it
e()Funct
ions

Wecanr ead and di splayal i


neoft extmor eef f
icient
lyusi ng thel i
ne-ori
ent ed
i
nput /
outputfunct i
onsget l
i
ne( )andwr i
te(
).Theget l
i
ne()functionreadsawhol elineoft ext
thatendswi thanewl inechar acter.Thisfunctioncanbei nv okedbyusi ngtheobjectci nas
foll
ows:
ci
n.get li
ne(li
ne, size)
;
Thisfunctioncal linvokest hef uncti
onwhi chreadschar acterinputintothev ariable
l
ine.Thereadingi ster minatedassoonasei therthenewl i
nechar acter'\n'i
sencount eredor
sizenumberofchar actersar eread( whicheveroccur sfi
rst)
.Thenewl ine.characterisread
butnotsav ed.I
nst ead, i
tisr eplacedbyt henul lcharact
er.
Forexampl e; considert hefoll
owing
code: charname[ 20];
ci
n.get li
ne(name, 20);
Assumet hatwehav egivent hef ol
lowinginputt hroughthekey board:
Neerajgood

Thi
sinputwillber
eadcor rectl
yandassignedtothechar
acterar
rayname.Letus
supposetheinputisasfoll
ows:
Obj
ectOrientedProgrammi ng
Inthi
scase,theinputwil
lbet er
mi natedaf
terr
eadingthefol
l
owing19charact
ers:
Obj
ectOrientedPro
Af
terreadi
ngt
hest
ri
ng/ci
naut
omat
ical
l
yaddst
het
ermi
nat
ingnul
lchar
act
ert
othe
ar
r .char
ay acter

Remember
,thet
wobl
ankspacescont
ainedi
nthest
ri
ngar
eal
sot
akeni
ntoaccount
,i.
e.
betweenObjectsandOr i
entedandPr o.
Wecanal soreadstr
ingsusingtheoperat
or>>asfoll
ows:
cin>>name;
Butr
ememberci ncanr eadstri
ngsthatdonotcont
ainwhit
espace.Thi
smeans
thatci
ncanr eadjustonewordandnotaser iesofwordssuchas“Neer
ajgood”.

For
mat
tedConsol
eI/
OOper
ati
ons

C++suppor
tsanumberoff
eat
urest
hatcoul
dbeusedf
orf
ormat
ti
ngt
heout
put
.

Thesefeat
uresi
nclude:
 iosclassfuncti
onsandf l
ags.
 Mani pul
ator
s.
 User-def
inedoutputf unct
ions.
Theiosclasscont
ainsalargenumberofmemberf uncti
onsthatcouldbeusedto
for
mattheoutputinanumberofway s.Themosti mpor
tantonesamongt hem ar
elist
ed
bel
ow.

Tabl
e10.
1
Functi
on Task
width(
) Tospeci
fyt
her
equi
redf
iel
dsi
zefordi
spl
ayi
nganout
putv
alue
Pr
eci
sion( Tospeci
fyt
henumberofdi
git
stobedi
spl
ayedaf
tert
hedeci
mal
) poi
ntofafl
oatv
alue

f
il
l(
) Tospeci
fyachar
actert
hatisusedtofi
ll
theunusedporti
onofa
fi
eld.
sel
f(
) Tospeci
fyfor
matfl
agsthatcancontr
olthefor
m ofoutput
di
splay(
suchasLef
t-j
ust
if
icat
ionandri
ght-j
ust
if
icat
ion)
.
Unsel
f(
) Tocl
eart
hef
lagsspeci
fi
ed.
Manipulatorsarespecialf
uncti
onsthatcanbei ncl
udedinthesestat
ementstoalterthe
formatpar ametersofastr
eam.Thet abl
egiv
enbelowshowssomei mport
ant
!manipulat
or
funct
ionst hatarefr
equent
lyused.Toaccessthesemani
pulat
ors,t
hefil
eiomani
p.hshould
beincludedintheprogram.

Table10.2
Mani pul
ator Equiv
alentI
osf
unct
ion
set
w( ) width()
Setprecisi
on() Precisi
on()
Setfi
l
l() fi
ll
()
set
iosf l
ags() self
()
Resetiosfl
ags() Unself()

Inaddit
iontot
hesefunct
ionssuppor
tedbytheC++li
brar
y,wecancr
eat
eour
ownmani
pulatorf
unct
ionstopr
ov i
deanyspeci
alout
putf
ormats.

St
udentAct
ivi
ty
1 Whati
sast
ream?
.
Def
ineput()andget()f
unct
ions
2
Whati
sthedi
ff
erencebet
weenget
li
ne()andget()
.
f
unct
ions?Def
inewr
it
e()f
unct
ions.
3
. Whatar
emani
pul
ator
s?

St
reams
C++i sdesi gnedt owor kwi t
hawi dev ar ietyofdev icesi ncludingterminals,di sks, and
tapedr ives.Al t
hougheachdev icei sv erydi f ferent,thesy stem suppl i
esani nter f
acet ot he
progr ammert hati sindependentoft heact ualdev i
cebei ngaccessed,Thi si nt erfacei s
knownasst r
eam.
Ast ream i sasequenceofby tes.I tact sei t
herasasour cefrom whicht hei nputdat a
canbeobt ainedorasadest i
nat i
ont owhi cht heout putdat acanbesent .Thesour ce
stream t hatpr ovidesdat at ot hepr ogr am i scal l
edt heout putst ream.Inot herwor ds,a
progr am ext r
act st heby tesf rom ani nputst ream andi nser tsby tesintoanout putst ream.
Thedat ai nt hei nputst ream cancomef rom t hekey boardoranyot herst or age
dev ice.Si mi l
ar l
y,t hedat ai nt heout putst ream cangot ot hescr eenoranyot herst or age
dev ice.Asment i
onedear li
er ,ast ream act sasani nterfacebet weent heprogr am andt he
i
nput /outputdev i
ce.Ther efor e,aC++pr ogr am handl esdat a(inputorout put)independent
oft hedev i
cesused.
C++cont ainssev eral pr e-definedst r
eamst hatar eaut omat i
call
yopenedwhena
progr am begi nsi tsexecut ion.Theyi ncl udeci nandcoutwhi chhav ebeenusedv er yof teni n
ourear l
ierpr ograms.Weknow t hatci nr epr esentst hei nputst ream connect edt ot he
standar di nputdev ice (usual lyt he key boar d)and coutr epresentst he out putst r eam
connect edt ot hest andar dout putdev ice( usual lythescr een).Not et hatt
hekey boar dand
thescr een ar edef aultopt ions.Wecan r edi r
ectst reamst o otherdev i
cesorf i
les,i f
necessar y.

I
/OOper
ati
ons
I
nputandOut
putst
atement
sofcomput
erl
anguagesar
eusedt
opr
ovi
decommu-
ni
cati
onsbetweent
heuserandt
hepr
ogr
am.I
nmostoft
hecomput
erl
anguages,
inputand
out
putaredone
through st at
ement s.Buti n C++,t hese oper
ationsar e carri
ed outt hrough it
sbui lt
-i
n
functions.TheI /
Of unct
ionsar edesignedinheaderfil
esli
kef stream.h,
iostream.hetc.
Throught hesefunct i
ons,dat acanber eadf r
om orwr i
tt
ent of i
lesorst andard
i
nput /outputdev ices l
ike key board and VDU.Thi s execut i
on ofa pr ogram can be
i
nter r
uptedbyi nput/outputcall
s.Hencet hedatacanbeent eredorout putcanber etr
ieved
duringexecut i
on.
Thef i
l
e,stream classessuppor tanumberofmemberf uncti
onsf orperfor
mingt he
i
nputandout putoperationsonf il
es.Onepairoff unct
ions,pot ()andget (),aredesigned
forhandl i
ngasi nglecharacteratatime.Anotherpairoffunctions,

wr
it
e()andr
eadQ,
aredesi
gnedt
owr
it
eandr
eadbl
ocksofbi
nar
ydat
a.

put
()andget
()Funct
ions
Thef unct
ionput()writesasinglechar actertotheassociat
edst ream.Simi
larl
y,the
f
uncti
on get()r eadsa singlecharacterf rom the,associated st
ream.Thepr ogram,
r
equestsforast r
ing.Onreceivi
ngthest r
ing,thepr ogram wri
tesit
,character
,bycharacter
,
t
othef i
l
eusi ngthepot()f
unct i
oni
naf orloop.Not ethatthelengt
hoft hestri
ngisusedt o
t
erminatetheforloop.

C++pr ov i
desanumberofusef ulpredef i
nedst ream cl assesforconsole
i
nput/out putoperations.Someoft heC++t hepr edef i
nedst ream objectsar el
isted
below.
cin Thisi st he nameofst andar d i nputst ream,usual l
y key boar d.
Thecor respondi ngnamei nCi sst di
n.
cout Thi si st henameofst andardout putst ream, usuallyscreenoft hemoni tor
.
Thecor respondi ngnamei nCi sst dout.
cer r Thisist henameofst andarder r
orout putst ream, usuall
yscreenoft he
monitor.Thecor respondingnamei nCi sst derr.
clog Thi sisanot herv er
sionofcer r.Itprovidesbuf fertocol l
ecterrors.Cdoesnot
haveast ream equivalenttothis.
Int hei
rdefaultr oles,thesest r
eamsar etiedupwi ththekey boardandscr eenoft he
monitorasdescr i
beabov e.Howev er,youcanr edir
ectt hem f rom andtoot herdev icesand
fi
les.

Key
wor
ds
put():Amemberofost r
eam cl ass, coul
dbeusedtooutputal i
neoft ext,
characterbychar act er.
Get( ):
Amemberofi st
ream class, usedtoi
nputasingl
echar acterataline.
Get l
i
ne( ):Thegetl ine()functionr eadsawholeli
neof-textthatendswi thanew
l
inechar acter.Thisf unctioncouldbei nv okedbyusi
ngtheobjectcin.
Mani pulators: Specialf
unctionst hatcanbeincl
udedinconsol eI/Ostatementst
o
alt
erthef ormat -
par amet ersofast ream

St
reams:C++isdesignedtoworkwi t
hawi dev ari
etyofdevicesincl
uding,disksandtake
dri
ves.Al
thougheachdeviceisver
ydiffer
entthesystem suppli
ersani nt
erf
aceto
theprogr
ammert hati
sindependentoftheactualdeviceaccessed.Thisint
erf
ace
isknownasst r
eam.

Outputst
ream:Thesour
cest
ream t
hatpr
ovi
desdat
atot
hepr
ogr
am i
scal
l
edt
he.
out
put
st
ream.
LECTURE-
41

Namespaces:

Scopes

Namedent i
ti
es,suchasvar
iabl
es,f
unct
ions,andcompoundtypesneedtobedecl
ared
bef
orebeingusedinC++.Thepointi
ntheprogram wher
ethi
sdeclar
ati
onhappens
i
nfl
uencesitsvi
sibi
li
ty:

Anenti
tydecl
aredoutsi ockhasgl
deanybl obalscope,meaningt hati
tsnamei sv
ali
d
anywherei
nthecode.Whil
eanentit
ydeclaredwithinablock,suchasaf unct
ionora
sel
ecti
vestat
ement,hasbl
ockscope,andisonlyvisibl
ewithi
nt hespeci
ficbl
ockin
whi
chitisdecl
ared,
butnotout
sideit
.

Var
iabl
eswi
thbl eknownasl
ockscopear ocalv
ari
abl
es.

Forexample,av
ari
abl
edeclaredi
nthebodyofafuncti
onisalocalv
ariabl
ethatext
ends
unti
ltheendoft
hethefunct
ion(i
.e.
,unt
ilt
hebr
ace}thatcl
osesthefuncti
ondefi
nit
ion)
,
butnotoutsi
dei
t:

i
ntf
oo; /
/gl
obalv
ari
abl
eint

some_funct
ion(
)
{
i
ntbar; /
/localv
ari
abl
e
bar=0;
}

i
ntother
_funct
ion()
{
foo=1; /
/ok:f
ooi sagl
obalv
ar i
abl
e
bar=2; /
/wrong:bari
snotvi
siblef
rom t
hisf
unct
ion
}

I
neachscope,
anamecanonlyr
epresentoneent
it
y.Forexampl
e,t
her
ecannotbet
wo
v
ari
abl
eswiththesamenamei
nthesamescope:

i
ntsome_funct
ion(
)
{
i
ntx;x=
0;
doubl
ex; //wr
ong:nameal
readyusedi
nthi
sscope
x=0.0;
}

Thev isi
bil
i
tyofanent i
tywithblockscopeext endsuntilt
heendoft hebl
ock,i
ncludi
nginner
blocks.Nevert
heless,aninnerbl ock,becausei ti
sadiff
erentblock,
canre-
uti
l
izeaname
exist
inginanout erscopetor efertoadi ff
erententi
ty;
inthiscase,t
henamewi l
lref
ertoa
diff
erententi
tyonlywithi
nt heinnerbl ock,
hidingtheenti
tyitnamesoutsi
de.Whileout
side
i
t,itwill
sti
llr
efertotheoriginalentit
y.Forexampl e:
13 P.T.
13 O
//innerblockscopes
#include<iost
ream>

13 P.
T.
13 O
usi
ngnamespacest
d;

i
ntmai n(){intx
=10; i
nty=20;
{
intx; //ok,innerscope.
x=50; //setsv aluetoinnerxy=50;
//setsvaluet o(outer)ycout<<" inner
block:
\n";
cout<<"x: "<<x<<' \n';cout<<"y:"
<<y<<' \
n';
}
cout<<"outerblock:\n";cout<<" x:
"
<<x<<' \
n';
cout<<" y
: "<<y<<' \n'
;
ret
urn0;
}

out
put
:
i
nnerblock:
x:50
y:50
outerbl
ock:
x:10
y:50
Not ethatyisnothi
ddeni
nthei
nnerbl
ock,
andt
husaccessi
ngyst
il
laccessest
heout
er
v
ari
abl
e.

Vari
abl
esdeclaredindeclarati
onsthati
ntr
oduceabl ock,suchasfunct
ionparamet
ers
andvari
ablesdeclar
edi nl
oopsandcondit
ions(suchasthosedecl
aredonaf ororanif
)
arel
ocaltotheblocktheyi
ntroduce.

Namespaces

Onlyoneenti
tycanexi
stwithapart
icul
arnameinaparti
cul
arscope.Thi
sissel
dom a
probl
em forl
ocalnames,si
ncebl
ockstendtoberel
ati
vel
yshort,andnameshave
parti
cul
arpur
poseswithi
nthem,suchasnamingacountervar
iable,
anargument
,et
c..
.

Butnon-localnamesbringmorepossi bi
li
ti
esf ornamecoll
i
sion,especi
all
yconsider
ing
thatl
ibr
ariesmaydeclaremanyf unct
ions,types,andv
ari
ables,nei
therofthem l
ocalin
natur
e,andsomeoft hem ver
ygeneri
c.

Namespacesal
lowust ogr
oupnamedent it
iesthatot
her
wisewouldhaveglobalscope
i
ntonar
rowerscopes,gi
vi
ngthem namespacescope.Thi
sallowsorgani
zi
ngt heelement
s
ofpr
ogramsint
odiffer
entl
ogi
calscopesrefer
redtobynames.

Thesy
ntaxt
odecl
areanamespacesi
s:

namespaceident
if
ier
{
named_enti
ti
es
}

Wher
eident
if
ieri
sanyv
ali
didenti
fi
erandnamed_ent
it
iesi
sthesetofv
ari
abl
es,
typesand
f
unct
ionsthatarei
ncl
udedwithi
nthenamespace.Forexampl e:
14 P.
T.
14 O
namespacemy
Namespace
{
i
nta,b;
}

I
nthiscase, t
hev
ari
abl
esaandbar
enor
mal
var
iabl
esdecl
aredwi
thi
nanamespacecal
l
ed
myNamespace.

Thesev ari
ablescanbeaccessedf r
om wi t
hintheirnamespacenormally,
withthei
r
i
dentif
ier(eit
heraorb),buti
faccessedf r
om outsidethemyNamespacenamespacetheyhav
e
tobepr operl
yqualif
iedwit
hthescopeoper ator:.Forexampl
: e,t
oaccesst heprev
ious
var
iabl
esf rom outsi
demyNamespacetheyshouldbequalifi
edli
ke:

1my
Namespace:
:
a
2my
Namespace:
:
b

Namespacesar
epar
ti
cul
arl
yusef
ult
oav
oidnamecol
l
isi
ons.Forexampl
e:

//namespaces#incl
ude
<iost
ream>usi
ng
namespacestd;

namespacefoo
{
i
ntval
ue(){r
etur
n5;
}
}

namespacebar
{
constdoubl
epi=3.1416;
doubleval ){r
ue( et
urn2*pi
;}
}

i
ntmain( ){
cout<<foo::v
alue()<<'\
n';
cout<<
bar:
:v
alue()<<'\n'
;cout<<bar:
:
pi<<'
\n'
;
ret
urn0;
}

out
put
:

5
6.
2832
3.
1416

I
nt hi
scase,t
herear etwof uncti
onswiththesamename: v
alue.Oneisdefi
nedwit
hint
he
namespacefoo,andt heotheroneinbar.Noredef
ini
ti
onerr
or shappenthankst
o
namespaces.Not i
cealsohowpii saccessedinanunqual
if
iedmannerf rom wi
thi
n
namespacebar(justaspi)
,whi l
eiti
sagainaccessedinmai
n,buthereitneedst
obe
quali
fi
edasbar:
:
pi.

Namespacescanbespl
i
t:Twosegment
sofacodecanbedecl
aredi
nthesamenamespace:

14 P.
T.
14 O
1namespacef
oo{i
nta;
}

14 P.
T.
14 O
2namespacebar{i
ntb;
}
3namespacefoo{i
ntc;
}

Thi
sdeclar
esthr
eevar
iabl
es:aandcarei
nnamespacef oo,
whil
ebisinnamespacebar
.
Namespacescanev
enextendacrossdi
ff
erentt
ransl
ati
onunit
s(i.
e.,
acr
ossdif
ferentf
il
es
ofsour
cecode).

usi
ng

Thekeywordusi
ngi
ntr
oducesanamei nt
othecurr
entdecl
arat
iver
egi
on(
suchasabl
ock)
,thus
avoi
dingt
heneedtoquali
fythename.Forexampl
e:

//usi
ng
#incl
ude<i
ost
ream>usi
ng
namespacest
d;

namespacef
ir
st
{
i
ntx=5;
i
nty=10;
}

namespacesecond
{
doubl
ex=3. 1416;
doubl
ey=2. 7183;
}

i
ntmai n(){usingf i
rst:
:x;
usingsecond: :
y;
cout<<x<<' \n';cout<<
y<<'\n';
cout<<f i
rst
::y<<'\n';cout<<
second::
x<<' \n'
;return0;
}
Out
put
:
5
2.
7183
10
3.
1416

Not i
cehowi nmai n,t
hevari
ablex(wit
houtanynamequal i
fi
er)ref
erstof
ir
st:
:
x,whereasy
referstosecond:
:
y, j
ustasspeci
fi
edbyt heusi
ngdecl
arat
ions.Thevari
abl
esfir
stya
:
: nd
xc
second:
: anstil
lbeaccessed,butrequir
eful
lyqual
i
fiednames.

Thekey
wor
dusi
ngcanal
sobeusedasadi
rect
ivet
oint
roduceanent
ir
enamespace:
//usi
ng
#incl
ude<i
ost
ream>usi
ng
namespacest
d;

namespacef
ir
st
{
i
ntx=5;
i
nty=10;

14 P.
T.
14 O
}

namespacesecond
{
doubl
ex=3. 1416;
doubl
ey=2. 7183;
}

i
ntmai n(){
usingnamespacefi
rst
;cout
<<x<<' \
n';
cout<<y<<'\n';
cout<<second::x<<'\n';cout<<
second::
y<<'\
n'r
;et
urn0;
}

out
put
:

5
10
3.
1416
2.
7183
I
nthiscase,
bydecl
ari
ngthatwewereusi
ngnamespacefi
r ,
stal
l di
rectusesofxandy
wi
thoutnamequali
fi
erswereal
sol
ookedupinnamespacefi
r .
st

nga
usi ndusi
ngnamespacehav
eval
i
dit
yonl
yint
hesamebl
ocki
nwhi
cht
heyar
est
atedori
n
theenti
resourcecodefilei
ftheyareuseddir
ect
lyinthegl
obalscope.Forexample,
itwoul
d
bepossiblet
of i
rstusetheobjectsofonenamespaceandthenthoseofanotheroneby
spli
tt
ingthecodeindiff
erentblocks:

//usingnamespaceexampl
e
#incl
ude<iost
ream>
usingnamespacestd;

namespacef
ir
st
{
i
ntx=5;
}

namespacesecond
{
doubl
ex=3. 1416;
}

i
ntmain( ){
{
usingnamespacefi
rst
;cout
<<x<<' \
n';
}
{
usingnamespacesecond;cout
<<x<<' \
n';
}
r
eturn0;
}

out
put
:
5
3.
1416

14 P.
T.
14 O
Namespaceal
iasi
ng

Exi
sti
ngnamespacescanbeal
i
asedwi
thnewnames,
wit
hthef
oll
owi
ngsy
ntax:

namespacenew_
name=cur
rent
_name;

Thest
dnamespace

Alltheenti
ti
es(v
ari
ables,
types,
const
ants,andf
unct
ions)ofthestandar
dC++l i
brar
yar
e
declaredwit
hint
hestdnamespace.Mostexamplesi
nthesetutor
ial
s,inf
act
,incl
udethe
fol
lowingli
ne:

usi
ngnamespacest
d;

Thi
sintroducesdir
ectvisi
bil
i
tyofallt
henamesoft hest
dn amespaceint
othecode.Thisis
doneinthesetutor
ial
stofacil
it
atecompr ehensi
onandshort
enthelengt
hoftheexampl es,
butmanypr ogrammersprefertoquali
fyeachoftheel
ementsofthestandar
dli
braryused
i
ntheirprograms.Forexample,i
nsteadof:

cout<<"
Hel
l
owor
ld!
";

I
tiscommont
oinst
eadsee:

st
d::
cout<<"
Hel
l
owor
ld!
";

Whethertheelementsinthest
dnamespaceareintr
oducedwithusi
ngdecl
arati
onsorare
ful
lyqual
ifi
edonev er
yusedoesnotchangethebehav i
ororeff
ici
encyoftheresul
ti
ng
progr
am inanyway .I
tismostlyamat
terofsty
leprefer
ence,al
thoughforproj
ectsmixi
ng
l
ibrar
ies,
expli
citqual
i
ficat
iont
endst
obepr ef
erred.

St
oragecl
asses

Thest orageforvari
ableswithgl obalornamespacescopei sall
ocatedfortheenti
re
durati
onoft heprogram.Thisi sknownasst ati
cstorage,anditcontrast
swi t
hthestorage
forlocalvari
ables(t
hosedecl aredwi thi
nablock).Theseusewhati sknownasaut omatic
storage.Thest or
ageforlocal v
ar i
ablesisonlyavai
lableduringt
hebl ockinwhichtheyare
declared;aft
erthat,
thatsamest oragemaybeusedf oral ocalv
ariableofsomeother
functi
on, orusedotherwise.

Butthereisanothersubst anti
aldi
ffer
encebet weenvar i
ableswithstat
icstor
ageandv
ari
abl
es
wit
h
aut
omat icstorage:
-Variabl
eswi hst
t ati
cstorage(suchasgl obalvari
ables)thatarenotexpli
cit
ly
i
nit
iali
zedareaut omat i
call
yinit
ial
i
zedt ozeroes.
-Variabl
eswi haut
t omat i
cstorage(suchasl ocalvar
iables)thatarenotexpl
ici
tl
y
i
nit
iali
zedareleftuninit
ial
ized,andthushav eanundet erminedv al
ue.
14 P.
T.
14 O
Forexampl
e:
//stati
cvsaut
omat
icst
orage#i
ncl
ude
<iost
ream>

14 P.
T.
14 O
usi
ngnamespacest
d;

i
ntx;

i
ntmain( )
{
i
nty;
cout<<x<<' \n'
;cout<<
y<<'\n'
;ret
urn0;
}
Out
put
:
0
4285838

Theactualoutputmayvar
y,butonlytheval
ueofxi
sguar
ant
eedt
obezer
o.ycanact
ual
l
y
cont
ainjustaboutanyv
alue(i
ncludingzer
o).

14 P.
T.
14 O
Lect
ure-
42:
New&Delete
Oper
ator
s

Dynamicmemoryal
l
ocat
ionmeanscreat
ingmemoryatrunt
ime.Forexampl
e,whenwe
decl
areanar
ray
,wemustprov
idesi
zeofarrayi
noursour
cecodetoall
ocat
ememor yat
compil
eti
me.

Buti
fweneedtoal
locatememor yatr
unti
mememustusenewoper at
orfol
lowedbydata
ty
pe.Ifweneedtoallocatememoryformor ethanoneelement,wemustpr ovi
detot
al
numberofel
ement
sr equir
edinsquar
ebracket[]
.Itwi
l
lret
urntheaddressoffi
rstby
teof
memor y
.

Sy
ntaxofnewoper
ator

pt
r=newdat
a-t
ype;
/
/al
loct
ememor
yforoneel
ement

pt
r=newdat
a-t
ype[si
ze]
;
/
/al
loct
ememor
yforf
ixednumberofel
ement

Delet
eoper at
orisusedtodeallocat
et hememor ycreatedbynew oper
atoratr
un-
ti
me.
Oncet hememor yisnolongerneededi tshoul
dbyf reedsothatt
hememor ybecomes
avail
ableagai
nforotherr
equestofdynamicmemor y
.

Sy
ntaxofdel
eteoper
ator

del
etept
r;
/
/deal
l
oct
ememor
yforoneel
ement

del
ete[
]pt
r;
/
/deal
l
oct
ememor
yforar
ray

Exampl
eofc++newanddel
eteoper
ator

14 P.
T.
14 O
#i
ncl
ude<i
ost
ream.
h>
#i
ncl
ude<coni
o.h>

14 P.
T.
14 O
v
oidmai
n()
{

i
ntsi
ze,
i
;
i
nt*
ptr
;

cout
<<"
\n\
tEnt
ersi
zeofAr
ray:
";
ci
n>>si
ze;

pt
r=newi
nt[
size]
;
/
/Cr
eat
ingmemor
yatr
un-
ti
meandr
etur
nfi
rstby
teofaddr
esst
opt
r.
f
or(
i=0;
i
<5;
i
++) /
/Inputar
rrayf
rom user
.
{
cout
<<"
\nEnt
eranynumber:
"
;ci
n>>pt
r[
i]
;
}
f
or(
i=0;
i
<5;
i
++) /
/Out
putar
rrayt
oconsol
e.
cout
<<pt
r[
i]
<<"
,";
del
ete[
]pt
r;
/
/deal
locat
ingal
lthememor
ycr
eat
edbynewoper
ator

15 P.
T.
15 O
}
Out
put:

Ent
ersi
zeofAr
ray:
5Ent
eranynumber:
78 Ent
er any
number:45 Ent
er
any number : 12
Ent
eranynumber:
89 Ent
er any
number:
56

15 P.
T.
15 O
78,
45,
12,
89,
56,

15 P.
T.
15 O

You might also like