0 ratings0% found this document useful (0 votes) 16 views35 pagesModule 3C++Notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
ovesloadinng cD ome Of
of c++ Lang
emhamced the power of
Afler oeeloadling clns
Ue Objects ta
Nay that you use built im dlata -t 470s
704 Caer overtoad operahre by ukiwg Creahin
fumiWou i
™ opevats funceloar depiaes
!
aha clhat She overloaaled
operatey
lahve A the lacs Upoam Nhich uk pill porkCyeahag a aeaubey operahs {
A mreaubts opevatos junnihions fare this general fase
yel_ type — clacs- mame :' opesotos Ht (on hist)
9
i
H/ Operation s
$
ret- type =7 yetusm J4pe n always claw Type (ovjar)
Cobject of the clove)
Clast- mane =7 manne OF the clats
At => place holder ce operat thar hatte ve
Oviiloaded ( 4+ 0 — o * w= ake)
ag - List => Lest of Aiguancants
Hote: arg-lict => Bimary operat ayy- [ror thewe will
be omly ome arguement » Yaaary Op
ahr te will enapky C Member Amor were
4 emenu br, Suaced oa)
losmar) & Ome
op Operatey
MnFt fonclucle < ioetsran
Whig
Mamuacpace Cel
class Loc
* mt loagituce , latitude
public koe > §§
int Le)
Loc Cimt lq
tomgitude = Lg, labtuck
void Show C)
cout 42 dogitucs <<
Cour 42 fahtude <<
loc Opevatos+ ( loe opr)
b;
1 over tood +4or doe
Ave does: operatrt Choe Op)
£
loc tonup }
Leoup. Lomgidudt® Opa longitude + longitude
Lemay. labbudh = ©p2 fotitud + ka tituch
Sa
yetarm lenny)Tot maaincy
¢
Obs ( Wo
Obi. Showl)
Ob2- Show)
fu cech on
Obi Obl + Oba |, // Operatrs
Obt.showl) > deploy
Yelurm 0)
pone Operator + Cloc Op2) have Ontly Ome operand
But cthave are Jno objects ( obt &0b2) - OFF objet
“ “sel ag this Obs u
Layt 0? opevats + paused Using [nr
yes pompible for gemerah a call do operator
fod] coi P v
Oba ( operamd om dhe yugnt oF operat) v
OPp2ude, Cablude
pubke: Looe s ff
loc Cie lg yiak Le)
t
Longitude = Ig
Latitude = UF}
Vecd chow C)
i
* cow: 24 tude 42
Cour 42 labtade <2
t
toe opeyator + (loc op2); 12 Biman
loc optrator - ( loc ©p2)-
loc opesatos = Cloe opr) }
Loe operator ++ C) } Humany or
aa
1 over toad + toc
doc loc i opecatve + (foe op>)
$
vow Loc temp}
Leomp. Lomgilude 2 Ops. lomgitude + Lomgitude
deep Aatetade = 072. doilude + labtuck ,
repose Femup. dahtade% Ops dabtud A abitud
Ye 1 flan sleaup ;
verdoad -~ doc
loc :: operates — ( loc opr)
ee ere
Loagitude — opr. longi tud
Lemp lougitude =
lah tud
temp. Lahtuck = daitud - opa
Yedusar sbemup :
ovivload aggiqgmmnemt fy loc
loc Operator = (Loe op2)
longitude = ops. longitude :
lotidud . opr. fakitude }
Yeluim xthis }Lovgiluct +1
Larlude
veda «the
loc Obi (10,20), Ob2 0,30)
Obs Chowe) , J dkeplay 10
Ob2- showl)) Wf =
+40b) 5
Obs chow) > J) Aveplay 21
Olea ¢ Yoo wh)
Ob, ++0b) 5
obi. chow) 3H) Aspley 12 2»
ob» Showy 5
Obi = Ob2 =0b3) / muthple arngqman «1
Obt. Chow €7) Ht Akeplay 40 40
Obs. Shoncy iH r
Yolusmn 0%a Syiead
ed
aands Caplieitly Maire pose , alex ovr teubltey [hart
Mperaboe Puptohow Thic aueams cthat frend
verloads a bimary operat has two parad
At induale < iostsean >
WSiang manuesparc
boc
Stal
Private (at lomgitade | lakdude '
puolic: loceré $ H meed h tometruct tenupora
foe ( iat dq, int Le)
i
lomgidude = bq ;
$ fartude = Ue}
Void Chow CY
Cour << lomgituch <<* ”
Cok xx latituch 2g 7”
Sn $
1 0% 4% oyestonded tring Yremd Slact om
} vem loc operator + (oe opt toe op2)>Joe optrahe loc 073)
Jeu
Coop. Lomgitudd = opt lemgitu + of
Eoaup. da dud opi fabtude + oj
Tebusm lenup
imb main co)
é
loe obs (10,20) , oba C£,30)>
Obi = Obi + ob2
Obi. Showed
Teduim 0%
NOTE: 3, you cam mot Ourvloud hue opesates
Lyitna famebom = 0), £1 >
When overloading the tncreanemt w decre
you will meed de Uke o veprence paranueter
Sairand Cun chow
2» Nomgitud.
pe laRbuds
macart operator
phear cingfs pviloadyigec7 ies
Usiw a trend i 2
| Ts fatima. ae
Ub a vefreante posdmmeler — Jhit D because
vi enn furrchoas Ao mot have thie po tere
tt < jostean >
Using mamuerpace Std
lace loc
Private: int Longitude, Yakitucle »
publee bocce $ 5
boc Cit dg ,imt Le)
t
lomgiduce = tq ;
latitude = bt,
5
Votd howe)
4
Cow << lomgilud <2 ~
Cout- <4 latituk <2"
boc operator = Coe opr)
Sri toe operator t+ C foe gop)
Siem toe operake -- Cloe op):
$jY purvtoad acsigmauemt fos lot
operahy = (doc opr?
gituce
fattude 6p lab lude
Team ath Wc velucn object thet ge
deo) Using Priamd lunch om
7 efreate paranucles
opecats +4 C loc oP)
oP. lomgituck ++
OP lofitud ++ >
Yetuim OP)
f
af tumchom
<= pvetadid Urveg Sea
Joc operahy -- ( boc xo?)
op. Aomaptudt == +
op. laktudt ~~ ?
Vetus OP,
Lk main C)
t
sob?
loc ;
loc | ObsN CI RMamMe oo
copa. ¢h?
ob) Show C)
yeduim 0%
¢+obt 5 I) dieptay t
Ob2 -yoOb!)
ob2 cron, tt displayAllocate aun Objech
i
iu perform allocation Thros bi
oavdruchr eatted aubrmaatcaly +1
Yefurm pointer +h anenvord
7 delete aun objeck
void operater delete delete (void *?
Ja Pree memory pointed +
Desdrucetys called acu awah eal
The
ype Sized 2 & deyaudl Type capa
A the fa.gess Kenge rece Of memory
allocated (6
Cire-b W etsembially ar vasigned inl eg
The pasonmerey Stae pill Comtain the auouber of bytes
meeded tv hold h
The object being allocated . drier 7)
nwa ounl Ol memory Clhat yous versiom OF men auutt allocate
The ovsloaded men CumeKonr must yelurm a potter trIhe ameatory efhat ue allocates of cthren’” bad. alloc
excephom éf au allocahomr enor occurs
she delete fanchoor seeive’ a posits
ed
Aeletle optvahy whem oveiloaded
Pca sna tncirecs ect stale ade lete
holdid by the object
the amenue
f Ae oor}
Ft incduds < iottyeau >
Ht indude< cstdliby
Ht ima < nen >
ucimg manmespare Crd |
Claes oe
fomgituds , takdude
imt
public: loc cr tt
foe C iat kg , it de)
{
longitude > 1g)
taktude = Ley
void Show)
é
cour 44 Lomautuce <+
cow 44 ott 42°")
5
void «operator men (Sire-
aivr dette C void *p>
t size) )
void oper
i)um overloaded! yelakve do doc
sid xloc:: optvales men Csire-t $120)
i Void ap
ou tiloaded men \en
P malloc ¢ Cire)
& Crp)
5
bad. alloe ba
threw ba)
Yelucm Py
3
7 delete bveyloaded velabve bh doe
void loc: : operates ¢ delete Cvoid ¥P)
t
Cour << "Pa ovevlouded delete \m
Sree CPD,
Imt main ¢ >
Pas men loc (1,20) 5
5
cateh C bad. alloc xa)
f 4
COUR << " Allocahom error fox P1.\m’ ;
5 Yeturm 1»nich Chad.allee xa)
cour Mlocahomr exros fo
yelum 3
\
Py—> chow C7
Pasa chew C)
delete 2
delete P2>
JYetuim O%
Sm overloaded mer
overloaded nen
int ovecloadecl dalele
Inn over loackd deleteINNERITANG
> imhented
class
clace That does the tmheritiag
v called the Derived class
e class Access Com
Whom a dete class cmhente amother , the
Of clhe base clase becomes mreanbess of the
Class
class derived clase manne > access bate class mane
é
$i
1 vody of clars *,
Acco’ Katus of the base - class mnemmbers tuciar
Ihe Abvived class determine! by access
The bare class access Apedpits maul be eidhes
public , private er protectedaud all protected men
srotected aueaubers of the derived
cases , Ua base's private heamemt:
base aud ax aot actomibl by mmewaber
class
ecaauple iluttral Odject ot the dype Eenved
divectly acers the public meaubtsé of the base
ff includ
using manuespaee Ctd ;
Clase base
mr 2,5 5
public void Set Cit a , it b)
fie &) a=bi$
void Show C)
t
cour aaa | <<
5
sh
Clas deaved Hi PuBMERMigE
imt K}
derived Cim'
public « ea ketVoid cnowk
howk(
vdurm 0
}
Ihe bake clase wv éaherited by unny +
fier > all publee aud protected Membe
claws becomre private aucmmbers OF the denve
2anuple lhe polloning programas pill not eve
Dacause beth Sete) aud Show) ase mon private el
° derived
Ht imcludk 4 josheauy
UWomg aranucspare Stl
Cots dase
iat 4
public: voidl Se Cimt a, imr b)
t eye bad
Votd Show )
courace xg" “425 ae
4prvale base
class @ derived
t
it
denved Ciml *)
publ
oer Ly
r
Void ghonke)
2 cout 44K £4
t
imt auaim ©)
dovved Ob(3)%)
Cammor att
Ob. Sk C1,2)3 /) error
Ob-thond) > Il ever cammsl =
vetusm 0%
j
Tarheritamee & protected Members
Re aera
The protected boy nocd & émeduded uA c+t DP
cam
of
Greater fleaibilily tm the tmhentancee mechamt
Whom a marenuber Of a late VY declased as pwter’
momauembe
Hat murnuber @ moe accorable by othe:
dod aucnubert
Clements OF Chhe pr gran. However pavtec
peg Cliff eontby Tf Cle pure clare w cmhente
public , them the bane class protected amenubess beceant
ot dhe ohne? clax aud are
d as
| Protected ereanbertMprvate + bat
public
Voto ek Cink a, imt b) § t=
L
Void chow) f cub<<4 <2
26
class denved : public base
i
int ky
Public: Void setyc) { k= L439)
Youd CnouKl $ cour << k <<
5)
lob nradar 6)
derived Ob}
Ob. $u (2,3) B
LS? 2
ob. gnowey > // Aspley
Ob. sekK 0) >
Ob shook (0; I} display 6void sek Cimt 0
votd fhowe) £ cour <4 ¢ 4%
Clocs devived’L public bae |) 245 cahenle
imt KY
pubke: votd wn oi Lad55
i
Clos devived2 + publee derived peal tosh
{
t
Obl
votd Shows) { couk <4 6 <4
frau dhived
int om 3}
public » Vowd germ) 4 met
york Showm() § cour <<
oh Shon) 5
PToov». tek?
Obs. Suremcic
Ob». Show kO)
Ob». Shonant)
YU usar 0
iG
f ckd Bake class Imhentamce
jeu possi vle do éahent a bake clas as protected
» dome, atl public & protect af auembus OF the aM s
become protected nuenubers of the derived lacs
Ht imduds 2 tocts ean >
aed naiude spate Cid 5
Class bate
prolecled: teat 4,5 5 [Private b hare Aucessarle by denve!
public! Gold éebiy Cin a, dmtb) f izas3~b-t
Void shawty C) 4 cout x b <2" "az jdk
Sycot f Getay CU, 12) 4
auets posers 447 aud SoU C
yee Kae<
Vord Let ehowe) f
tow nmaian ©)
£ grived ob;
// ob wij 2)? Sau oo patected au
desieed
Ob.cuKd), Hob pubic augaubts? OF
Ob. snow (95 OR publte mueaubert of usiv
6b. ShowipOs H clegal Zhon ij v pe
of She danved
Yeturm oO)Tmheribarg Multiple Bake cla :
1 csivle or a denved clacc timber
derived Omnents
Protected » imk x
pub Ke void Showxd) § Coureg 7 ) AL
derived Ob} Aeparant & eat bare
Ob. sek (10, 20) 5 cla Ahould have
6b. Shown) 5 MH dicplay 10 | Access Lpeuipine G pul
ob. Shang 5 [| —»
5 return 05
- 20henlance
major quethomt “that a
t
and dostracort Orem he tahoot
acs & donved clawe ComAractors
yostvuctsst art called
an parannclere be paksed fo bare clos
mstyuctors
Comvtrutiors & Dettruttv7s axe executed
porsire fora bare date , aderved claet
fe Comiaim Com\ruclort ava [er destruces
Emrportamt to ymderhtand the orcas um Ohich
these fameboms are executed dem amr Object
Clerived class Comet émdo ekictamce aud Ahem Ut Jo
Our of exrtctamce
H imclude x iostyeauy
Using mMomnecpaie Ad 5
Clogs bate
public: base 6) t come £4" tomsdvuctiong bare\” a
og bose \'3 4
base? £ cower 44" Daitvuch:
b,
clay denved + public bare
£ public: derived ©)
— dined ©) & covd £2
{cow ne toad ruttiay avd
wm perieuchoy poe; &objeet
Lomsls ut b)
‘ cam ple Aiaupl
ply
Ihic program
Comitrecharg bake
Comitruch ay dinved
Dettvachg alevived
Detdvech we bare
cux ot der
F Combtrechs& are executed anther oF
Dettyudess ave executed tm Yeverse oschs
Cake OF Maltipk Imhentamee The Lanne rule APPS
H incuck < fotfyeau.hs —// ekamuple om maldileel|end
Imhentame
u oe Mamses pare tol 5
Clas bakes
public: based) f cour 44° coouhruchong bere\n
my busel) 4 cour <2" Duirutbag dear”) 5
0
clos deviveds } pablre bare
public: demvecl Wf cow <<" Comabsustiog deavsd3\)
wv ded 40 $ cour ed" Des choy dsaved 20h
byclass denvec2 + public deniveds
public derived 20) §
denvedl2 Ob
omstrect destruct obs
¥ our pat of Clhic proqrann
Combrachng hare
Comptstech ag devived §
Commiruch ay derived 2
Dettruchoy devived >
Destseuchng derive 1
Destouch og bare
Examaple om Muldple Imhentamce
ft imulude 2 iotteaus
Ca mranmecpace Sty
Class baser
public! baserc) £ courea” Coniruekong aver ¥
based & coupe” dechuchag bued \n i}
ia
Clase base2 ‘
£ public: pase rer Cout2é " Conmtyuch ng basea\or 5 $
| wv bose 2O? f cours" Distracting bure>\n ah
| bpubke bare 2
clas denver Oe bare,
eats ot
conmtruch4 ‘
deaved” ay
deaved ) § cowr ale
£
public
| w denived © & cout <2" per coy
| b>
tay mata cd
derived Ob}
270
1 comjruth dod Destruct ob ra
yetum 03 Tp Bz
olp fy Lop
Comedyecth ore J
“4 apoe =>pd
Cooanty uth ay bune>
Comaruchag Derived
Detsuchag besved
Destruckag bane 2
| Destruchoy bone) A
| Nole « '
— #Com\yuctes Art ‘called va Ovdy ot durivatioon
deviver! gabentaate ksh
ordtx ¥egnt lyfanmaredey 5 a ;
avamacley¢ -ty Bare cleats commlruchs?
pe
possible pa asanueters f'svan alevivicl clace Comly
tetoes to bane class comlyuctos — General foram in at pollens
devved amlruchy Carg-lict) | bared (aq list)
bane (
t
M1 body of derived Comtlructe
}
H imeludi< tortreauy
Asiana manver pace ad)
lace base
5
Protected ! imt L 5
Couk 24 Cons
pubwe + base Liat) ee)
whune C) { cour dd” petraciy
$
class denved *
{
puble bare
ior 3°,
public
/} Denyed Uses x5) Yo pasted along fo bar
yi)
devved Cimt & » imt yt barely) 249 C
t
Jen)
Commbrachag devived
(cee
{ cour <4" pectruchag dived”,
vdoiwed ©)
WY vor Gh C) f cow ds ¢ 42
s,
eS
}fo Clh xamuple derived Comuyuctos
Joclasil ay dabierg
nuetert x andy. However Devivel wer Ook
heat a base class i» imhivled as pavate, all
eapbers OF Shak Clast becom
publcc aud protected a
embers Of cfhe devived! class . However , im certain
assy foamt Jo wostore ome oy maoze Emhented sermon’
to onigiaal access Sa Phis vo possible da Crt
by uikng aces dedavabom
2
: clos bare
f
public: imy > W public es base
$5
// Tenhint bide as private
class devived | private bare
t
public
Y heen acces declarahom
bases: dT) // mate 3 public agaionexample bane ex inherited as privale by
derived public amembeu 3 1 anadk a private eucabe
of
lerived class. Jloweves ny mulucliong
Jag
pase: Hib tow 3 im pubic im dlevived a0
tere declasahom meer dhnved's publee headiag
public Adatos
EX. dhe fi Uoriang prograc eUlastyare
Abom 5 moter how co odes aceass detlavahow
Fy Seti t) anal geticy ch public Status
F include 4 iostyeany
Usiag manvespace Md 5
Clasé base
5
imt 4, 4 prvate ty base
public: im 5k »
void febi Cimba) { t= 2%}
éent gett ©) § retuim OF
bs
I) inhente dhe bane as private
Class derived : private bake
s
public: baker: J jH] make J public agun
pases! Seti $)s// mate sei punlic
panes! gx TOs! aware gett public
Hi toanest hy A Hhegad » you cane cleat acer’
imt a |} publee
iantidiy Clhis prigsama
HH vonlodh 4 (co stseaur)
4 anaamespace Cd;
0% bake
imk 2 5
Y
M deivid) iomherttes bave
class diviveds + public bare
public: tm ) y
5,wh both denvedy ) deavid
are piee oF bare bryietd
W public deviveds , pubbe denved
public: fmt cum
ain ¢ )
denveds ob 5
Ob t= 103 HM this 0 aembi
ou, x
Ob.J = Qo
Ob.k = 30}
4 4 o aambeguous hese ho
Ob Summ= Ob + 0b.5 FOb-K 4
1 also ambiguous Nnic & 2
Cou £4 Ob da” ”
Coux << 0bd KK" " 2g bik 44
Couk << Ob tar}
vetuim o!
h
Im che above prvgsams both denivedd aud cyived 2
fl
i dS aut
imheri base, Honeves dlerivtc!4 jtherile both devised
Cerived2 This mncams clhere at px copies oO} bare3 Theryptr
objec! OF type deny 13 }
MW expr esinrom Like Obi- te
- ferived L
Hin Ate eens
hee the Atatew
thevintly ambiguous
foo ways
this amaguily cam be overconue by
=7 Using Ccope resoluboar opesaha
mg base clase as virtual C aboe trauple dense} 5
darived2 an virtual
Scop retolubear gpevatry ci “the abovt example
tant mata ¢)
devivids Ob ;
Ob. denved 1: t= 105M Scope vedelved use denveds's 4
opt setleve
ob sum = ob-deivediiid +0b- dF tank » /s«asc denvedt : virtual public base
imt 35,
public
4;
Class derived2 . Virtual public base
f
public: Im k 5
b
J+ denved3 tathents both denvedt aud denrid2
these w domly dare Copy of base clase «)
clase derived » pubkic denvidt , public deni
tent Sum 5
pubke
ton maior C)
t
devived3 Ob5
ob.t = 05H men umainbrgous
Ob J+ 203
by = 30+
A vananmbagous
| Ch AC) HO
cour 44 ob Sum a
t yeduin 0}