let us c++.pdf
TRANSCRIPT
-
8/20/2019 Let us c++.pdf
1/107
2. Primitive Types and Operators 17
2.1 Modulus Operator % ..................................................................... 172.2 Conversion Between Different Types in Calculation ........................... 17
2.3 Do Not ely On t!e "recision of #loat Nu$ers ................................ 17
2.& 'ssi(n$ent Operators .................................................................. 172.) *alue of 'ssi(n$ent +,pression ..................................................... 172.- T!e nte(er *alue of C!aracter ...................................................... 17
2.7 /o(ic Operators ........................................................................... 17
3. Control Structures 18
3.1 Control 0tructures ........................................................................ 1
3.2 if ................................................................................................ 1
3.3 ifelse ......................................................................................... 13.& Conditional Operator .................................................................... 1
3.) w!ile .......................................................................................... 13.- for /oop ...................................................................................... 13.7 'void Modifyin( t!e Control *ariale in t!e /oop Body ...................... 1
3. switc! ......................................................................................... 1
3. dow!ile ...................................................................................... 1
3.14 5rea6 and 5continue ................................................................. 1
4. Arrays 21
&.1 Declare and nitiali8e 'rray ........................................................... 21
&.2 'rray 0i8e Must Be Constant.......................................................... 21&.3 'rray 0i8e ................................................................................... 21&.& 'rray and "ointer ......................................................................... 21
&.) "ass 'rray to #unction .................................................................. 22&.- 0earc!in( 'rray ........................................................................... 23
&.7 Multiple0uscripted 'rray ............................................................ 23&. 0trin( 9andlin( #unctions ............................................................. 23
5. Pointers and Strins 25
).1 "ointer Declaration and nitiali8ation............................................... 2)).2 Castin( Between Nu$eric 'ddress and "ointer ................................ 2)
).3 Constant "ointer and "ointer to Constant ....................................... 2)
).& "ass "ointer By eference ............................................................. 2)
).) eceive array wit! pointer ............................................................. 2-).- "ointer +,pressions and 'rit!$etic ................................................. 2-
).7 "ointer Offset and 0uscription ...................................................... 2-). :si8eof: Operator.......................................................................... 27
). 0i8e of 0trin( and C!aracter 'rray ................................................. 27
).14 #unction "ointer and Call Bac6 Tec!ni;ue ........................................ 27).11 'rray of #unction "ointer and MenuDriven 0yste$ .......................... 2).12 "ower and #le,iility of "ointers ..................................................... 2
-
8/20/2019 Let us c++.pdf
2/107
!. Class 32
-.1 Class .......................................................................................... 32
-.2 Met!ods of a Class ....................................................................... 32-.3 Constructor ................................................................................. 32-.& Default Construcotr ...................................................................... 33
-.) Copy Constructor ......................................................................... 33
-.- 'ccessin( Class Me$ers .............................................................. 33-.7 Typical Met!ods ........................................................................... 33-. 'void epeatin( Code ................................................................... 3&
-.
-.1) Me$er O?ects ........................................................................... 3--.1- Me$er O?ects 0!ould Be nitiali8ed wit! Me$er nitiali8ers .......... 3-
-.17 #riend ......................................................................................... 37-.1 t!is pointer.................................................................................. 3
-.1 Me$ory 'llocation and Manipulation ............................................... 3-.24 "ointer 0tatus after delete ............................................................. 3
-.21 Me$ory /ea6 ............................................................................... 3
-.22
-.2) assert ......................................................................................... &1-.2- "ro,y@
-
8/20/2019 Let us c++.pdf
3/107
8. "n#eritance 48
.1 Met!od Overridin( ........................................................................ &
.2 nitiali8ation of t!e Baseclass "art of t!e O?ect .............................. &.3 Conversion etween ase class and derived class ............................. &.& 5isa> 5!asa> :se': and :Jnow': elations!ip .......................... &
.) "ulic> "rotected and "rivate n!eritance ........................................ &
.- 0!rin6in( n!eritance ................................................................... )4.7 Met!ods T!at 're Not n!erited ..................................................... )4. 0oftware +n(ineerin( wit! n!eritance ............................................ )4
. "artial 'ssi(n$ent ....................................................................... )4.14 0e;uence of Constructor Call in n!eritance .................................... )1.11 Default Constructor in n!eritance .................................................. )2
$. Polymorp#ism 53 .1 *irtual Met!ods ............................................................................ )3.2 "oly$orp!is$ .............................................................................. )3
.3 Dyna$ic and 0tatic Bindin( ........................................................... )3.& 'stract Base Class G'BCH ............................................................. )3.) *irtual Destructor ......................................................................... )3
.- 9ierarc!y for nterface and $ple$entation .................................... )3
.7 Base Class dio$ ......................................................................... )3
. 'pply "oly$orp!is$ on Operator AA and .................................. )&
1%. Stream "O 55
14.1 ostrea$ /irary 9eader #iles ........................................................ ))14.2 0trea$ O Classes and O?ects ...................................................... ))
14.3 Output t!e address of a pointer ..................................................... ))14.& Met!od put .................................................................................. ))14.) 0trea$ nput ............................................................................... ))
14.- nfor$atted O............................................................................ )-
14.7 0trea$ $anipulators .................................................................... )-14. 0trea$ +rror 0tates ..................................................................... )
11. &ile Processin 5$
11.1 Data 9ierarc!y ............................................................................ )11.2 "ri$ary Jey ............................................................................... )
11.3 #iles and 0trea$s ........................................................................ )
11.& #ile Open Modes........................................................................... )
11.) C!ec6in( open and input success ................................................... )11.- Met!od e,it ................................................................................. -4
11.7 #ile "osition "ointer ...................................................................... -411. 0e;uential 'ccess #ile ................................................................... -4
11. ando$ 'ccess #ile and O?ect 0eriali8ation .................................... -411.14 #ile and Directory Manipulation .................................................... -2
-
8/20/2019 Let us c++.pdf
4/107
-
8/20/2019 Let us c++.pdf
5/107
1.
1. C'' (AS"CS
1.1
1.1 Advantage of Structured Programming
'lt!ou(! it is a trend to use o?ectoriented pro(ra$$in(>
structured pro(ra$$in( also !as its advanta(e. nternal structureof o?ects are often est uilt wit! structured pro(ra$$in(
tec!ni;ues. 'lso> t!e lo(ic of $anipulatin( o?ects is este,pressed wit! structured pro(ra$$in(..
1.2 1.2 Interpreter and Compiler Program
nterpreter pro(ra$s were developed t!at can directly e,ecute
!i(!level lan(ua(e pro(ra$s wit!out t!e need of co$pilin( t!esepro(ra$s into $ac!ine lan(ua(e. t is used on cases t!at
pro(ra$s are fre;uently updated. Once t!e pro(ra$ is developed>
a co$piled version will e produced to run ;uic6ly..
1.3 1.3 Escape Sequence
5K is escape c!aracter. t to(et!er wit! t!e followin( c!aracter
for$s an escape se;uence used in output state$ent. T!ey are
used to control t!e printer and are not printed out.
5Kn c!an(e to a new line. t is a (ood co$$on practice to add
it in t!e end of all printin( state$ents.
5Kt !ori8ontal ta.
5Kr carria(e return L return t!e cursor to t!e e(innin( ofcurrent line.
5Ka alert. 0ound t!e syste$ ell.
KK used to print out a 5K.
5K used to print out a doule ;uote.
1.4 1.4 Namespace
include Aiostrea$usin( na$espace std
int $ainG H
Pcout AA 5
-
8/20/2019 Let us c++.pdf
6/107
' na$espace is a (roup of software co$ponents wit! t!e sa$e
na$e prefi, L e.(.> std. +ac! !eader file in t!e CII draft standarduses a na$espace called 5std to (uarantee t!at every feature
provided y t!e CII standard lirary is uni;ue fro$ softwareco$ponents developed y ot!er pro(ra$$ers. T!e state$ent
aove si$ply says t!at we are usin( software co$ponents fro$t!e CII standard lirary> suc! as cout. f we use t!e na$espace
in front of eac! software co$ponent> t!en we neednSt t!estate$ent at t!e top. f we want to define our own class lirary>
we s!ould use our own na$espace.
1. 1. Advantages of !! Programming
OO pro(ra$$in( !as a lot of advanta(es over procedure
pro(ra$$in(> $any of t!e$ are ac!ieved y data encapsulation.
"rocedure pro(ra$$in( can also call e,istin( functions to ac!ievecode reusin(> ut functions and data are separate in ot!erwords> functions are stateless t!ey donSt re$e$er t!eir own
state across different calls. all data
to e $anipulated !ave to e passed to and returned y t!e
function. Data are t!erefore e,posed to pro(ra$$ers> w!o $ay$anipulate t!e data wierdly or carelessly. Besides> a sin(le piece
of data $ay e passed around and !andled y a lot of functionswit!in a lar(e pro?ect. it $ay e
very difficult to find out w!ere t!e error !appens.
n co$parison> OO pro(ra$$in( wit! data encapsulation can
avoid t!ese prole$s. Because data are encapsulated wit!functions to for$ an o?ect> functions can re$e$er t!eir ownstate and t!eir results. T!ere is no lon(er need to pass t!is part of
data to t!ese functions every ti$e t!ey are called. 0ensitive or
private data can e t!erefore isolated fro$ outside world. fanyone wants to do anyt!in( on t!e data> t!ey !ave to do itt!rou(! t!e o?ectSs functions> w!ic! can e well defined and
errorproof.
T!is si$ulates real world o?ects etter. Ta6e a $an as an o?ect.T!is o?ect can !ave a data $e$ers suc! as ody te$prature.Ot!er people can not directly c!an(e !is ody te$prature wit!out
(oin( t!rou(! !is own cooperation and p!ysical reaction. 0o ody
te$prature is a private data $e$ers isolated fro$ t!e pulic.T!is isolation eli$inates t!e possiility t!at ot!er pro(ra$s $ayaccidentally c!an(e an o?ectSs own sensitive data inproperly.
' wellwritten class is co!esive and selfcontained. t contains allnecessary data to si$ilate t!e realworld prole$> all necessary
-
8/20/2019 Let us c++.pdf
7/107
functions to $anipulate t!ese data and provide services to outside
world. t e,ists and functions ;uite independently> reducin( t!ecouplin( wit! outside world to t!e lowest e,tent> and t!erefore
$ay e reused in different occasions.
'n o?ect 56nows !ow to e!ave itself properly L !ow to
construct and initiali8e itself> !ow to response to different 6inds of
e,ternal $essa(es properly> !ow to destroy itself> etc.. Once aclass is properly written and fully tested> ot!er pro(ra$s cansi$ply $a6e use of it to perfor$ a certain tas6> and will !ave little
c!ance to encounter any error. T!is (reatly reduces t!eco$ple,ity of pro(ra$$in( and possiility of errors.
0o (enerally spea6in(> OO pro(ra$$in( and data encapsulation
!as t!e followin( advanta(es=1. 1. educes data e,posure= ecause private data are
encapsulated wit!in o?ects> w!en t!eir functions are called>
less data need to e tran$itted. T!ese reduces t!e e,posure ofdata and t!e c!ance of errors.
2. 2. Clearer responsiility for data= ecause eac! o?ect is
responsile for !is own private data and ot!ers can not wron(lyc!an(e it> w!en a piece of data is wron(> we easily 6now w!o is
doin( t!e wron( t!in(.
3.
3. /ess errorprone= if a pro?ect uses only t!ose wellwritten and fully tested classes> it is $uc! easier to or(ani8e>$odify> deu( and $aintain t!an t!ose written in procedural
lan(ua(es. T!e i((er t!e si8e> t!e $ore ovious t!eadvanta(e.
4. &. More stale for clients= w!en a classs i$ple$entation isc!an(ed> as lon( as its function si(natures are not c!an(ed> a
pro(ra$ w!ic! uses t!is class will not e affected.
5. ). +n!ances software reuse= y co$position Gincludin(
ot!er o?ect as data $e$erH and in!eritance Guild a new
class ased on a ase classH> software reuse is (reatlystren(t!ened.
1." 1." #i$rar% mat&.&
Consists of all $at!e$atical functions=
ceil G,H ceil G.2H F 14
cos G,H
e,p G,H e,
fasG,H asolute value of ,
-
8/20/2019 Let us c++.pdf
8/107
floor G,H floor G.H F
f$od G,> yH re$inder of ,@y as a float. f$od G.)> 3.2H F4.2)
lo( G,H lo( e,
lo(14 G,H lo( 14,
pow G,> yH , y sin G,H
s;rt G,H s;rt GH F 3tan G,H
1.' 1.' (unction Protot%pe
T!e function prototype is placed outside any function includin(
5$ain> ri(!t after t!e 5include preprocessor directive. T!atSs
w!y function prototype !as file scope.
#unction "rototype is so$et!in( #OT'N and earlier versions ofC do not !ave. t is desi(ned to enale t!e co$piler to 6now w!at6ind of a function it is efore a function is called. T!atSs w!y w!en
t!e function ody is efore t!e callin( state$ent t!e function
prototype is not necessary. t also enales t!e co$piler to find out
w!et!er a function is properly called i. (. wit! wron( nu$ers ofar(u$ents> and convert t!e para$eter type if t!e ar(u$ents
supplied is not correct.
Uou can include t!e na$es of t!e para$eters into t!e functionprototype to $a6e it loo6 $ore clear> ut t!e co$piler will i(noret!e para$eters.
1.) 1.) *loc+
T!e declarations and state$ents enclosed in races 5 P R is calleda loc6. ' loc6 is ?ust a co$pound state$ent w!ic! includesdeclarations. ' loc6 instead of a function is t!e s$allest
co$ination of state$ents in CII. Uou can create a loc6anyw!ere you li6e L ?ust enclose at least one declaration and onestate$ent wit! races.
T!e variales declared in a loc6 !as a 5loc6 scope L t!ey are!idden outside t!is loc6. *ariales declared outside t!is loc6 in
t!e sa$e function will still e 5visile inside t!is loc6 Gso are(loal variales> of courseH. 0o t!e c!aracter of a loc6 is different
fro$ a function= a function is of twoway infor$ation !idin(> w!ile
a loc6 is of oneway only.
1., 1., time-/
T!is function returns t!e current calendar ti$e in seconds. ts
-
8/20/2019 Let us c++.pdf
9/107
!eader file is 5time.#.
1.1 1.1 0andom Num$er eneration
unsi(ned seed
cin seedsrand)seed* @@ or srand Gti$e G4H Hy F a I randG H %
♦ V Pseudo+random se,uence
#unction 5rand returns a pseudorando$ se;uence of inte(er
etween 4 and 'NDWM'X Ga sy$olic constant defined in t!e
5stdli-.#H. T!e function prototype of 5rand is in t!is !eader file
5stdli-.#. T!e nu$ers (enerated y 5rand is actually a fi,edse;uence. +ac! ti$e you run t!is pro(ra$> you (et t!e sa$e
se;uence. To c!an(e t!is se;uence> you !ave to use anot!erfunction 5srand to 5seed t!e 5rand function wit! differentunsi(ned inte(er. ts !eader file is also 5stdli-.#. #or eac!
inte(er a uni;ue and fi,ed se;uence is (enerated y 5rand.
♦
V Scalin
T!e function to (enerate a rando$ se;uence of nu$er wit!in a
certain ran(e is called 5scalin(=
n F a I rand GH %
t!e rando$ nu$ers are fro$ a to a I .
1.11 1.11 Enumeration
'n enu$ is an alias of an inte(er. t setups up a correspondin(relations!ip etween a specific inte(er and a userc!osen
identifier. nstead of !avin( to re$e$er w!at an inte(errepresents> t!e pro(ra$$er can easily re$e$er t!e self
e,plained alias. #or e,a$ple> a set of inte(ers fro$ 4 to 7represents color lac6> lue> (reen> cyan> red> $a(enta> rown
and w!ite. 'fter we define
enu$ Color PBlac6> Blue> Yreen> Cyan> ed> Ma(enta> Brown>
we can always use 5Blac6 instead of 4> ut t!e co$piler will ?usttreat 5Blac6 as 4.
Now 5Color is a userdefined type. Uou can use t!is type ?ust li6e
int> float to declare variales> ut t!ese variales can only !avet!e values enclosed in P R=
-
8/20/2019 Let us c++.pdf
10/107
Color c1 c2c1 F Yreen
c2 F BrownifGc1 FF edH...
Uou can also ?oin t!e definition of t!e enu$ type and declaration
of its variales to(et!er=
enu$ PBlac6> Blue> Yreen> Cyan> ed> Ma(enta> Brown>
c1> c2
Uou can assi(n enu$s to ot! variales of t!eir own types> or
si$ply inte(er variales=
enu$ PBlac6> Blue> Yreen> Cyan> ed> Ma(enta> Brown>
int c1 c2
c1 F Yreen
c2 F BrownifGc1 FF edH...
By default> t!e first enu$ enclosed in P R !as t!e value of 4> t!e
ne,t 1>... > unless specifically defined=
enu$ PBlac6> Blue> Yreen> Cyan F 23> ed> Ma(enta> Brown>
T!en Blac6 F 4> Blue F 1> Yreen F 2> Cyan F 23> ed F 2&>Ma(enta F 2)>...
1.12 1.12 lo$al aria$les
Yloal variales are variales declared outside any loc6 includin(main function. T!ey are visile in all loc6s in all files in t!e sa$eprocess. n files ot!er t!an t!e one w!ere t!e (loal variale is
defined> you !ave to use 6eyword e/tern to tell t!e co$piler=
:T!e followin( (loal variale w!ose na$e is ,,, and w!ose typeis ,,, is defined elsew!ere> and you !ave to find out w!ere
yourself.:
Yloal variales can e defined in eit!er a !eader file or a source
file. But if you define a (loal variale in a !eader file> t!en w!en$ore t!an one files include t!at !eader file> $ultiple copies of t!e
sa$e (loal variale will e instantiated> and you will !ave lin6
errors. 0o you s!ould nor$ally put t!e definition of (loalvariales in a source file.
-
8/20/2019 Let us c++.pdf
11/107
@@ZZZZZZZZZZZZ (loals.cpp ZZZZZZZZZZZZZZZZZ
@@ Uou dont need a (loals.!Qinclude :stdaf,.!:
int array3E F P1> 2> 3R @@ array is t!e (loal o?ect
@@ZZZZZZZZZZZZZZZ '.cpp ZZZZZZZZZZZZZZZZZZZinclude :stdaf,.!:
include :'.!:include Aiostrea$.!
e/tern int arrayE
'=='GH
Pcout AA array4E AA : : AA array1E AA : : AA array2E AA
endl
R
@@ZZZZZZZZZZZZZZ B.cpp ZZZZZZZZZZZZZZZZZZZZZ
include :stdaf,.!:
include :B.!:include Aiostrea$.!
e/tern int arrayE
B==BGHP
cout AA array4E AA : : AA array1E AA : : AA array2E AA
endlR
@@ZZZZZZZZZZZZZZZZ $ain ZZZZZZZZZZZZZZZZinclude :stdaf,.!:
include :a.!:include :.!:
int $ainGint ar(c> c!arZ ar(vEH
P' a
B
-
8/20/2019 Let us c++.pdf
12/107
return 4
R
Output will e=
1 2 3
1 2 3
But t!e aove approac! is not w!at people nor$ally do. Because
t!is approac! re;uires eac! file w!ic! uses t!ose (loal varialesto declare all of t!e$ w!ic! 6eyword e,tern one y one> causin(
redundant code and is errorprone. T!e nor$al approac! is tocreate a separate !eader file and put all e/tern declarations of
t!e (loal variales in it. /o(ically t!is !eader file s!ould !ave t!e
sa$e na$e as t!e source file> ut it can e different Gas s!own int!e followin( e,a$pleH. T!en all files w!ic! accesses t!e (loalvariales can si$ply include t!is !eader file=
@@ZZZZZZZZZZZZ (loals.cpp ZZZZZZZZZZZZZZZZZ
include :stdaf,.!:
int array3E F P1> 2> 3R @@ array is t!e (loal o?ect
int 'NU F &
@@ZZZZZZZZZZZZZZ 'ny.! ZZZZZZZZZZZZZZZZZ
ifndef W'NUW9define W'NUW9
e/tern int arrayE
e/tern int 'NU
endif
@@ZZZZZZZZZZZZZZZ '.cpp ZZZZZZZZZZZZZZZZZZZinclude :stdaf,.!:include :'.!:include Aiostrea$.!
0include Any.#
'=='GH
P
cout AA array4E AA: :AA array1E AA: :AA array2E AA::AA 'NU AA endl
-
8/20/2019 Let us c++.pdf
13/107
-
8/20/2019 Let us c++.pdf
14/107
1.14 1.14 Creation and eletion of lo$al aria$les
T!e (loal o?ects constructors are called efore any pro(ra$ is
e,ecuated> and t!eir destructors are called after all pro(ra$ ends.
@@ZZZZZZZZZZZZZZ '.! ZZZZZZZZZZZZZZ
class '
Ppulic=
void 0ayGH
'Gc!ar Z na$eHvirtual ['GH
private=
c!ar Z $Wna$e
R
@@ZZZZZZZZZZZZZ '.cpp ZZZZZZZZZZZZZZZ
include :stdaf,.!:include :'.!:
'=='Gc!ar Z na$eH = $Wna$eGna$eH
Pc!ar uf4E
sprintfGuf> :Constructor of %sKn:> $Wna$eH
printfGufHR
'==['GHP
c!ar uf4E
sprintfGuf> :Destructor of %sKn:> $Wna$eH
printfGufH
R
void '==0ayGHP
c!ar uf4EsprintfGuf> :My na$e is %sKn:> $Wna$eH
printfGufHR
ZZZZZZZZZZZZZZZZ B.! ZZZZZZZZZZZZZZZZZZZZZ
class B
P
pulic=
-
8/20/2019 Let us c++.pdf
15/107
BGH
virtual [BGHR
ZZZZZZZZZZZZZZZZ B.cpp ZZZZZZZZZZZZZZZZZZZZZ
include :stdaf,.!:include :B.!:
include :'.!:
A -)O(A"6(*
B==BGHP
c!ar uf4EsprintfGuf> :Constructor of class BKn:H
printfGufHR
B==[BGHP
c!ar uf4EsprintfGuf> :Constructor of class BKn:H
printfGufH
R
ZZZZZZZZZZZZZZZ Test.cpp ZZZZZZZZZZZZZZZZZ
include :stdaf,.!:include :a.!:
A main)O(A"6A"6*
e/tern A -
int $ainGint ar(c> c!arZ ar(vEHP
printfG:KnBe(innin( of $ainQKn:H-.Say)*printfG:+nd of $ainQKnKn:H
return 4R
T!e output will e=
Constructor of Y/OB'/WNWM'N
Constructor of Y/OB'/WNWB
-
8/20/2019 Let us c++.pdf
16/107
Be(innin( of $ainQ
My na$e is Y/OB'/WNWB+nd of $ainQ
Destructor of Y/OB'/WNWB
Destructor of Y/OB'/WNWM'N
Because (loal o?ects are created efore any code is e,ecuted>t!ey $ust not e any resource t!at can not e initiali8ed :on t!espot: and !as to e initiali8ed y t!e pro(ra$. f you !ave to !ave
a (loal resource li6e t!at> create a (loal reference GpointerH tot!e resource> w!ic! can e initiali8ed to N// on t!e spot> t!encreate and initiali8e t!e resource in t!e pro(ra$.
1.1
1.1 Name Conflict *eteen #ocal and lo$al aria$le
f in a loc6 a local variale of t!e sa$e na$e as t!e (loalvariale is declared> t!e local variale will suppress t!e (loal onefro$ t!e declaration line onwards. To access t!e (loal variale
fro$ t!is loc6> use unary scope resolution operator :==: in front
of t!e identifier.
int , F 14 @@ Yloal variale
int $ain G H
Pint , F &> y
y F ,@ , @@ *alue s!ould e 4.&R
1.1" 1.1" Storage Class
+ac! variale or o?ect !as its attriutes includin( stora(e class>scope and lin6a(e.
♦ V auto
*ariales of auto$atic@local stora(e class are created w!en t!eloc6 in w!ic! t!ey are defined is entered> and destroyed w!ent!e loc6 is e,ited. ocal varia-les are -y deault o automatic
storae class. 0o t!e 5auto specifier is rarely used.
-
8/20/2019 Let us c++.pdf
17/107
♦ V reister
variale> it is to su((est t!e co$piler to 6eep t!is variale in oneof t!e co$puterSs !i(!speed re(isters in stead of $e$ory. T!eloadin( and savin( ti$e is s!orter t!an $e$ory. By placin( a
!eavily used variale into t!e re(ister> t!e total run ti$e can e
reduced. 9owever> t!e co$piler $ay i(nore t!is su((estion> ift!ere is no re(ister availale. On t!e ot!er !and> todaySsopti$i8in( co$piler are capale of reco(ni8in( fre;uently used
variales can decide to put t!e$ in re(ister wit!out t!e need for are(ister declaration.
Not often used.
♦
V static
f a local variale is declared 5static> it is still only 6nown in t!efunction in w!ic! t!ey are defined> ut w!en t!e function is e,ited>t!at variale is not destroyed> instead it is retained for ne,t use.
Before t!e first ti$e of use> if not specially initiali8ed> all nu$ericvariales are initiali8ed to 8ero.
f t!ere is an initiali8ation in t!e function suc! as :static int , F 1:
it only wor6s first ti$e t!e function is called. Ot!erwise t!e
variale can not 6eep t!e value of last ti$e and t!erefore !as no
difference wit! nor$al local variales.
T!is 6ind of scope is $ainly used y procedural lan(ua(es. #or OOit is rarely needed.
♦
V e/tern
Yloal variales Gand function definitionsH are created y placin(
variale declarations outside any function definition. lo-alvaria-les deault to storae class speciier 9e/tern:. T!ey
6eep t!eir values t!rou(!out t!e e,ecution of t!e pro(ra$> andcan e referred y any functions t!at follows t!eir declarations or
definitions in t!e file. 'ccordin( to "/"> t!e use of (loal varialess!ould e avoided unless t!ere is a special need.
1.1' 1.1' Scope
♦
V &ile scope
' p!ysical file is of file class. T!erefore> (loal variales> function
prototypes and function definitions> w!ic! are out of any functionody> are of file scope.
-
8/20/2019 Let us c++.pdf
18/107
♦ V &unction scope
Because a function is not t!e s$allest unit in CII> only laels are
wit! function scope. /aels are identifiers followed y a colon> i.(.> t!e case lael 5case 3.)= in 5switc! structure. /aels areused in 5switc! structure or 5(oto state$ent to $ar6 t!e location
of a state$ent> so t!at ot!er state$ent 6nows w!ere to (o. T!ey
are i$ple$entation details t!at functions !ide fro$ one anot!er.
♦ V (loc; scope
Because loc6 is t!e s$allest unit in CII> $ost
variales@identifiers are of loc6 scope. T!ey are local varialesdeclared in a loc6.
♦
V &unction+prototype scopedentifiers in t!e functionprototype declaration !ave function
prototype scope. T!e identifiers can e reused elsew!ere wit!outa$i(uity. T!is is t!e lowest scope in CII.
1.1) 1.1) 0ecursion
' recursive function is a function t!at calls itself eit!er directly ort!rou(! ot!er function. T!ere are suc! 6ind of prole$s t!at t!e
direct solution can not e easily e,pressed> ut t!e relations!ipetween t!e prole$ and its si$pler version is e,plicit. T!us t!e
prole$ can e si$plified repeatedly reduced to a s$aller version>until it reac!es t!e si$plest case called :ase case:> and finally
eco$es 6nown. n s!ort> recursion 6eeps producin( si$plerversion of t!e ori(inal prole$ until t!e ase case is revealed.
#ro$ lo(ical point of view> recursion is invalid or i$practical= youcan not use an un6nown solution to solve a prole$. But in CII
recursion only $eans to $a6e anot!er copy of t!e function andcall it a(ain. 0o recursion in CII is not real recursion. T!erefore it
is si$ple.
' s$art use of recursion on ot!er issues=
int $ainGHP
int c
ifG G c F cin.(etGH H QF +O#HP
$ainG H
cout AA c
R
-
8/20/2019 Let us c++.pdf
19/107
return 4R
♦ V
-
8/20/2019 Let us c++.pdf
20/107
return 4
R
void isearc! Gint nu$er> int \ location> int array E> int fro$>
int toHP @@ ZZZZZZZZZZ Base Case ZZZZZZZZZZZZ
int $iddle F Gfro$ I toH @ 2
ifGarray$iddleE FF nu$erHP
location F $iddlereturn
R
ifG G nu$er array toEH ]] G nu$er A array fro$E H HP
location F 1
returnR
ifG$iddle FF fro$H
ifGarraytoE FF nu$erH
P location F toreturn
Relse
Plocation F 1
return
R
@@ ZZZZZZZZZZ ecursion ZZZZZZZZZZZZZ
ifG nu$er array $iddleEHisearc! Gnu$er> location> array> $iddle> toH
else
isearc! Gnu$er> location> array> fro$> $iddleH
returnR
1.2 1.2 0ecursion E5ercise 2 6 7oers of 8anoi
-
8/20/2019 Let us c++.pdf
21/107
include Aiostrea$
void !anoi Gc!ar> c!ar> c!ar> intH
int $ain G H
Pint n F &
!anoi Ga> > c> nHcin n
return 4R
void !anoi Gc!ar fro$> c!ar via> c!ar to> int nH
PifGnFF1H
Pcout AA fro$ AA : F : AA to AA endlreturn
R
n!anoi Gfro$> to> via> nH
cout AA fro$ AA : F : AA to AA endl
!anoi Gvia> fro$> to> nHreturnR
1.21
1.21 !rder of Evaluation on !perands
a F function1 Ga> H I function2 Gc> dH
n CII t!e order of evaluation of t!e two operands eside so$e
operators suc! as :I: is indefinite. f t!e result of t!e calculation
depends on t!e order of evaluation of t!e two operands i. e. t!e
callin( order of t!e two functions it is a lousy desi(n indeed t!en t!e result will e indefinite.
1.22 1.22 Constant aria$le
To put :const: ;ualifier in front of a para$eter in ot! t!e
unction prototype and unction deinition is to tell t!eco$piler t!at t!e function doesnt $odify t!e variale. ' constantvariale or pointer s!ould e initiali8ed w!en declared.
-
8/20/2019 Let us c++.pdf
22/107
1.23 1.23 Principle of #east Privilege -P#P/
T!e principle of least privile(e is to always assi(n least data
accessin( privile(e to t!e pro(ra$. n $ost cases it is ac!ieved yusin( of ;ualifier :const:. :const: is used to pass variales andarrays to functions in w!ic! t!ey s!ould not e $odified. t is also
used to define a local variale t!at s!ouldnt e c!an(ed. 'ny
atte$pt to $odify t!e constant variale will e c!ec6ed out yco$piler efore t!e pro(ra$ is run. sin( t!is principle to properlydesi(n software can (reatly reduce deu((in( ti$e and i$proper
side effects> and can $a6e a pro(ra$ easier to $odify and$aintain.
1.24
1.24 Inline (unctions
0o$e functions are of ;uite s$all si8e> ut ;uite fre;uently called.
Co$pared wit! t!e function call over!ead> t!e pro(ra$ si8ereduced y not repeatedly include t!e loc6 of state$ents $ay etrivial. n t!ese cases we put :inline: ;ualifier in front of t!e
function definition to tell co$piler to insert t!e ody of t!e called
function into t!e callin( function to avoid a call.
all functions t!at call its!ould e reco$piled.
Jeyword inline is specially useful for wrapper classes.
1.2
1.2 0eference
T!ere are two ways to pass ar(u$ents to called functions in $any
lan(ua(es= :callyvalue: and :callyreference:.
♦ V call+-y+value
only a copy of t!e
ar(u$ent is passed to t!e called function. T!e copy constructor oft!e passed o?ect is called to $a6e t!e copy> re;uirin( e,tra
over!ead. T!e ori(inal values are untouc!ed. T!is is (ood for data
security> ut ad for perfor$ance.♦ V call+-y+reerence
' reference is declared y puttin( :\: in front of t!e identifier int!e function !eader. ' reference is not a variale. t is ?ust an
alias of a variale.
it is actually t!e address of one$e$ory cell used to !old different values. n $ac!ine lan(ua(e
we would directly use t!e address to represent t!e variale> ut in
!i(!level lan(ua(es identifiers are used to present addresses. 0o
-
8/20/2019 Let us c++.pdf
23/107
w!en we write
int a F 33
we actually created an alias to represent t!e address of a $e$orycell !oldin( t!e value of 33. it ?ust
converts it to t!e correspondin( address.
T!erefore> w!en we write
int \ F a
we ?ust created anot!er alias for t!at address. Now for t!e sa$eaddress we !ave two alias= 5a and 5. 'lt!ou(! :: is created
:out of: a> ut once created t!ey are e;ual.
T!erefore> w!en a o?ect is passed y reference> a new alias is
created in t!e called function to refer to t!e address of t!at o?ect. H su$Ga> H su$G\a> \H
prototype int su$Ginta> int H
int su$Gint \a>int \H
int su$Gint Z ptr1>int Z "tr2H
#ro$ t!e aove for$ you can see t!at t!e $ost e,plicit e,pression
is callyreference wit! pointer. T!e callin( state$ent of callyreference is t!e sa$e as callyvalue> t!erefore t!e pro(ra$$er
$ay for(et t!at !e is callin( y reference.
-
8/20/2019 Let us c++.pdf
24/107
1.2" 1.2" efault Arguments
proaly of so$e definite values> you can specify t!ese values int!e function prototype. you can o$it t!e para$eters.
void countGint , F 1> int y F 1> int 8 F 1HP...R
int $ain G HP
countGH
count G2> 3H
R
Only t!e ri(!t$ost ar(u$ents can e o$itted you can not
provide t!e 1st and 3rd ar(u$ent and o$it t!e $iddle one.
1.2' 1.2' !verloading (unctions
#unctions wit! t!e sa$e na$e ut different si(nature Gi.e.ar(u$ent listH are called overloaded functions. Overloaded
functions are reco(ni8ed y t!e co$piler t!rou(! t!e ar(u$ent list
in t!e call=
include Aiostrea$
void printGint iHP
cout AA :int i F : AA i AA endl
R
void printGc!ar cH
P
cout AA :c!ar c F : AA c AA endlR
int $ainGHP
int i F 123&
c!ar c F CprintGiHprintGcH
cin i
-
8/20/2019 Let us c++.pdf
25/107
R
1.2) 1.2) E!(
'n inte(er constant defined in t!e :iostream.#: !eader file. t is a
syste$dependent 6eystro6e co$ination. #or e,a$ple> in M0DO0 it is 5Ctrl^> w!ile in NX it is 5CtrlD. n ot!er syste$ it
$ay e 5+O# or even 50top !ereQ. T!e value of +O# in 'N0standard is a ne(ative inte(er value> nor$ally L1. n Borland CII
it is also L1.
1.2, 1.2, Ne #ine
' new line is re(arded as a c!aracter in CII= 5Kn. Uou can usesuc! state$ent to detect a eturn=
ifGc F F KnSH_
-
8/20/2019 Let us c++.pdf
26/107
2.
2. P
-
8/20/2019 Let us c++.pdf
27/107
2." 2." 7&e Integer alue of C&aracter
T!e inte(er value of a c!aracter is its ASC"" code> for e,a$ple>
7 for aS> for S> for cS>... To ac;uire t!is value> usevariale type convertin( operator 5staticWcast A =
include Aiostrea$
include Aiostrea$int $ain GHP c!ar 6eyoard
int adoP cout AA :+nter one c!aracter> and will tell you its '0C=
Kn Kn:
cin 6eyoardcout AA Ga F staticWcast Aint G6eyoardHH AA endl AA:Kn
Kn Kn Kn:
Rw!ile Ga QF 141 \\ a QF -Hreturn 4
R
2.' 2.' #ogic !perators
\\= 'ND
]]= OQ= /o(ic Ne(ation> turnin( t!e value of a lo(ic e,pression fro$ trueto false or fro$ false to true.
-
8/20/2019 Let us c++.pdf
28/107
3.
3. CO6T t!e value of w!ic! is c!osen fro$ two options>dependin( on t!e value of t!e condition e,pression=
condition e,pression ` option 1 = option 2
+,a$ple=
cout AA G (rade F -4 ` 5"assedQ Kn = 5#ailedQ KnH
(rade F -4 ` cout AA 5"assedQ Kn = cout AA 5#ailedQ Kn
3. 3. &ile
w!ile G condition e,pression H state$ent
-
8/20/2019 Let us c++.pdf
29/107
f t!e condition e,pression is true t!e state$ent will e
perfor$ed> and t!e condition e,pression c!ec6ed a(ain. f t!ere isno action in t!e state$ent to cause t!e condition e,pression to
eco$e false eventually> it will cause a 5infinite loop.
5w!ile structure actually is an 5if structure wit! a 5(o to
state$ent at t!e end to (o ac6 to 5if.
3." 3." for #oop
forGe,pression 1 e,pression 2 e,pression 3H
state$ent
e,pression 1= initiali8e t!e loopSs control variale
e,pression 2= loopcontinuation condition
e,pression 3= incre$ent t!e control variale.
's a co$plete loop> first t!e condition is c!ec6ed> if satisfied> t!e
state$ent is e,ecuted> t!en t!e control variale is incre$ented.
+,a$ple=
forG int n F 1> $ F 1> counter F 1 counter AF14 counter F
counter I2Hcout AA counter AA endl
Notice t!at after t!e loop t!e variale 5counter will !ave a valueof 12.
+,pression 1 and 3 can e lists of co$$aseparated e,pressions.T!e co$$a used !ere are 5co$$a operators. T!e value of t!e
list is t!e value of t!e last e,pression. t is usale w!en you need$ore t!an one local variale in t!e loop. (y initialiDin t#ese
varia-les inside t#e loop instead o outside t#e loop itma;es t#e proram clearer and also conorms ?it# t#e
Principle o east Privilee )PP*.
f e,pression 1 is $issin( fro$ t!e 5for !eader ut it !as eeninitiali8ed efore t!e loop> t!e value will e used. f e,pression 2 is
$issin(> t!e continuation condition will e y default true and t!e
loop will run infinitely. f t!e control variale is incre$ented in t!e
loop ody> t!en e,pression 3 can e saved. 'nyway t!e colon cannot e saved.
Many pro(ra$$ers prefer e,pression 3 to e 5counter II>ecause incre$ent occurs only after t!e loop ody is e,ecuted.
-
8/20/2019 Let us c++.pdf
30/107
3.' 3.' Avoid 9odif%ing t&e Control aria$le in t&e #oop
*od%
t is not a error ut it can produce une,pected results.
3.) 3.) sitc&
switc! Gcontrollin( e,pressionHP
case a=case =
state$entsrea6
case c=
state$entsrea6default=
state$entsR
a> > c are called 5case laels. T!ey can only e a constant> or a
c!aracter represented y aS or 'S. t!e case laels are one y one co$pared wit! t!e
controllin( e,pression. allt!e state$ents after t!at case lael will e e,ecuted> until $eetin(
one 5rea6 state$ent. 0o puttin( different laels to(et!er si$ply$eans 5O.
f a 5default= lael is put> w!en no case lael is $atc!ed> t!estate$ents after t!e 5default= lael is e,ecuted. t is not a $ustut a (ood practice to always put a 5default lael even if you are
asolutely sure your pro(ra$ is free of u(s.
' 5rea6 state$ent is not re;uired after t!e 5default case if it isat t!e last.
3., 3., do;&ile
do
P state$ent1state$ent2
Rw!ile Gcontinuation state$entH
T!e only difference etween t!is and 5w!ile state$ent is t!at t!econtinuation condition is c!ec6ed after t!e ody !ad e e,ecuted.
include Aiostrea$
-
8/20/2019 Let us c++.pdf
31/107
int $ain GHP c!ar 6eyoard
int ado
Pcout AA :+nter one c!aracter> and will tell you its '0C=
Kn Kn:cin 6eyoard
cout AA Ga F staticWcast Aint G6eyoardHH AA endl AA:KnKn Kn Kn:
Rw!ile Ga QF 141 \\ a QF -Hreturn 4 R
f we use 5w!ile we !ave to add one state$ent efore t!e loop= 5aF4.
3.1 3.1 5doE?#ile or 5s?itc#> 5-rea;
state$ent causes i$$ediate e,it fro$ t!e state$ent> w!ile
5continue s6ips t!e state$ents after it until t!e end of loop> ande(ins as nor$al t!e ne,t loop.
Notice t!at rea6 can only e,it one layer of loop. f t!ere are $ore
t!an one layers of nested control structure> rea6 can not e,it allof t!e$=
int $ainGHP
fstrea$ file1G:test.t,t:> ios==outH
int i> ?
for Gi F 4 i A 14 iIIHP
file1 AA :Outer loop= i F : AA i AA endl
for G? F 4 ? A 14 ?IIH
Pfile AA :nner loop= ? F : AA ? AA endlifGi FF 3 \\ ? FF 3H -rea;
R
file1 AA endlR
-
8/20/2019 Let us c++.pdf
32/107
file1.closeGH
cin iR
n t!is case> a unstructured pro(ra$$in( tec!ni;ue oto can eused.
-
8/20/2019 Let us c++.pdf
33/107
4.
4. A y> student)E F P4> 1> &> > 1-R
T!e nu$ers in PR are called initialiDers. f t!e nu$er of
initiali8ers are less t!an t!e nu$er of t!e array ele$ents> t!e
re$ainin( ele$ents are auto$atically initiali8ed to 8ero. T!ere$ust e at least one initiali8er in t!e PR. (ut suc# ;ind o
e/pression can only -e used in declaration. ou canFt use 9G% 1..H : in assinment.
4.2
4.2 Arra% Si>e 9ust *e Constant
nstead of directly placin( a fi(ure suc! as :21: in t!e races of
t!e array declaration> it is etter to place a constant variale. nsuc! way w!en you need t!e c!an(e t!e array si8e you only need
to c!an(e one place.
const int si8e F 21
T!e ot!er reason is to avoid 5maic num-er= if nu$er 21
fre;uently appears in t!e pro(ra$> and an ot!er irrelevant 521!appens to appear> it will $islead t!e reader t!at t!is 521 !as
so$et!in( to do wit! t!e for$er one.
Only constant varia-le can -e used as array siDe. T!ereforeyou can not $a6e t!e array si8e dyna$ic y inputtin( an inte(er
fro$ 6eyoard in run ti$e and use it as array si8e.
4.3 4.3 Arra% Si>e
n ava> an array is an o?ect wit! an array wit! fi,edsi8e> plusdata $e$er G:len(t!:H indicatin( t!e array si8e> and co$pilin(
ti$e oundary c!ec6in(. But in CII an array is ?ust an address oft!e first array ele$ent. Declarin( t!e si8e of t!e array can only
!elp co$piler to allocate $e$ory for t!e array> ut t!e co$piler
never c!ec6s w!et!er t!e array ound or si8e is e,ceeded=
int $ain GHP
int > a3E F P4>1>2R
a3EF3
cout AA :a3E F : AA a3E AAendl
-
8/20/2019 Let us c++.pdf
34/107
a&EF&
cout AA :a&E F : AA a&E AAendlcin
R
T!e prole$ t!at will !appen if you e,ceed t!e array ound is=
ecause t!e co$piler was told t!at t!e array was only of 3
ele$ents> so it $ay !ave put ot!er variales in t!e succeedin($e$ory locations. T!erefore y declarin( an array of 3 ele$entst!en puttin( a value into t!e &t! ele$ent> you $ay !ave
overwritten anot!er variales and produced very serious lo(icerrors w!ic! is very difficult to find out.
T!erefore> t!e si8e of an array s!ould e carefully oserved.
4.4
4.4 Arra% and Pointer
T!ere are two widely used for$ats to represent a loc6 of data= apointer and an array=
c!ar Z c"trc!ar uf4E
T!e na$e of an array is a constant pointer to t!e first ele$ent of
t!e array. T!erefore> t!e na$e of a c!arcter array is e;ual to
const c#ar I. Uou can not assi(n ant!er address to t!e array
na$e li6e
uf F c"tr
T!e ot!er difference etween a pointer and array is= a pointersuc! as c#ar I cPtr can point to anyw!ere> $ost proaly
so$ew!ere in t!e O0s territory t!at you cant access. 'n array
suc! as c#ar -uJ8%K !owever> points to a loc6 of $e$oryallocated y t!e co$piler.
f a loc6 of c!aracters ends wit! 6 i.e. 4> it can e treated asa strin(> w!ic! is reco(ni8ed in $ost applications.
♦ V Bou-le+,uoted constant strin
' doule;uote enclosed strin( represents a const c#ar const I
pointin( to so$e co$pilerallocated space !oldin( t!e strin(> wit!
t!e last c!aracter ein( 6. T!erefore> w!en you say
c!ar Z c"tr
c"tr F :9ello worldQ:
Co$piler will allocate a continuous 13 ytes Glast yte to !old
-
8/20/2019 Let us c++.pdf
35/107
N// or 4H so$e w!ere> set t!e$ to e :9ello worldQ:> and assi(n
its address to pointer cPtr. Because t!e ytes are constant> youcan never a$end t!e content of t!e strin(.
T!erefore> if you want to a$end t!e content of :9ello worldQ:> youcan not directly assi(n its address to a pointer. Uou !ave to copy
t!e constant ytes into a c!aracter array=
c!ar str144EstrcpyGstr> :9ello worldQ:H
c!ar Z sustr F strstrGstr> :world:H$e$cpyGsustr> : 1H$s(GstrH
T!e output will e
9ello
-
8/20/2019 Let us c++.pdf
36/107
sprintfGuf> ::H
To write into a c!ar array=
sprintfGuf> :%s> %.-d> %c> %.3f> 4,%.,:>:9ello 123&> '> 123.&> 4,aaH
T!e output will e=
9ello 44123&> '> 123.&44> 4,44aa
#or a list of all for$at specifications> searc! M0DN wit! title
:#or$at 0pecification #ields= printf and wprintf #unctions:.
4.
4. Pass Arra% to (unction
int calculate Gint $e$erJK> int si8eH
Pint i> avera(e F 4
forG i F 4 i A si8e iIIHavera(e IF $e$er iE
avera(e @F si8e
return avera(e
R
int $ain G H
Pint avera(e> student )E F P-7> 3> > > 7&Ravera(e F calculate Gstudent> )H
cout AA :T!e avera(e score is : AA avera(e AA endl
cin avera(ereturn 4
R
To indicate to t!e co$piler t!at a function is e,pectin( an array>t!ere $ust e 5 E followin( t!e array na$e in ot! t!e functionprototype and function definition.
CII auto$atically passes arrays y reference. Dereferencin(
operator 5\ is not used> ecause t!e na$e of t!e array is t!eaddress of t!e first array ele$ent t!e na$e of array :student: is
e;ual to :\student4E:.
4." 4." Searc&ing Arra%
T!ere are two ways to searc! for a fi(ure in an array=
-
8/20/2019 Let us c++.pdf
37/107
inear searc!= co$pare eac! array ele$ent one y one wit! t!e
searc!ed fi(ure until it is found or reac!in( t!e end of t!e array.'vera(e co$parison ti$e= !alf of t!e array si8e.
(inary searc!= can only e applied on sorted array. By c!ec6in(t!e $iddle ele$ent you will find out w!ic! !alf of t!e array
contains t!e ele$ent. Ma,i$u$ co$parison ti$e= lo( n arraysi8e. f
an array needs to e searc!ed fre;uently> t!en it is wort!w!ile tospend a (reat ti$e to sort it first. efer to t!e pro(ra$ in 53.11+,ercise L Binary 0earc! of an 'rray.
4.' 4.' 9ultiple;Su$scripted Arra%
include Aiostrea$
void print Gint E 3E> int> intH
int $ain G HP
int ,
int array1 2E 3E F P P1> 2> 3R> P&> )> -RR
int array2 2E 3E F P1> 2> 3> &R
print Garray1> 2> 3Hprint Garray2> 2> 3H
cin ,return 4
R
void print Gint a E 3E> int first> int secondHP
forGint i F 4 i A first iIIHP
forGint ? F 4 ? A second ?IIH
cout AA a iE ?E
cout AA endlR
returnR
♦ V Beclaration o t#e dimensions
eac! di$ension of t!earray s!ould e declared in ot! t!e function prototype and
function definition. T!e first di$ension does not need a nu$er>
-
8/20/2019 Let us c++.pdf
38/107
?ust li6e sin(ledi$ension arrays> ut t!e suse;uent di$ensions
does.
'n n , 3 array is located in t!e $e$ory in suc! a se;uence= G4> 4HG4> 1H G4> 2H G1> 4H G1> 1H G1> 2H... f t!e co$piler 6nows t!enu$er of colu$ns w!ic! is 3> it will put t!e fist ele$ent G4> 4H of
first row on t!e first $e$ory location> t!e first ele$ent on second
row on t!e fourt! $e$ory location> t!e first ele$ent on t!ird rowon t!e 7t! location>...
-
8/20/2019 Let us c++.pdf
39/107
5.
5. PO"6T> Zy"tr1 F N//> Z;ty"tr1 F \;tyfloat 8> Z8"tr1
8"tr1 F \8
"ointer variale ,"tr1> y"tr1> 8"tr1 and ;ty"tr1 are variales
containin( t!e addresses of anot!er nor$al variales. 5 I
indicates t!at t!e followin( variale is a pointer. 5 int I indicates
t!at t!e followin( variale is a pointer pointin( to an inte(er. function prototype or function
definition> 5Z is not a dereferencin( operator.
:N//: is defined as 4 in Aiostream and several standard
lirary !eader files. ' pointer wit! a value of 4 points to now!ere.
.2
.2 Casting *eteen Numeric Address and Pointer
Uou can ac;uire t!e nu$eric address contained in a pointer and
vice versa t!rou(! castin( etween t!e inte(er type and t!epointer type=
typedef unsi(ned lon( D
-
8/20/2019 Let us c++.pdf
40/107
cout AA 5Offset of $Wa3 is 5 AA GD 123> 144H'ny Z p'ny2 F )Any I*)d?(ase ' 2%%* @@ castin(
D and t!e pointer itself can
also e a constant. f a pointer is a constant pointer> it s!ould e
initiali8ed w!en declared> and it can not e pointed to any ot!ervariale.
0uppose p1 is a pointer pointin( to a 5"erson o?ect. T!ere are
t!ree 6inds of use of 5const=printG"erson Z const p1H pointer is constant ut o?ect is not.
printGconst "erson Z p1H o?ect is constant ut pointer is not
printGconst "erson Z const p1H ot! t!e o?ect and t!e pointer
are constant
.4 .4 Pass Pointer *% 0eference
f we want to pass a pointer to a function and $odify t!at pointer
in t!e function> we can not say
Type Z ptr F new Type
TestGptrH
void TestGType Z ptr4HP...R
Because t!e pointer is passed y value> and t!e ori(inal pointer:ptr: will 6eep unc!an(ed even if you c!an(e t!e :ptr4: in t!e
function. Uou !ave to pass t!e pointer y reference=
-
8/20/2019 Let us c++.pdf
41/107
TestG\ptrH
void TestGType II ptr4H
PGZptr4H F \,
...R
n t!is way you can use 5 )Iptr%* to access t!e ori(inal pointer:ptr:.
. . 0eceive arra% it& pointer
t!e na$e
of array is an address of t!e first ele$ent. Because of t!is> apointer can e used in t!e called function to receive t!e array.
T!en y $ovin( t!e pointer Ge. (. pointer IIH> all t!e rest arrayele$ent can e accessed.
."
." Pointer E5pressions and Arit&metic
T!ere are t!ree 6inds of arit!$etic operations t!at can e done to
a pointer=
♦ V "ncrement
pointer II @
pointer IF @ F 3
"t means movin t#e pointer to t#e ne/t or previous 3rd
element not Must increase t#e value o t#e pointer -y 3. ft!e si8e of t!e variale to w!ic! t!e pointer is pointin( to is &>
t!en actually t!e value of t!e pointer will e increased y 3 , &.
♦ V Bierence
int , F pointer2 L pointer1
f pointer1 is pointin( to t!e )t! ele$ent and pointer2 t!e t!>
t!en , will e 3> not 3,& Gsuppose t!e type si8e is &H.♦ V Assinment
pointer1 F pointer2
pointer1 and pointer2 $ust e of t!e sa$e type> ot!erwise a castoperator $ust e used to convert t!e type of t!e pointer. T!e only
e,ception is w!en pointer1 is declared to e type 5void Gi.e.>
void IH. 'ny type of pointer can e assi(ned to a pointer to voidwit!out castin(. 9owever> it can not e conversed.
-
8/20/2019 Let us c++.pdf
42/107
♦ V Comparison
T!e two pointers for co$parison $ust e pointin( to t!e sa$e
array. T!e result $ay s!ow w!ic! one is pointer to a !i(!ernu$ered ele$ent.
"ointer arit!$etic Gincludin( incre$ent and differenceH is$eanin(less unless perfor$ed on one array> ecause we are onlysure t!at array ele$ents are located one after anot!er.
-
8/20/2019 Let us c++.pdf
43/107
c!ar Z a1 F :4123&)-7:
int a214E F P4> 1> 2> 3> &> )> -> 7> > Rc!ar Z ptr1 F \a13E
int Z ptr2 F \a23Ecout AA :ptr14E F : AA ptr14E AA :> ptr1-E F : AA
ptr1-E AA endlcout AA :ptr24E F : AA ptr24E AA :> ptr2-E F : AA
ptr2-E AA endlcout AA :Kn "ress any 6ey to ;uit...: AA endl
(etc!GHR
Output result=
ptr14E F 3>ptr1-E F ptr24E F 3>
ptr2-E F
.) .) ?si>eof? !perator
CII provides unary operator :siDeo : to deter$ine t!e nu$er ofytes occupied y an array> variale> constant or type na$e suc!
as :int:> :c!ar:> etc. :G H: is needed=
int a> > nfloat ,> array 3E
a F si8eof , F si8eof array
n F si8eof array @ si8eof GfloatH
T!e last state$ent is to find t!e nu$er of ele$ents of an array.
Notice t!at t!e nu$er of ytes for a certain type is different fordifferent syste$s. CII is platfor$dependent> not li6e ava.
., ., Si>e of String and C&aracter Arra%
'lt!ou(! a strin( 5c!ar Z and a c!aracter array 5c!ar E can eused in t!e sa$e way in $ost cases> w!en it co$es to si8e issue>
t!ey are different. T!e si8e of t!e 5c!ar Z is t!e si8e of t!e c!arpointer> w!ile t!e si8e of t!e c!ar array is t!e si8e of t!e array=
c!ar Z te$p1 F :acdef(:c!ar te$p224E F :acdef(:c!ar te$p334E F :acdef(:
cout AA :0i8e of a c!ar Z is : AA si8eof te$p1
-
8/20/2019 Let us c++.pdf
44/107
AA :> si8e of c!ar24E is : AA si8eof te$p2
AA :> si8e of c!ar34E is : AA si8eof te$p3 AA endl
Output will e=
0i8e of a c!ar Z is &> si8e of c!ar24E is 24> si8e of c!ar34E is
34
.1 .1 (unction Pointer and Call *ac+ 7ec&nique
#unction pointers are $ainly used to ac!ieve call ac6 tec!ni;ue>w!ic! will e discussed ri(!t after.
ust li6e an array na$e is t!e address of t!e first array ele$ent> afunction na$e is a actually t!e startin( address of t!e function
code. ' function pointer !olds t!e address of a function> ?ust li6e afloat pointer !olds t!e address of a float variale. ' function
pointer can point to eit!er a (loal function or a class function.
♦ V lo-al unction pointer
include :stdaf,.!:
typede void)ICA(ACN&6CT"O6*)int* @@ define t!e
function pointer
void (ar;)int n
-
8/20/2019 Let us c++.pdf
45/107
int $ainGint ar(c> c!arZ ar(vEH
PServerG=(ar;> 2H @@ passin( function pointer
ServerG=Cry> 3Hreturn 4
R
Bar6QBar6Q
-
8/20/2019 Let us c++.pdf
46/107
P
forGint i F 4 i A nepeat iIIHprintfG:0sssQKn:H
return $Wna$eR
private=
c!ar Z $Wna$eR
void ServerGCreature I pCreature CA(ACN>TOB m>int nepeatH
Pc!ar Z na$e F )pCreature+Im*)n :My na$e is %sQKnKn:> na$eH
printfGufHR
int $ainGint ar(c> c!arZ ar(vEH
P
Cat I pCat F new CatG:essy:HSna;e I pSna;e F new 0na6eG:o!n:H0erverGpCat> )CA(ACN>TOB*=Catiao> 2H @@
passin( function pointer0erverGpSna;e> )CA(ACN>TOB*=Sna;eSsss> 3H
return 4R
MiaoQMiaoQMy na$e is essyQ
0sssQ0sssQ
0sssQMy na$e is o!nQ
♦ V Call (ac; Tec#ni,ue
Callac6 tec!ni;ue is an effort to seperate 5w!at fro$ 5!ow.
you $ay find t!at at a certian point in your pro(ra$> you
-
8/20/2019 Let us c++.pdf
47/107
need to invo6e a function w!ic! !as t!e sa$e si(nature ut
different i$ple$entation for different use cases. n ot!er words>for every specific case> t!e type of infor$ation passed to and
returned y t!at function Gw!ic! represents 5w!atH is t!e sa$e>ut t!e i$ple$entation of t!e function Gw!ic! represents 5!owH is
different. Different client Gw!o uses your pro(ra$H $ay !avedifferent i$ple$entations.
n t!is case> you !ave to provide a $ec!anis$ so t!at t!e client$ay re(ister !is own version of t!at function to your pro(ra$
efore t!e invo6in( point> so t!at your pro(ra$ 6nows w!ic! oneto call. T!is tec!ni;ue is called 5callac6.
T!ere are t!ree ways to ac!ieve callac6.
T!e OO approac! of callac6 is to let t!e client class in!erit fro$and i$ple$ent an interface. n your code you si$ply !old aninterface pointer and call t!e interface $et!ods t!rou(! t!at
pointer. T!e client pro(ra$ will create !is i$ple$entation o?ect>assi(n its pointer to t!e interface pointer in your class efore t!ecallin( pointer in your class is reac!ed.
9owever> if t!e client class is already finis!ed and did noti$ple$ent t!e interface you want> you !ave to use a less OO
approac!. T!e client pro(ra$$er Gor your do it for !i$H s!ouldwrite a separate $atc!in( class for t!e client class> w!ic! in!erit
fro$ t!e desired interface wit! t!e function you will call ac6>w!ic! provides t!e service you need y $anipulatin( clientclass
o?ects. n your code you !ave a pointer to t!e interface andinvo6e t!e service provided y t!e separate class.
T!e least OO approac! is to use function pointers li6e t!e aove
e,a$ple.
.11 .11 Arra% of (unction Pointer and 9enu;rivenS%stem
One use of function pointers is in $enudriven syste$s. T!e user
is pro$pted to select an option fro$ a $enu Ge.(.> 1[)H. +ac!
option is severed y a different function. "ointers to different
functions is stored in an array of function pointers. T!e userSsc!oice is used as a suscript of t!e array.
int fun1GH
int fun2GH
int fun3GHint fun&GHint fun)GH
-
8/20/2019 Let us c++.pdf
48/107
int $ainGHP
c!ar GZfun"tr3EHGintH F Pfun1> fun2> fun3Rint c!oice F 4
w!ileGc!oice QF 1H
PGZfun"trc!oiceEHGH
c!in c!oiceR
R
T!e li$itation t!is application is t!at all t!e functions s!ould !ave
t!e sa$e si(nature and return type.
.12
.12 Poer and (le5i$ilit% of Pointers
"ointers in CII is a very powerful tool. t is e,tre$ely fle,ile and
t!erefore can (enerate every 6ind of errors if $isused.
#or e,a$ple> you can only cast an o?ect of a suclass to its
superclass. No ot!er castin( etween userdefined classes isallowed. 9owever> pointers to different classes can e cast to eac!
ot!er wit!out any restrict.
t!e address. 0o you can cast a pointer to an inte(er to a+$ployeeclass pointer. T!en t!e +$ployee pointer will ?ustassu$e t!at startin( fro$ t!e passed address it can find all
attriutes of +$ployee class.
class "erson P
pulic=
"ersonGc!ar Z F 4> int F 4> ool F true> c!ar F Hvoid printGH constvoid doNot!in(GH
private=
c#ar I na$eint a(e
-ool (endac#ar lood
R
"erson=="ersonGc!ar Z n> int a> ool (> c!ar H= na$eGnH> a(eGaH> (endaG(H> loodGH PR
void "erson==printGH const
-
8/20/2019 Let us c++.pdf
49/107
P
cout AA na$e AA : : AA a(e AA : : AA (enda AA : :AA lood AA endl
R
void "erson==doNot!in(GH PR
class +$ployee P
pulic=+$ployeeGc!ar Z F 4> int F 4> ool F true> c!ar Z F 4H
void displayGHprivate=
c#ar I e$pNa$eint e$p'(e
-ool e$pYendac#ar Z e$pTitle
R
+$ployee==+$ployeeGc!ar Z n> int a> ool (> c!ar Z tH
= e$pNa$eGnH> e$p'(eGaH> e$pYendaG(H> e$pTitleGtH PR
void +$ployee==displayGH
P cout AA e$pNa$e AA : : AA e$p'(e AA : : AAe$pYenda
AA : : AA e$pTitle AA endlR
int $ainGint ar(c> c!arZ ar(vEH
PDerived d1G123&> )-7HDerived d2Gd1H
d2.printGHcout AA endl
"erson p1G:#ran6:> 3&> true> OH+$ployee e1G:#ran6:> 3&> true> :+n(ineer:H
"erson Z p2 F )Person I*\e1
+$ployee Z e2 F )>mployee I*\p1
cout AA :p1 F :
-
8/20/2019 Let us c++.pdf
50/107
p1.printGH
cout AA :p2 F G"erson ZH\e1 F :p2printGH
cout AA :Kne1 F :
e1.displayGHcout AA :e2 F G+$ployee ZH\p1 F :
e2displayGH
return 4R
Output will e=
p1 F #ran6 3& 1p2 F G"erson ZH\e1 F #ran6 3& 1
e1 F #ran6 3& 1 +n(ineere2 F G+$ployee ZH\p1 F #ran6 3& 1 `b
-
8/20/2019 Let us c++.pdf
51/107
!.
!. CASS
".1
".1 Class
p to t!is sta(e weve een $ainly tal6in( aout issues w!ic! are
co$$on to ot! procedural Gsuc! as CH and OO lan(ua(es. #ro$now on we will tal6 $ore aout OO issues.
's a class> it co$ined t!e data attriutes and t!e e!avior
attriutes of an o?ect to(et!er> and for$ed an o?ect w!ic! can
si$ulate ot! aspects of a realworld o?ect.
To distin(uis! independent functions suc! as t!ose strin( !andlin(
functions in :strin.#: and functions w!ic! elon( to a class> class
$e$er functions are t!ereinafter called :$et!ods:.
T!e pu-lic and private laels are called mem-er access
speciiers. 'll data $e$ers and $et!ods declared y t!e
:pu-lic: specifier are accessile fro$ outside> and all declared y:private: are only accessile for $et!ods.
'ctually an o?ect contains only t!e data $e$ers. Met!ods do
not elon( to any specific o?ect. T!e elon( to t!e class. 'llo?ects s!are one copy of $et!ods.
operator on a class or an o?ect you will only (et t!e total si8e oft!e data $e$ers.
".2 ".2 9et&ods of a Class
f t!e $et!od is defined inside t!e class ody> it is auto$atically
inlined. t $ay i$prove t!e perfor$ance> ut it is not (ood forinfor$ation !idin(> ecause t!e client of t!e o?ect is ale to :see:
t!e i$ple$entation of its $et!ods. f a $et!od is defined outsidet!e class ody> you !ave to use 6eyword :inline: if you want it to
e inlined. Only t!e si$plest $et!ods can e defined inside t!e
class ody.
To define t!e $et!od outside t!e class ody> you !ave to usescope resolution operator > w!ic! we !ave used efore to
access (loal variales> w!en a local variale wit! t!e sa$e na$e
!ad een declared. se :class na$e==: in front of t!e $et!oddefinition to $a6e it uni;ue> ecause ot!er classes $ay !ave
$et!ods of t!e sa$e na$e.
Met!ods w!ic! c!an(es t!e data $e$ers are so$eti$es called:commands:> and $et!ods w!ic! do not c!an(e are called
:,ueries:. 0eparatin( t!e co$$ands and ;ueries leads to
si$pler> $ore fle,ile and easyunderstandin( interfaces.
-
8/20/2019 Let us c++.pdf
52/107
♦ V Call a met#od
To call a $et!od> use t!e o?ect na$e plus :.: plus t!e $et!od
na$e> or a pointer to t!at o?ect plus 5+ plus t!e $et!od na$e.
".3 ".3 Constructor
T!ere is a special $et!od wit! t!e sa$e na$e as t!e class called
constructor. T!ere is no return type Geven not voidH for t!isspecial $et!od.
0uppose 5Test is a class> t!e followin( line
Test t1G3)> 5#ran6H
creates a Test o?ect in co$pile ti$e> assi(nin( its address to 5t1.
Test Z ptr F new TestG3)> 5#ran6H
:new: is a special $et!od w!ic! creates a Test o?ect dyna$ically
at run ti$e and returns a pointer to t!at new o?ect. T!e returnedpointer is received y 5ptr. T!e followin( lines
int calculateGTest \H @@ #unction prototype
calculateG TestG3)> 5#ran6H H
Test Z ptr F \TestG3)> 5#ran6H
create a Test o?ect in co$pile ti$e> ut do not assi(n a na$e>
instead point a pointer or reference to it.
Default ar(u$ents are reco$$ended for constructors so t!at even
if no ar(u$ents are passed to t!e o?ect t!e data $e$ers canstill e initiali8ed to a consistent state. 0T/ containers re;uires
t!e o?ects to !ave default constructors.
Constructor can e overloaded. Nor$ally t!ree 6inds of
constructors are needed=
1.
1. Default constructor= no ar(u$ents2.
2. Constructor= !as all ar(u$ents to construct an uni;ue
o?ect
3. 3. Copy constructor= !as an ar(u$ent its own type> to
copy a new o?ect out of it.
T!e default constructor and nor$al constructor can e $er(edinto one if t!e nor$al constructor uses default ar(u$ents.
f no constructor is provided> t!e co$piler auto$atically insert a
default constructor. T!is default constructor does not perfor$ any
-
8/20/2019 Let us c++.pdf
53/107
operation. 0o t!e data $e$ers of t!e o?ect $ay not e
consistent.
Builtin types are not initiali8ed w!en created.
♦
V ser+deined Converters
0uppose a $et!od !as an ar(u$ent of type :C!ild:> w!ic! !as an
onear(u$ent constructor :C!ildG"arentH:. if you pass a :"arent: o?ect instead of :C!ild:> t!e
co$piler will i$plicitly call t!e onear(u$ent constructor andconvert t!e :"arent: o?ect to :C!ild:.
class Base P
pulic=
BaseGint aH = $e$erGaHP
cout AA :Base constructor called wit! : AA a AA endl
Rprivate=
int $e$er
R
void testG(ase o-M1HP
cout AA :Base o?ects $e$er F : AA o?1.$e$erR
int $ainGH
PtestG333H
R
T!e output will e=
Base constructor called wit! 333
Base o?ects $e$er F 333Onear(u$ent constructors are called userdefined converters.
".4 ".4 efault Construcotr
Default constructor is called i$plicitly w!en you create an array ofo?ects. f you want to !ave an array of o?ects t!at do not !ave a
default constructor> t!e wor6around is to !ave an array of
pointers and initiali8e t!e$ usin( operator ne?.
-
8/20/2019 Let us c++.pdf
54/107
". ". Cop% Constructor
' copy constructor is not only e,plicitly called y t!e pro(ra$$er
to create new o?ects y copyin( an e,istin( o?ect> it is alsoi$plicitly called y t!e co$piler to $a6e a copy of an o?ect w!enit is passed y value. f copy constructor is not provided> co$piler
will provide a default copy constructor> w!ic! $a6es default
$e$erwise copy> w!ic! can not deal wit! o?ects wit! pointer$e$ers.
T!ere are two rules for t!e para$eter of copy constructor=
1. 1. Copy constructorSs ar(u$ent can not e passed yvalue. Ot!erwise t!e copy constructor call results in infinite
recursion> ecause for callyvalue> a copy of t!e o?ect
passed to t!e copy constructor $ust e $ade> w!ic! results int!e copy constructor ein( called recursively.
2. 2. T!e o?ect ar(u$ent passed to t!e copy constructor$ust e constant. Ot!erwise it can not e applied on constant
o?ect.
"." "." Accessing Class 9em$ers
' classSs data $e$ers and $et!ods !ave class scope.ndependent functions !ave file scope.
Data $e$ers and $et!ods are directly accessile y ot!er$et!ods of t!e sa$e class. "ro(ra$s outside a class can only
access a classSs pulic $e$ers t!rou(! one of t!e !andles of ano?ect= o?ect na$e> reference to o?ect> pointer to o?ect.
0o two 6inds of variales $ay appear in a $et!od= local varialeswit! loc6 scope w!ic! is destroyed after t!e call> and data
$e$ers.
"ulic $e$ers of a class is desi(ned to e an interface for its
clients. t is reco$$ended to 6eep all t!e data $e$ers under 5private> and provide for clients pulic $et!ods to set or (et t!eir
values. T!is !elps to !ide i$ple$entation details fro$ t!e clients>reducin( u(s and i$provin( pro(ra$ $odifiaility. t alsosi$plifies t!e deu((in( process ecause prole$s wit! data
$anipulations are locali8ed to eit!er t!e classSs $et!ods or
friends.
"rivate data $e$ers can also e c!an(ed y 5riends of its
class. Because of t!is> t!e use of :friends: is dee$ed y so$e
people to e a violation of infor$ation !idin(.
Bot! structures and classes !ave private> pulic and protected
-
8/20/2019 Let us c++.pdf
55/107
access. Default of classes is private> default for structure is pulic.
".' ".' 7%pical 9et&ods
♦ V Constructors
Discussed efore.
♦
V Access met#ods
To allow outside clients to $odify private data> t!e class s!ould
provide 5set $et!ods. To allow clients to read t!e values of
private data> t!e class s!ould provide so$e 5(et $et!ods. T!ese$et!ods are called 5access $et!ods. T!ey can also translate t!e
data for$at used internally durin( i$ple$entation into t!e for$atfor clients. #or e,a$ple> ti$e $ay e $ost conveniently
e,pressed in seconds Gw!ic! is t!e return type of function 5ti$eG4HH> ut clients $ay very possily want t!e for$at of
54-=34.
♦ V Service met#ods
T!ese $et!ods provide services for clients.
♦ V tility met#ods
T!ey are only called y ot!er $et!ods> and nor$ally are private.
♦
V Bestructors
'uto$atically called w!en an o?ect leave scope to release all
resources !eld y t!e o?ect. T!e na$e of a destructor for a classis t!e tilde G[H c!aracter followed y t!e class na$e.
0tac6 $e$ory resources !eld y t!e o?ect suc! as its co$pilercreated $e$ers are released auto$atically w!en t!e o?ect
leaves scope or e,plicitly deleted. ' destructor is only needed to
release resources w!ic! can not e auto$atically released> suc! as
dyna$ically allocated $e$ory Gusin( :new:H or networ6 ordataase connection.
".)
".) Avoid 0epeating Code
'lways try to avoid repeatin( code if t!ey $ust e 6ept identical.
'lt!ou(! writin( t!e sa$e state$ents a(ain can avoid a $et!od
call and t!us (ood for perfor$ance> it is ad for $aintenance>ecause once t!e pro(ra$ need to e c!an(ed ot! places s!ould
e c!an(ed $eanti$e. +,tra attention s!ould e paid to always6eep t!e$ identical. 0o always use a $et!od call to avoid
repeatin( code.
f you really want to avoid t!e $et!od call> use 5inline ;ualifier
-
8/20/2019 Let us c++.pdf
56/107
in front of t!e $et!od definition.
"., "., @&en Constructors and estructors are Called
#or (loal o?ects> constructors are called efore any ot!er
$et!ods includin( $ain e(ins e,ecution. Destructors are calledw!en $ain ter$inates or 5e,it $et!od is called.
#or auto$atic local o?ects> constructors are called w!ene,ecution reac!es t!e point w!ere t!e o?ects are declared.
Destructors are called w!en t!e o?ects leave scope i.e. t!e loc6in w!ic! t!ey are declared is e,ited.
#or static local o?ects> constructors are called only first ti$e w!ent!e e,ecution reac!es t!e point w!ere t!e o?ects are declared.
Destructors are called w!en $ain ter$inates or 5e,it $et!od iscalled.
t is t!e sa$e in ava.
".1
".1 efault 9em$erise Cop% and efault
9em$erise Assignment
if no copyconstructor is provided> a default $e$erwise copy will !appen.
#or o?ects wit!out dyna$ic $e$ers i.e. pointers> a default$e$erwise copy can do t!e ?o. But for o?ects containin(
pointers to ot!er o?ects> a default $e$erwise copy will onlypoint t!e pointers of t!e two o?ects to t!e sa$e ot!er o?ect.
T!is is called s!allow copy.
anot!er> if no overloaded assi(n$ent operator is provided> adeault mem-er?ise assinment will !appen. t is t!e sa$e
as default $e$erwise copy.
".11 ".11 Pass;$%;value and Cop% Constructor
Bot! in CII and ava> copy constructors are not desi(ned forclonin( o?ects e,plicitly> ecause copy constructor does not
support poly$orp!is$.
n CII> o?ects are y default passed y value> and w!en it!appens> a copy of t!e ar(u$ent o?ect is auto$atically $ade y
t!e co$piler for t!e called $et!od. T!erefore> copy constructor isa $ust for any class w!ic! needs deep copy t!at default$e$erwise copy can not ac!ieve. Copy constructor is t!erefore
(iven i( i$portance and eco$es one of t!e four ele$ents of t!e
OC#= all classes s!ould provide t!eir properly i$ple$ented copy
-
8/20/2019 Let us c++.pdf
57/107
constructors.
n ava> ecause all o?ects are passed y reference and t!e
lan(ua(e even does not support auto$atic passyvalue> t!ere isno need for enforce$ent of copy constructors. #or t!e purpose ofclonin( o?ects> ava provides a $ore roust and auto$ated
facility L t!e clone $ec!anis$.
".12 ".12 Cop% Constructor vs. (actor% 9et&od
' factory $et!od is a $et!od w!ic! uses dyna$ic $e$oryallocation to clone itself and return a pointer to t!e new copy.
0uppose you !ave a astract class 0!ape and a series of derived
concrete classes suc! as Circle> 0;uare> ectan(le> etc. ' factory
$et!od of Circle loo6s li6e
0!ape Z cloneGHP
return new CircleGZt!isH @@ callin( copy constructor
R
Copy constructor can not e used to clone o?ects in case of
poly$orp!is$. T!is is true in ot! CII and ava> ecause copyconstructor does not support poly$orp!is$.
0uppose you !ave a $et!od w!ic! receives a concreteclass
o?ect wit! a 0!ape !andle and do so$et!in( on it. Now if youwant to $a6e a copy of it in t!at $et!od> wit! a factory $et!odyou can say
pulic void $odify'ndDisplayG0!ape Z o?H
P0!ape o?1 F o?. cloneGH
...R
f t!e passed ar(u$ent is a Circle> t!e 0!ape pointer 5o? will (et
a Circle> if itSs 0;uare> you will (et a 0;uare. But if you say
0!ape o?1 F new 0!apeGo?H
ecause copy constructor can only produce and return an o?ect of
its own type> you will only (et a 0!ape o?ect. Uou will lose allinfor$ation of t!e derivedclass part of data.
-
8/20/2019 Let us c++.pdf
58/107
".13 ".13 arious Places to use
$eanti$e. t can not e $odified> and only constant $et!ods canaccess it. Nonconstant $et!ods can not access constant$e$ers> even if t!ey do not $odify t!e o?ects.
Declarin( an o?ect to e constant not only can prevent it fro$ein( $odified> it is also (ood for perfor$ance= todays
sop!isticated opti$i8in( co$pilers can perfor$ certainopti$i8ations on constants> ut can not do it on variales.
♦
V Constant arument o a met#odDeclarin( an ar(u$ent 5const will prevent t!e $et!od to $odify
it. f you return t!is constant ar(u$ent ac6> ut did not declaret!e return type constant> t!e co$piler will co$plain.
♦
V Constant return type o a met#od
t is $eanin(less to declare t!e return type constant if it is return
y value. Declarin( t!e return y reference constant is to prevent
t!e client fro$ accessin( t!e private data $e$er t!rou(! t!ereference. f a $et!od returns one private data $e$er y
reference> t!e client w!o calls t!is $et!od can $odify reversilyt!is $e$er.
#or t!e sa$e reason> if a constant $et!odSs return type is areference to a data $e$er> t!e return type s!ould also e
constant ot!erwise t!e data $e$er
♦ V Constant met#od
' $et!od is declared constant y puttin( :const: after its function!eader. ' constant $et!od can not $odify any data $e$er. t
still can $odify received ar(u$ents and local variales. Only class$et!ods can e declared 5constant> independent functions can
not.
all its non
constant $et!ods are foridden to e called y t!e co$piler. n
t!e followin( e,a$ple> co$piler will pro$pt error on $et!od call:t1.printG H:=
class TestConstant P
pulic=TestConstantG int i F 4H
-
8/20/2019 Let us c++.pdf
59/107
int (etGH const @@ can e called for a constant o?ect
void printGH @@ can not e called for a constant o?ectprivate=
int $e$erR
TestConstant==TestConstantG int iH
P $e$er F R
int TestConstant==(etGH constP return $e$er R
void TestConstant==printGH const
P cout AA :9ello t!e worldQ: R
int $ainGint ar(c> c!arZ ar(vEHP
const TestConstant t1G123&H
cout AA :T!e $e$er is : AA t1.(etGH AA endlcout AA :T!e $essa(e is :
t1.printGHcout AA endl
return 4
RT!erefore> always try to declare as $any $et!ods constant as youcan> especially t!ose $odificationfree $et!ods> so t!at w!en a
client creates a constant o?ect> !e can still call its $odificationfree $et!ods.
Declarin( $odificationfree $et!ods constant co$es wit! anot!erenefit= if you inadvertently $odify t!e o?ect in t!is $et!od> t!e
co$piler can always find it out for you. t can !elp to eli$inate
$any u(s.
f t!e return type of a constant $et!od is a reference to a data$e$er> t!e return type $ust e also e constant> ot!erwise t!eclient can $odify t!e data $e$er t!rou(! t!e reference> w!ic!
s!ouldnSt !appen ecause t!e $et!od is constant.
9owever> t!ere are cases w!en you !ope t!at if t!e o?ect is not
constant> you want to $odify t!e data $e$er t!rou(! t!e returntype> w!ile if t!e o?ect is constant> you still want to read t!e data
$e$er t!rou(! t!e return type. f you only provide a nonconstant $et!od wit! nonconstant return type> it can not e
called for a constant o?ect> w!ile if you only provide a constant
-
8/20/2019 Let us c++.pdf
60/107
$et!od wit! constant return type> it can not $odify t!e data
$e$er. To solve t!is prole$> you can provide a pair ofoverloaded $et!ods=
const int \ (etGH const
P return a R
int \ (etGHP return a R
".14 ".14 9em$er initiali>er
'ssi(n$ent state$ents can not e used in a constructor to
initiali8e constant data $e$ers. Me$er initiali8ers $ust e used
to initiali8e constant data $e$ers. ' list of initiali8ers start wit! a: : after t!e constructor !eader> speparated y :>:. +ac!initiali8er is t!e na$e of t!e data $e$er followed y its value in
rac6ets=
Test==TestGint a> int > int cH= $e$er1GaH> $e$er2GH>
$e$er3GcH
P...R
'll data $e$ers C'N e initiali8ed usin( $e$er initiali8ersynta,> ut t!e followin( t!in(s M0T e initiali8ed wit! $e$er
initiali8ers=
1. 1. constant data $e$ers>
2. 2. references>
3. 3. ase class portions of derived classes.
".1 ".1 9em$er !$ects
' data $e$er of a userdefined type is called a $e$er o?ect.
t!e $e$er o?ects are createdfirst> t!en t!ey are used to construct t!e parent o?ect. T!e order
of t!e creation of $e$er o?ects is decided y t!e order t!ey aredeclared in t!e class definition> not t!e order of t!eir $e$erinitiali8ers.
Me$er o?ects do not !ave to e initiali8ed e,plicitly. f $e$erinitiali8ers are not provided> t!e $e$er o?ectSs defaultconstructor will e called i$plicitly. Not providin( a default
constructor for t!e class of a $e$er o?ect w!en no $e$er
initiali8er is provided for t!at $e$er o?ect is a synta, error.
Me$er o?ects still 6eep t!eir privacy fro$ t!eir owner. Owner
-
8/20/2019 Let us c++.pdf
61/107
classs $et!ods can not directly access t!eir private data
$e$ers. T!ey !ave to access t!e$ t!rou(! t!eir 5(et or 5set$et!ods.
' $e$er o?ects can e auto$atic so$eti$es called 5valuese$antics> or an reference to anot!er o?ect so$eti$es called
5reference se$antics.
Me$er o?ects are also called servers> and owners called clients.
".1" ".1" 9em$er !$ects S&ould *e Initiali>ed it&9em$er Initiali>ers
Co$piler does not force you to initiali8e $e$er o?ects wit!initiali8ers> ut you are stron(ly reco$$ended to do so.
f a $e$er o?ect is initiali8ed in t!e constructor wit! anassi(n$ent operator> its default constructor will e called first>
t!en its assi(n$ent operator. f it is initiali8ed wit! initiali8er> onlyits constructor will e called. t is not only t!e $atter of savin(
one $et!od call> ut also t!e $atter of safety. #or a class wit!out
a properly i$ple$ented default constructor or assi(n$entoperator> usin( assi(n$ent operator to initiali8e it $ay cause
une,pected lo(ic errors suc! as s!allow copy.
class Base P
pulic=BaseGHBaseGconst int iH
const Base \ operator FGconst Base \ 1Hprivate=
int $e$erR
Base==BaseGH
P cout AA :Bases default constructorQ: AA endl R
Base==BaseGconst int iH= $e$erGiHP cout AA :Bases constructorQ: AA endl R
const Base \ Base==operator FGconst Base \ 1H
Pcout AA :Bases assi(n$ent operatorQ: AA endl$e$er F 1.$e$er
return Zt!isR
-
8/20/2019 Let us c++.pdf
62/107
class ser Ppulic=
serGconst Base \ 1Hprivate=
Base $e$erR
ser==serGconst Base \ 1H
Pcout AA :sers constructorQ: AA endl
$e$er F 1R
int $ainGint ar(c> c!arZ ar(vEH
PBase 1G123&Hser u1G1H
return 4R
Output will e=
Bases constructorQ
Bases default constructorQsers constructorQBases assi(n$ent operatorQ
Now if you c!an(e t!e sers constructor to use initiali8er to
initiali8e Base o?ect=
ser==serGconst Base \ 1H = $e$erG1H
P cout AA :sers constructorQ: AA endl R
Output will eco$e=
Bases constructorQsers constructorQ
".1' ".1' (riend
'n independent function can e (ranted t!e privilled(e to access aclasss private $e$ers if t!at class declares t!is function to ea friend of !is. ' function can not declare itself to e a friend of a
class.
To e ale to access a class> t!is independent function s!ould
-
8/20/2019 Let us c++.pdf
63/107
usually receive an ar(u$ent of t!at class> so t!at it can use t!e
passed !andle.
void s!ow"rivacyGconst Need#riends \ n1H constP
cout AA :O?ects private $e$er is : AA n1.$e$er AAendl
R
class Need#riends Priend void s!ow"rivacyGconst Need#riends \ n1H const
pulic=
Need#riendsGint iH
private=int $e$er
R
' $et!od can e friends of different classes. Overloaded $et!odscan e friends of a class.
".1) ".1) t&is pointer
test1G123&H
But w!en we call a $et!od testG H of o?ect o1> we !ave to call
t!rou(! t!is o?ects !andle=
o1.test2G123&H
9owever> internally a $et!od and an independent function are t!e
sa$e for t!e co$piler. iti$plicitly convert it to add one $ore ar(u$ent t!e o?ectt!rou(! w!ic! t!e $et!od is called> so t!at t!e $et!od 6nowsw!ic! o?ect to access. 0o t!e aove $et!od call is i$plicitly
converted to so$et!in( li6e
test2G\o1> 123&H
nside t!e $et!od> t!e passed !andle is represented y pointer
:t#is:. Uou can use it to access t!e o?ect.
#or e,a$ple> if class Test !as t!ree $et!ods $et!od1> $et!od2
-
8/20/2019 Let us c++.pdf
64/107
and $et!od3> t!eir return types are all Test> and t!ey all end wit!
return Zt!is
T!en you can write a line of code li6e
o1.$et!od1GH.$et!od2GH.$et!od3GH
T!is is called cascaded $et!od call.
".1, ".1, 9emor% Allocation and 9anipulation
T!ere are two ways to allocate $e$ory for an o?ect= statically at
co$pile ti$e and dyna$ically at run ti$e.
♦ V Static memory allocation
To allocate $e$ory statically at co$pile ti$e> t!e co$piler $ust6now for sure t!e si8e of t!e o?ect.
int aint 144E
float
+$ployee c
T!e co$piler reads t!e type definition of t!e o?ect Gfor o?ect c itis t!e class definition of class +$ployeeH and 6nows t!e si8e of t!e
o?ect.But if you say
int si8e
cin si8efloat arraysi8eE
Co$piler will !ave no way to 6now !ow $any ytes of $e$ory toallocate for t!e array. T!erefore it will co$plain.
♦
V Bynamic memory allocation
To allocate $e$ory at run ti$e> t!ere are two ways= Cstyle$e$ory allocation usin( malloc and ree> and CII style
allocation usin( ne? and delete.
To use Cstyle $e$ory allocation for an int array of si8e 124=
int Z pnt F Gint ZHmallocG124 Z si8eofGintHH
ifGpnt FF N//HP
cout AA :Me$ory allocation failedQKn:
return
-
8/20/2019 Let us c++.pdf
65/107
R
memsetGpnt> 4> 124H
T!ere is a si(nificant difference etween C and CII style dyna$ic$e$ory allocation. malloc allocates e,actly t!e a$ount of$e$ory t!at you want> and it doesnSt care w!at you are (oin( to
put into t!at loc6 of $e$ory. t is also not responsile for
initiali8in( t!e allocated $e$ory. 0o usually t!ere is a $e$setfunction call after $alloc to initiali8e it e,plicitly.
n co$parison> CIISs operatior new re;uires a type definition
instead of t!e nu$er of ytes you want to allocate. t reads t!etype definition and allocate e,actly t!e a$out of $e$ory needed
to !old t!e o?ect of t!e (iven type> t!en it calls t!e constructor of
t!at type to initiali8e t!e o?ect.T!erefore> malloc is t!e $ost fle,ile way to allocate $e$ory> forit does t!e least t!in( for you and leave you wit! all freedo$. But
it is also errorprone. t is $uc! safer and si$pler to allocate$e$ory for an encapsulated CII o?ect.
Besides> Cstyle function $e$set $ay reac! t!e encapsulation
law. t can directly access private data $e$ers of an o?ect.
♦ V emory de+allocation
To free t!e $e$ory wit! Cstyle code=
reeGpntH
To free t!e $e$ory in CII code=
delete p#loat
'(ain> CIISs delete is $ore convenient to use. t calls t!edestructor of t!e type efore freein( t!e $e$ory.
♦ V Bierence -et?een static allocation and dynamicallocation
T!e over!ead of dyna$ic $e$ory allocation is t!at it ta6esco$puter ti$e to otain $e$ory fro$ t!e O0> and it $ay notalways succeed. 0o for t!e sa6e of perfor$ance> if you can decide
t!e si8e of t!e $e$ory> always allocate $e$ory at co$pile ti$e
usin( declarations.
/ocal o?ects created y declaration is discarded after leavin(
scope> ut o?ects created y dyna$ic $e$ory allocation is not
destroyed after leavin( scope. f not deleted it e,ists until t!e endof run.
-
8/20/2019 Let us c++.pdf
66/107
".2 ".2 Pointer Status after delete
'fter an o?ec