Você está na página 1de 144

History of C++

Published by Juan Soulie


Last update on Jan 18, 2008 at 12:19pm UTC

Durin the !0s, "hile #omputers "ere still in an early sta e o$ de%elopment, many ne" pro rammin lan ua es appeared& 'mon them, 'L()L !0, "as de%eloped as an alternati%e to *)+T+', but ta-in $rom it some #on#epts o$ stru#tured pro rammin "hi#h "ould later inspire most pro#edural lan ua es, su#h as CPL and its su##esors .li-e C//0& 'L()L !8 also dire#tly in$luen#ed the de%elopment o$ data types in C& ,e%ertheless 'L()L "as an non1spe#i$i# lan ua e and its abstra#tion made it impra#ti#al to sol%e most #ommer#ial tas-s& 2n 19!3 the CPL .Combined Pro rammin lan ua e0 appeared "ith the idea o$ bein more spe#i$i# $or #on#rete pro rammin tas-s o$ that time than 'L()L or *)+T+',& ,e%ertheless this same spe#i$i#ity made it a bi lan ua e and, there$ore, di$$i#ult to learn and implement& 2n 19!4, 5artin +i#hards de%eloped the 6CPL .6asi# Combined Pro rammin Lan ua e0, that si ni$ied a simpli$i#ation o$ CPL but -ept most important $eatures the lan ua e o$$ered& 'lthou h it too "as an abstra#t and some"hat lar e lan ua e& 2n 1940, 7en Thompson, immersed in the de%elopment o$ U,28 at 6ell Labs, #reated the 6 lan ua e& 2t "as a port o$ 6CPL $or a spe#i$i# ma#hine and system .D9C PDP14 and U,280, and "as adapted to his parti#ular taste and ne#essities& The $inal result "as an e%en reater simpli$i#ation o$ CPL, althou h dependent on the system& 2t had reat limitations, li-e it did not #ompile to e:e#utable #ode but threaded1#ode, "hi#h enerates slo"er #ode in e:e#ution, and there$ore "as inade;uate $or the de%elopment o$ an operatin system& There$ore, $rom 1941, Denis +it#hie, $rom the 6ell Labs team, be an the de%elopment o$ a 6 #ompiler "hi#h, amon other thin s, "as able to enerate e:e#utable #ode dire#tly& This <,e" 6<, $inally #alled C, introdu#ed in addition, some other ne" #on#epts to the lan ua e li-e data types .#har0& 2n 1943, Denis +it#hie, had de%eloped the basis o$ C& The in#lusion o$ types, its handlin , as "ell as the impro%ement o$ arrays and pointers, alon "ith the later demonstrated #apa#ity o$ portability "ithout be#omin a hi h1le%el lan ua e, #ontributed to the e:pansion o$ the C lan ua e& 2t "as established "ith the boo- <The C Pro rammin Lan ua e< by 6rian 7erni han and Denis +it#hie, -no"n as the =hite 6oo-, and that ser%ed as de $a#to standard until the publi#ation o$ $ormal ',>2 standard .',>2 83J11 #ommittee0 in 1989& 2n 1980, 6?arne >troustrup, $rom 6ell labs, be an the de%elopment o$ the C// lan ua e, that "ould re#ei%e $ormally this name at the end o$ 1983, "hen its $irst manual "as oin to be published& 2n )#tober 198@, the $irst #ommer#ial release o$ the lan ua e appeared as "ell as the $irst edition o$ the boo- <The C// Pro rammin Lan ua e< by 6?arne >troustrup& Durin the 80s, the C// lan ua e "as bein re$ined until it be#ame a lan ua e "ith its o"n personality& 'll that "ith %ery $e" losses o$ #ompatibility "ith the #ode "ith C, and "ithout resi nin to its most important #hara#teristi#s& 2n $a#t, the ',>2 standard $or the C lan ua e published in 1989 too- ood part o$ the #ontributions o$ C// to stru#tured pro rammin & *rom 1990 on, ',>2 #ommittee 83J1! be an the de%elopment o$ a spe#i$i# standard $or C//& 2n the period elapsed until the publi#ation o$ the standard in 1998, C// li%ed a reat e:pansion in its use and today is the pre$erred lan ua e to de%elop pro$essional appli#ations on all plat$orms& C// has been e%ol%in , and a ne" %ersion o$ the standard, #//09, is bein de%eloped to be published be$ore the end o$ 2009, "ith se%eral ne" $eatures&

A brief description Programs


,o"adays #omputers are able to per$orm many di$$erent tas-s, $rom simple mathemati#al operations to sophisti#ated animated simulations& 6ut the #omputer does not #reate these tas-s by itsel$, these are per$ormed $ollo"in a series o$ prede$ined instru#tions that #on$orm "hat "e #all a pro ram& ' #omputer does not ha%e enou h #reati%ity to ma-e tas-s "hi#h it has not been pro rammed $or, so it #an only $ollo" the instru#tions o$ pro rams "hi#h it has been pro rammed to run& Those in #har e o$ eneratin pro rams so that the #omputers may per$orm ne" tas-s are -no"n as pro rammers or #oders, "ho $or that purpose use a pro rammin lan ua e&

Programming languages
' pro rammin lan ua e is a set o$ instru#tions and a series o$ le:i#al #on%entions spe#i$i#ally desi ned to order #omputers "hat to do& =hen #hoosin a pro rammin lan ua e to ma-e a pro?e#t, many di$$erent #onsiderations #an be ta-en& *irst, one must de#ide "hat is -no"n as the level o$ the pro rammin lan ua e& The le%el determines ho" near to the hard"are the pro rammin lan ua e is& 2n the lo"er le%el lan ua es, instru#tions are "ritten thin-in dire#tly on inter$a#in "ith hard"are, "hile in <hi h le%el< ones a more abstra#t or #on#eptual #ode is "ritten& (enerally, hi h le%el #ode is more portable, that means it #an "or- in more di$$erent ma#hines "ith a smaller number o$ modi$i#ations, "hereas a lo" le%el lan ua e is limited by the pe#uliarides o$ the hard"are "hi#h it "as "ritten $or& ,e%ertheless, the ad%anta e o$ lo" le%el #ode is that it is usually $aster due to the $a#t that it is indeed "ritten ta-in ad%anta e o$ the possibilities o$ a spe#i$i# ma#hine& ' hi her or lo"er le%el o$ pro rammin is to be #hosen $or a spe#i$i# pro?e#t dependin on the type o$ pro ram that is bein de%eloped& *or e:ample, "hen a hard"are dri%er is de%eloped $or an operatin system ob%iously a %ery lo" le%el is used $or pro rammin & =hile "hen bi appli#ations are de%eloped usually a hi her le%el is #hosen, or a #ombination o$ #riti# parts "ritten in lo" le%el lan ua es and others in hi her ones& 'lthou h there are lan ua es that are #learly thou ht to be lo" le%el, li-e 'ssembly, "hose instru#tion sets are adapted to ea#h ma#hine the #ode is made $or, and other lan ua es are inherently hi h le%el, li-e the Ja%a, that is desi ned to be totally independent o$ the plat$orm "here is oin to run& The C/ / lan ua e is in a middle position, sin#e it #an intera#t dire#tly "ith the hard"are almost "ith no limitations, and #an as "ell abstra#t lo"er layers and "or- li-e one o$ the most po"er$ul hi h le%el lan ua es&

Why C++?
C// has #ertain #hara#teristi#s o%er other pro rammin lan ua es& The most remar-able ones are: Object oriented programming The possibility to orientate pro rammin to ob?e#ts allo"s the pro rammer to desi n appli#ations $rom a point o$ %ie" more li-e a #ommuni#ation bet"een ob?e#ts rather than on a stru#tured se;uen#e o$ #ode& 2n addition it allo"s a reater reusability o$ #ode in a more lo i#al and produ#ti%e "ay& Portability Aou #an pra#ti#ally #ompile the same C// #ode in almost any type o$ #omputer and operatin system "ithout ma-in any #han es& C// is the most used and ported pro rammin lan ua e in the "orld&

!re"ity Code "ritten in C// is %ery short in #omparison "ith other lan ua es, sin#e the use o$ spe#ial #hara#ters is pre$erred to -ey "ords, sa%in some e$$ort to the pro rammer .and prolon in the li$e o$ our -eyboardsB0& #odular programming 'n appli#ationCs body in C// #an be made up o$ se%eral sour#e #ode $iles that are #ompiled separately and then lin-ed to ether& >a%in time sin#e it is not ne#essary to re#ompile the #omplete appli#ation "hen ma-in a sin le #han e but only the $ile that #ontains it& 2n addition, this #hara#teristi# allo"s to lin- C// #ode "ith #ode produ#ed in other lan ua es, su#h as 'ssembler or C& C Compatibility C// is ba#-"ards #ompatible "ith the C lan ua e& 'ny #ode "ritten in C #an easily be in#luded in a C// pro ram "ithout ma-in any #han e& Speed The resultin #ode $rom a C// #ompilation is %ery e$$i#ient, due indeed to its duality as hi h1 le%el and lo"1le%el lan ua e and to the redu#ed siDe o$ the lan ua e itsel$&

Structure of a program Probably the best "ay to start learnin a pro rammin lan ua e is by "ritin a pro ram& There$ore, here is our $irst pro ram:
// my first program in C++ #include <iostream> using namespace std; int main () { cout << "Hello World "; return !; " Hello World

The $irst panel sho"s the sour#e #ode $or our $irst pro ram& The se#ond one sho"s the result o$ the pro ram on#e #ompiled and e:e#uted& The "ay to edit and #ompile a pro ram depends on the #ompiler you are usin & Dependin on "hether it has a De%elopment 2nter$a#e or not and on its %ersion& Consult the #ompilers se#tion and the manual or help in#luded "ith your #ompiler i$ you ha%e doubts on ho" to #ompile a C// #onsole pro ram& The pre%ious pro ram is the typi#al pro ram that pro rammer apprenti#es "rite $or the $irst time, and its result is the printin on s#reen o$ the <Eello =orldB< senten#e& 2t is one o$ the simplest pro rams that #an be "ritten in C//, but it already #ontains the $undamental #omponents that e%ery C// pro ram has& =e are oin to loo- line by line at the #ode "e ha%e ?ust "ritten:

// my first program in C++


This is a #omment line& 'll lines be innin "ith t"o slash si ns . //0 are #onsidered #omments and do not ha%e any e$$e#t on the beha%ior o$ the pro ram& The pro rammer #an use them to in#lude short e:planations or obser%ations "ithin the sour#e #ode itsel$& 2n this #ase, the line is a brie$ des#ription o$ "hat our pro ram is&

#include <iostream>

Lines be innin "ith a hash si n .#0 are dire#ti%es $or the prepro#essor& They are not re ular #ode lines "ith e:pressions but indi#ations $or the #ompilerCs prepro#essor& 2n this #ase the dire#ti%e #include <iostream> tells the prepro#essor to in#lude the iostream standard $ile& This spe#i$i# $ile .iostream0 in#ludes the de#larations o$ the basi# standard input1output library in C//, and it is in#luded be#ause its $un#tionality is oin to be used later in the pro ram& 'll the elements o$ the standard C// library are de#lared "ithin "hat is #alled a namespa#e, the namespa#e "ith the name std& >o in order to a##ess its $un#tionality "e de#lare "ith this e:pression that "e "ill be usin these entities& This line is %ery $re;uent in C// pro rams that use the standard library, and in $a#t it "ill be in#luded in most o$ the sour#e #odes in#luded in these tutorials& This line #orresponds to the be innin o$ the de$inition o$ the main $un#tion& The main $un#tion is the point by "here all C// pro rams start their e:e#ution, independently o$ its lo#ation "ithin the sour#e #ode& 2t does not matter "hether there are other $un#tions "ith other names de$ined be$ore or a$ter it 1 the instru#tions #ontained "ithin this $un#tionCs de$inition "ill al"ays be the $irst ones to be e:e#uted in any C// pro ram& *or that same reason, it is essential that all C// pro rams ha%e a main $un#tion&

using namespace std;

int main ()

The "ord main is $ollo"ed in the #ode by a pair o$ parentheses . ()0& That is be#ause it is a $un#tion de#laration: 2n C//, "hat di$$erentiates a $un#tion de#laration $rom other types o$ e:pressions are these parentheses that $ollo" its name& )ptionally, these parentheses may en#lose a list o$ parameters "ithin them& +i ht a$ter these parentheses "e #an $ind the body o$ the main $un#tion en#losed in bra#es .{"0& =hat is #ontained "ithin these bra#es is "hat the $un#tion does "hen it is e:e#uted&

cout << "Hello World";

This line is a C// statement& ' statement is a simple or #ompound e:pression that #an a#tually produ#e some e$$e#t& 2n $a#t, this statement per$orms the only a#tion that enerates a %isible e$$e#t in our $irst pro ram&

cout represents the standard output stream in C//, and the meanin o$ the entire statement is to insert a se;uen#e o$ #hara#ters .in this #ase the Hello World se;uen#e o$ #hara#ters0
into the standard output stream ."hi#h usually is the s#reen0&

cout is de#lared in the iostream standard $ile "ithin the std namespa#e, so thatCs "hy "e
needed to in#lude that spe#i$i# $ile and to de#lare that "e "ere oin to use this spe#i$i# namespa#e earlier in our #ode& ,oti#e that the statement ends "ith a semi#olon #hara#ter . ;0& This #hara#ter is used to marthe end o$ the statement and in $a#t it must be in#luded at the end o$ all e:pression statements in all C// pro rams .one o$ the most #ommon synta: errors is indeed to $or et to in#lude some semi#olon a$ter a statement0&

return 0;

The return statement #auses the main $un#tion to $inish& return may be $ollo"ed by a return #ode .in our e:ample is $ollo"ed by the return #ode !0& ' return #ode o$ 0 $or the main $un#tion is enerally interpreted as the pro ram "or-ed as e:pe#ted "ithout any errors durin its e:e#ution& This is the most usual "ay to end a C// #onsole pro ram&

Aou may ha%e noti#ed that not all the lines o$ this pro ram per$orm a#tions "hen the #ode is e:e#uted& There "ere lines #ontainin only #omments .those be innin by //0& There "ere lines "ith dire#ti%es $or the #ompilerCs prepro#essor .those be innin by #0& Then there "ere lines that be an the de#laration o$ a $un#tion .in this #ase, the main $un#tion0 and, $inally lines "ith statements .li-e the insertion into cout0, "hi#h "ere all in#luded "ithin the blo#- delimited by the bra#es . {"0 o$ the main $un#tion& The pro ram has been stru#tured in di$$erent lines in order to be more readable, but in C//, "e do not ha%e stri#t rules on ho" to separate instru#tions in di$$erent lines& *or e:ample, instead o$

int main () { cout << " Hello World "; return !; "
=e #ould ha%e "ritten:

int main () { cout << "Hello World"; return !; "


'll in ?ust one line and this "ould ha%e had e:a#tly the same meanin as the pre%ious #ode& 2n C//, the separation bet"een statements is spe#i$ied "ith an endin semi#olon . ;0 at the end o$ ea#h one, so the separation in di$$erent #ode lines does not matter at all $or this purpose& =e #an "rite many statements per line or "rite a sin le statement that ta-es many #ode lines& The di%ision o$

#ode in di$$erent lines ser%es only to ma-e it more le ible and s#hemati# $or the humans that may read it& Let us add an additional instru#tion to our $irst pro ram:

// my second program in C++ #include <iostream> using namespace std; int main () { cout << "Hello World "; cout << "#$m a C++ program"; return !; "

Hello World

#$m a C++ program

2n this #ase, "e per$ormed t"o insertions into #out in t"o di$$erent statements& )n#e a ain, the separation in di$$erent lines o$ #ode has been done ?ust to i%e reater readability to the pro ram, sin#e main #ould ha%e been per$e#tly %alid de$ined this "ay:

int main () { cout << " Hello World return !; "

"; cout << " #$m a C++ program ";

=e "ere also $ree to di%ide the #ode into more lines i$ "e #onsidered it more #on%enient:

int main () { cout << "Hello World "; cout << "#$m a C++ program"; return !; "
'nd the result "ould a ain ha%e been e:a#tly the same as in the pre%ious e:amples& Prepro#essor dire#ti%es .those that be in by #0 are out o$ this eneral rule sin#e they are not statements& They are lines read and pro#essed by the prepro#essor and do not produ#e any #ode by themsel%es& Prepro#essor dire#ti%es must be spe#i$ied in their o"n line and do not ha%e to end "ith a semi#olon .;0&

Comments
Comments are parts o$ the sour#e #ode disre arded by the #ompiler& They simply do nothin & Their purpose is only to allo" the pro rammer to insert notes or des#riptions embedded "ithin the sour#e #ode& C// supports t"o "ays to insert #omments:

// line comment /% &loc' comment %/


The $irst o$ them, -no"n as line #omment, dis#ards e%erythin $rom "here the pair o$ slash si ns . //0 is $ound up to the end o$ that same line& The se#ond one, -no"n as blo#- #omment, dis#ards

e%erythin bet"een the /% #hara#ters and the $irst appearan#e o$ the %/ #hara#ters, "ith the possibility o$ in#ludin more than one line& =e are oin to add #omments to our se#ond pro ram:

/% my second program in C++ (it) more comments %/ #include <iostream> using namespace std; int main () { cout << "Hello World "; // prints Hello World cout << "#$m a C++ program"; // prints #$m a C++ program return !; "

Hello World

#$m a C++ program

2$ you in#lude #omments "ithin the sour#e #ode o$ your pro rams "ithout usin the #omment #hara#ters #ombinations //, /% or %/, the #ompiler "ill ta-e them as i$ they "ere C// e:pressions, most li-ely #ausin one or se%eral error messa es "hen you #ompile it&

$ariables% &ata 'ypes%

Published by Juan Soulie


Last update on 5ar 3, 2008 at 9:@0pm UTC

The use$ulness o$ the <Eello =orld< pro rams sho"n in the pre%ious se#tion is ;uite ;uestionable& =e had to "rite se%eral lines o$ #ode, #ompile them, and then e:e#ute the resultin pro ram ?ust to obtain a simple senten#e "ritten on the s#reen as result& 2t #ertainly "ould ha%e been mu#h $aster to type the output senten#e by oursel%es& Eo"e%er, pro rammin is not limited only to printin simple te:ts on the s#reen& 2n order to o a little $urther on and to be#ome able to "rite pro rams that per$orm use$ul tas-s that really sa%e us "or- "e need to introdu#e the #on#ept o$ %ariable& Let us thin- that 2 as- you to retain the number @ in your mental memory, and then 2 as- you to memoriDe also the number 2 at the same time& Aou ha%e ?ust stored t"o di$$erent %alues in your memory& ,o", i$ 2 as- you to add 1 to the $irst number 2 said, you should be retainin the numbers ! .that is @/10 and 2 in your memory& Falues that "e #ould no" $or e:ample subtra#t and obtain G as result& The "hole pro#ess that you ha%e ?ust done "ith your mental memory is a simile o$ "hat a #omputer #an do "ith t"o %ariables& The same pro#ess #an be e:pressed in C// "ith the $ollo"in instru#tion set:

a * +; & * ,; a * a + -; result * a . &;


)b%iously, this is a %ery simple e:ample sin#e "e ha%e only used t"o small inte er %alues, but #onsider that your #omputer #an store millions o$ numbers li-e these at the same time and #ondu#t sophisti#ated mathemati#al operations "ith them& There$ore, "e #an de$ine a %ariable as a portion o$ memory to store a determined %alue& 9a#h %ariable needs an identi$ier that distin uishes it $rom the others, $or e:ample, in the pre%ious #ode the %ariable identi$iers "ere a, & and result, but "e #ould ha%e #alled the %ariables any names "e "anted to in%ent, as lon as they "ere %alid identi$iers&

(dentifiers
' %alid identi$ier is a se;uen#e o$ one or more letters, di its or unders#ore #hara#ters . /0& ,either spa#es nor pun#tuation mar-s or symbols #an be part o$ an identi$ier& )nly letters, di its and sin le unders#ore #hara#ters are %alid& 2n addition, %ariable identi$iers al"ays ha%e to be in "ith a letter& They #an also be in "ith an underline #hara#ter . / 0, but in some #ases these may be reser%ed $or #ompiler spe#i$i# -ey"ords or e:ternal identi$iers, as "ell as identi$iers #ontainin t"o su##essi%e unders#ore #hara#ters any"here& 2n no #ase they #an be in "ith a di it& 'nother rule that you ha%e to #onsider "hen in%entin your o"n identi$iers is that they #annot mat#h any -ey"ord o$ the C// lan ua e nor your #ompilerCs spe#i$i# ones, "hi#h are reserved keywords& The standard reser%ed -ey"ords are:

asm0 auto0 &ool0 &rea'0 case0 catc)0 c)ar0 class0 const0 const/cast0 continue0 default0 delete0 do0 dou&le0 dynamic/cast0 else0 enum0 e1plicit0 e1port0 e1tern0 false0 float0 for0 friend0 goto0 if0 inline0 int0 long0 muta&le0 namespace0 ne(0 operator0 pri2ate0 protected0 pu&lic0 register0 reinterpret/cast0 return0 s)ort0 signed0 si3eof0 static0 static/cast0 struct0

s(itc)0 template0 t)is0 t)ro(0 true0 try0 typedef0 typeid0 typename0 union0 unsigned0 using0 2irtual0 2oid0 2olatile0 (c)ar/t0 ()ile
'dditionally, alternati%e representations $or some operators #annot be used as identi$iers sin#e they are reser%ed "ords under some #ir#umstan#es:

and0 and/e40 &itand0 &itor0 compl0 not0 not/e40 or0 or/e40 1or0 1or/e4
Aour #ompiler may also in#lude some additional spe#i$i# reser%ed -ey"ords& $ery important) The C// lan ua e is a <#ase sensiti%e< lan ua e& That means that an identi$ier "ritten in #apital letters is not e;ui%alent to another one "ith the same name but "ritten in small letters& Thus, $or e:ample, the 56789: %ariable is not the same as the result %ariable or the 5esult %ariable& These are three di$$erent %ariable identi$iers&

*undamental data types


=hen pro rammin , "e store the %ariables in our #omputerCs memory, but the #omputer has to -no" "hat -ind o$ data "e "ant to store in them, sin#e it is not oin to o##upy the same amount o$ memory to store a simple number than to store a sin le letter or a lar e number, and they are not oin to be interpreted the same "ay& The memory in our #omputers is or aniDed in bytes& ' byte is the minimum amount o$ memory that "e #an mana e in C//& ' byte #an store a relati%ely small amount o$ data: one sin le #hara#ter or a small inte er . enerally an inte er bet"een 0 and 2@@0& 2n addition, the #omputer #an manipulate more #omple: data types that #ome $rom roupin se%eral bytes, su#h as lon numbers or non1 inte er numbers& ,e:t you ha%e a summary o$ the basi# $undamental data types in C//, as "ell as the ran e o$ %alues that #an be represented "ith ea#h one: +ame &escription Chara#ter or small inte er& >hort 2nte er& 2nte er& Si,e1byte 2bytes Gbytes .angesi ned: 1128 to 124 unsi ned: 0 to 2@@ si ned: 1324!8 to 324!4 unsi ned: 0 to !@@3@ si ned: 121G4G83!G8 to 21G4G83!G4 unsi ned: 0 to G29G9!429@ si ned: 121G4G83!G8 to 21G4G83!G4 unsi ned: 0 to G29G9!429@ true or $alse 3&Ge /H1 38 .4 di its0 1&4e /H1 308 .1@ di its0 1&4e /H1 308 .1@ di its0 1 "ide #hara#ter

c)ar s)ort int .s)ort0 int long int .long0 &ool float dou&le long dou&le (c)ar/t

Lon inte er& 6oolean %alue& 2t #an ta-e one o$ t"o %alues: true or $alse& *loatin point number& Double pre#ision $loatin point number& Lon double pre#ision $loatin point number& =ide #hara#ter&

Gbytes 1byte Gbytes 8bytes 8bytes 2 or G bytes

I The %alues o$ the #olumns Si,e and .ange depend on the system the pro ram is #ompiled $or& The %alues sho"n abo%e are those $ound on most 321bit systems& 6ut $or other systems, the eneral spe#i$i#ation is that int has the natural siDe su ested by the system ar#hite#ture .one < word<0 and the $our inte er types c)ar, s)ort, int and long must ea#h one be at least as lar e as the one pre#edin it, "ith c)ar bein al"ays 1 byte in siDe& The same applies to the $loatin point types float, dou&le and long dou&le, "here ea#h one must pro%ide at least as mu#h pre#ision as the pre#edin one&

&eclaration of "ariables
2n order to use a %ariable in C//, "e must $irst de#lare it spe#i$yin "hi#h data type "e "ant it to be& The synta: to de#lare a ne" %ariable is to "rite the spe#i$ier o$ the desired data type .li-e int, bool, $loat&&&0 $ollo"ed by a %alid %ariable identi$ier& *or e:ample:

int a; float mynum&er;


These are t"o %alid de#larations o$ %ariables& The $irst one de#lares a %ariable o$ type int "ith the identi$ier a& The se#ond one de#lares a %ariable o$ type float "ith the identi$ier mynum&er& )n#e de#lared, the %ariables a and mynum&er #an be used "ithin the rest o$ their s#ope in the pro ram& 2$ you are oin to de#lare more than one %ariable o$ the same type, you #an de#lare all o$ them in a sin le statement by separatin their identi$iers "ith #ommas& *or e:ample:

int a0 &0 c;
This de#lares three %ariables .a, & and c0, all o$ them o$ type int, and has e:a#tly the same meanin as:

int a; int &; int c;


The inte er data types c)ar, s)ort, long and int #an be either si ned or unsi ned dependin on the ran e o$ numbers needed to be represented& >i ned types #an represent both positi%e and ne ati%e %alues, "hereas unsi ned types #an only represent positi%e %alues .and Dero0& This #an be spe#i$ied by usin either the spe#i$ier signed or the spe#i$ier unsigned be$ore the type name& *or e:ample:

unsigned s)ort int ;um&er<f7isters; signed int =y>ccount?alance;


6y de$ault, i$ "e do not spe#i$y either signed or unsigned most #ompiler settin s "ill assume the type to be si ned, there$ore instead o$ the se#ond de#laration abo%e "e #ould ha%e "ritten:

int =y>ccount?alance;
"ith e:a#tly the same meanin ."ith or "ithout the -ey"ord signed0 'n e:#eption to this eneral rule is the c)ar type, "hi#h e:ists by itsel$ and is #onsidered a di$$erent $undamental data type $rom signed c)ar and unsigned c)ar, thou ht to store #hara#ters& Aou should use either signed or unsigned i$ you intend to store numeri#al %alues in a c)ar1siDed %ariable&

s)ort and long #an be used alone as type spe#i$iers& 2n this #ase, they re$er to their respe#ti%e inte er $undamental types: s)ort is e;ui%alent to s)ort int and long is e;ui%alent to long int&
The $ollo"in t"o %ariable de#larations are e;ui%alent:

s)ort @ear; s)ort int @ear;


*inally, signed and unsigned may also be used as standalone type spe#i$iers, meanin the same as signed int and unsigned int respe#ti%ely& The $ollo"in t"o de#larations are e;ui%alent:

unsigned ;e1t@ear; unsigned int ;e1t@ear;


To see "hat %ariable de#larations loo- li-e in a#tion "ithin a pro ram, "e are oin to see the C// #ode o$ the e:ample about your mental memory proposed at the be innin o$ this se#tion:

// operating (it) 2aria&les #include <iostream> using namespace std; int main () { // declaring 2aria&lesA int a0 &; int result; // processA a * +; & * ,; a * a + -; result * a . &; // print out t)e resultA cout << result; // terminate t)e programA return !;

"

Do not "orry i$ somethin else than the %ariable de#larations themsel%es loo-s a bit stran e to you& Aou "ill see the rest in detail in #omin se#tions&

Scope of "ariables
'll the %ariables that "e intend to use in a pro ram must ha%e been de#lared "ith its type spe#i$ier in an earlier point in the #ode, li-e "e did in the pre%ious #ode at the be innin o$ the body o$ the $un#tion main "hen "e de#lared that a, &, and result "ere o$ type int& ' %ariable #an be either o$ lobal or lo#al s#ope& ' lobal %ariable is a %ariable de#lared in the main body o$ the sour#e #ode, outside all $un#tions, "hile a lo#al %ariable is one de#lared "ithin the body o$ a $un#tion or a blo#-&

(lobal %ariables #an be re$erred $rom any"here in the #ode, e%en inside $un#tions, "hene%er it is a$ter its de#laration& The s#ope o$ lo#al %ariables is limited to the blo#- en#losed in bra#es .JK0 "here they are de#lared& *or e:ample, i$ they are de#lared at the be innin o$ the body o$ a $un#tion .li-e in $un#tion main0 their s#ope is bet"een its de#laration point and the end o$ that $un#tion& 2n the e:ample abo%e, this means that i$ another $un#tion e:isted in addition to main, the lo#al %ariables de#lared in main #ould not be a##essed $rom the other $un#tion and %i#e %ersa&

(nitiali,ation of "ariables
=hen de#larin a re ular lo#al %ariable, its %alue is by de$ault undetermined& 6ut you may "ant a %ariable to store a #on#rete %alue at the same moment that it is de#lared& 2n order to do that, you #an initialiDe the %ariable& There are t"o "ays to do this in C//: The $irst one, -no"n as #1li-e, is done by appendin an e;ual si n $ollo"ed by the %alue to "hi#h the %ariable "ill be initialiDed:

type identifier * initial/2alue ;


*or e:ample, i$ "e "ant to de#lare an int %ariable #alled a initialiDed "ith a %alue o$ 0 at the moment in "hi#h it is de#lared, "e #ould "rite:

int a * !;
The other "ay to initialiDe %ariables, -no"n as #onstru#tor initialiDation, is done by en#losin the initial %alue bet"een parentheses .()0:

type identifier (initial/2alue) ;


*or e:ample:

int a (!);
6oth "ays o$ initialiDin %ariables are %alid and e;ui%alent in C//&

// initiali3ation of 2aria&les

#include <iostream> using namespace std; int main () { int a*+; 2alue * + int &(,); 2alue * , int result; 2alue undetermined a * a + D; result * a . &; cout << result; " return !;

// initial // initial // initial

(ntroduction to strings
Fariables that #an store non1numeri#al %alues that are lon er than one sin le #hara#ter are -no"n as strin s& The C// lan ua e library pro%ides support $or strin s throu h the standard string #lass& This is not a $undamental type, but it beha%es in a similar "ay as $undamental types do in its most basi# usa e& ' $irst di$$eren#e "ith $undamental data types is that in order to de#lare and use ob?e#ts .%ariables0 o$ this type "e need to in#lude an additional header $ile in our sour#e #ode: <string> and ha%e a##ess to the std namespa#e ."hi#h "e already had in all our pre%ious pro rams than-s to the using namespace statement0&

// my first string #include <iostream> #include <string> using namespace std; int main () { string mystring * ":)is is a string"; cout << mystring; return !; "

:)is is a string

's you may see in the pre%ious e:ample, strin s #an be initialiDed "ith any %alid strin literal ?ust li-e numeri#al type %ariables #an be initialiDed to any %alid numeri#al literal& 6oth initialiDation $ormats are %alid "ith strin s:

string mystring * ":)is is a string"; string mystring (":)is is a string");


>trin s #an also per$orm all the other basi# operations that $undamental data types #an, li-e bein de#lared "ithout an initial %alue and bein assi ned %alues durin e:e#ution:

// my first string #include <iostream> #include <string> using namespace std;

:)is is t)e initial string content :)is is a different string content

int main () { string mystring; mystring * ":)is string content"; cout << mystring mystring * ":)is string content"; cout << mystring return !; "

is t)e initial << endl; is a different << endl;

*or more details on C// strin s, you #an ha%e a loo- at the strin #lass re$eren#e&

Constants
Constants are e:pressions "ith a $i:ed %alue&

Published by Juan Soulie


Last update on )#t 11, 2004 at 8:@9am UTC

/iterals
Literals are used to e:press parti#ular %alues "ithin the sour#e #ode o$ a pro ram& =e ha%e already used these pre%iously to i%e #on#rete %alues to %ariables or to e:press messa es "e "anted our pro rams to print out, $or e:ample, "hen "e "rote:

a * +;
the + in this pie#e o$ #ode "as a literal #onstant& Literal #onstants #an be di%ided in 2nte er ,umerals, *loatin 1Point ,umerals, Chara#ters, >trin s and 6oolean Falues&

(nteger +umerals
-EEC E!E .,ED
They are numeri#al #onstants that identi$y inte er de#imal %alues& ,oti#e that to e:press a numeri#al #onstant "e do not ha%e to "rite ;uotes ."0 nor any spe#ial #hara#ter& There is no doubt that it is a #onstant: "hene%er "e "rite -EEC in a pro ram, "e "ill be re$errin to the %alue 144!& 2n addition to de#imal numbers .those that all o$ us are used to use e%ery day0 C// allo"s the use as literal #onstants o$ o#tal numbers .base 80 and he:ade#imal numbers .base 1!0& 2$ "e "ant to e:press an o#tal number "e ha%e to pre#ede it "ith a ! .Dero #hara#ter0& 'nd in order to e:press a he:ade#imal number "e ha%e to pre#ede it "ith the #hara#ters !1 .Dero, :0& *or e:ample, the $ollo"in literal #onstants are all e;ui%alent to ea#h other:

E+ !--D !1B&

// decimal // octal // )e1adecimal

'll o$ these represent the same number: 4@ .se%enty1$i%e0 e:pressed as a base110 numeral, o#tal numeral and he:ade#imal numeral, respe#ti%ely& Literal #onstants, li-e %ariables, are #onsidered to ha%e a spe#i$i# data type& 6y de$ault, inte er literals are o$ type int& Eo"e%er, "e #an $or#e them to either be unsi ned by appendin the u #hara#ter to it, or lon by appendin l:

E+ E+u E+l E+ul

// // // //

int unsigned int long unsigned long

2n both #ases, the su$$i: #an be spe#i$ied usin either upper or lo"er#ase letters&

*loating Point +umbers


They e:press numbers "ith de#imals andHor e:ponents& They #an in#lude either a de#imal point, an e #hara#ter .that e:presses <by ten at the 8th hei ht<, "here 8 is an inte er %alue that $ollo"s the e #hara#ter0, or both a de#imal point and an e #hara#ter:

DF-B-+G CF!,e,D -FCe.-G DF!

// // // //

DF-B-+G CF!, 1 -!H,D -FC 1 -!H.-G DF!

These are $our %alid numbers "ith de#imals e:pressed in C//& The $irst number is P2, the se#ond one is the number o$ '%o adro, the third is the ele#tri# #har e o$ an ele#tron .an e:tremely small number0 1all o$ them appro:imated1 and the last one is the number three e:pressed as a $loatin 1point numeri# literal& The de$ault type $or $loatin point literals is dou&le& 2$ you e:pli#itly "ant to e:press a float or long dou&le numeri#al literal, you #an use the f or l su$$i:es respe#ti%ely:

DF-B-+G9 CF!,e,Df

// long dou&le // float

'ny o$ the letters than #an be part o$ a $loatin 1point numeri#al #onstant . e, f, l0 #an be "ritten usin either lo"er or upper#ase letters "ithout any di$$eren#e in their meanin s&

Character and string literals


There also e:ist non1numeri#al #onstants, li-e:

$3$ $p$ "Hello (orld" "Ho( do you doI"


The $irst t"o e:pressions represent sin le #hara#ter #onstants, and the $ollo"in t"o represent strin literals #omposed o$ se%eral #hara#ters& ,oti#e that to represent a sin le #hara#ter "e en#lose it bet"een sin le ;uotes .$0 and to e:press a strin ."hi#h enerally #onsists o$ more than one #hara#ter0 "e en#lose it bet"een double ;uotes ."0& =hen "ritin both sin le #hara#ter and strin literals, it is ne#essary to put the ;uotation mar-s surroundin them to distin uish them $rom possible %ariable identi$iers or reser%ed -ey"ords& ,oti#e the di$$eren#e bet"een these t"o e:pressions:

1 $1$ 1 alone "ould re$er to a %ariable "hose identi$ier is 1, "hereas $1$ .en#losed "ithin sin le ;uotation mar-s0 "ould re$er to the #hara#ter #onstant $1$&
Chara#ter and strin literals ha%e #ertain pe#uliarities, li-e the es#ape #odes& These are spe#ial #hara#ters that are di$$i#ult or impossible to e:press other"ise in the sour#e #ode o$ a pro ram, li-e ne"line .Jn0 or tab .Jt0& 'll o$ them are pre#eded by a ba#-slash .J0& Eere you ha%e a list o$ some o$ su#h es#ape #odes:

Jn ne"line Jr #arria e return Jt tab J2 %erti#al tab

J& ba#-spa#e Jf $orm $eed .pa e $eed0 Ja alert .beep0 J$ sin le ;uote .$0 J" double ;uote ."0 JI ;uestion mar- .I0 JJ ba#-slash .J0
*or e:ample:

$Jn$ $Jt$ "9eft Jt 5ig)t" "oneJnt(oJnt)ree"


'dditionally, you #an e:press any #hara#ter by its numeri#al '>C22 #ode by "ritin a ba#-slash #hara#ter .J0 $ollo"ed by the '>C22 #ode e:pressed as an o#tal .base180 or he:ade#imal .base11!0 number& 2n the $irst #ase .o#tal0 the di its must immediately $ollo" the ba#-slash .$or e:ample J,D or JB!0, in the se#ond #ase .he:ade#imal0, an 1 #hara#ter must be "ritten be$ore the di its themsel%es .$or e:ample J1,! or J1B>0& >trin literals #an e:tend to more than a sin le line o$ #ode by puttin a ba#-slash si n . J0 at the end o$ ea#h un$inished line&

"string e1pressed in J t(o lines"


Aou #an also #on#atenate se%eral strin #onstants separatin them by one or se%eral blan- spa#es, tabulators, ne"line or any other %alid blan- #hara#ter:

"t)is forms" "a single" "string" "of c)aracters"


*inally, i$ "e "ant the strin literal to be e:pli#itly made o$ "ide #hara#ters . (c)ar/t0, instead o$ narro" #hara#ters .c)ar0, "e #an pre#ede the #onstant "ith the L pre$i::

9":)is is a (ide c)aracter string"


=ide #hara#ters are used mainly to represent non19n lish or e:oti# #hara#ter sets&

!oolean literals
There are only t"o %alid 6oolean %alues: true and $alse& These #an be e:pressed in C// as %alues o$ type &ool by usin the 6oolean literals true and false&

&efined constants 01define2


Aou #an de$ine your o"n names $or #onstants that you use %ery o$ten "ithout ha%in to resort to memory1#onsumin %ariables, simply by usin the #define prepro#essor dire#ti%e& 2ts $ormat is:

#define identifier 2alue


*or e:ample:

#define K# DF-B-+G,C+

#define ;6W9#;6 $Jn$


This de$ines t"o ne" #onstants: K# and ;6W9#;6& )n#e they are de$ined, you #an use them in the rest o$ the #ode as i$ they "ere any other re ular #onstant, $or e:ample:

// defined constantsA calculate circumference #include <iostream> using namespace std; #define K# DF-B-+G #define ;6W9#;6 $Jn$ int main () { dou&le r*+F!; dou&le circle; circle * , % K# % r; cout << circle; cout << ;6W9#;6; " return !;

D-FB-+G

// radius

2n $a#t the only thin that the #ompiler prepro#essor does "hen it en#ounters #define dire#ti%es is to literally repla#e any o##urren#e o$ their identi$ier .in the pre%ious e:ample, these "ere K# and ;6W9#;60 by the #ode to "hi#h they ha%e been de$ined .DF-B-+G,C+ and $Jn$ respe#ti%ely0& The #define dire#ti%e is not a C// statement but a dire#ti%e $or the prepro#essorL there$ore it assumes the entire line as the dire#ti%e and does not re;uire a semi#olon . ;0 at its end& 2$ you append a semi#olon #hara#ter .;0 at the end, it "ill also be appended in all o##urren#es "ithin the body o$ the pro ram that the prepro#essor repla#es&

&eclared constants 0const2


=ith the const pre$i: you #an de#lare #onstants "ith a spe#i$i# type in the same "ay as you "ould do "ith a %ariable:

const int pat)(idt) * -!!; const c)ar ta&ulator * $Jt$;


Eere, pat)(idt) and ta&ulator are t"o typed #onstants& They are treated ?ust li-e re ular %ariables e:#ept that their %alues #annot be modi$ied a$ter their de$inition&

Operators

Published by Juan Soulie


Last update on Jun 8, 2004 at 10:1@am UTC

)n#e "e -no" o$ the e:isten#e o$ %ariables and #onstants, "e #an be in to operate "ith them& *or that purpose, C// inte rates operators& Unli-e other lan ua es "hose operators are mainly -ey"ords, operators in C// are mostly made o$ si ns that are not part o$ the alphabet but are a%ailable in all -eyboards& This ma-es C// #ode shorter and more international, sin#e it relies less on 9n lish "ords, but re;uires a little o$ learnin e$$ort in the be innin & Aou do not ha%e to memoriDe all the #ontent o$ this pa e& 5ost details are only pro%ided to ser%e as a later re$eren#e in #ase you need it&

Assignment 032
The assi nment operator assi ns a %alue to a %ariable&

a * +;
This statement assi ns the inte er %alue @ to the %ariable a& The part at the le$t o$ the assi nment operator .*0 is -no"n as the lvalue .le$t %alue0 and the ri ht one as the rvalue .ri ht %alue0& The l%alue has to be a %ariable "hereas the r%alue #an be either a #onstant, a %ariable, the result o$ an operation or any #ombination o$ these& The most important rule "hen assi nin is the right-to-left rule: The assi nment operation al"ays ta-es pla#e $rom ri ht to le$t, and ne%er the other "ay:

a * &;
This statement assi ns to %ariable a .the l%alue0 the %alue #ontained in %ariable & .the r%alue0& The %alue that "as stored until this moment in a is not #onsidered at all in this operation, and in $a#t that %alue is lost& Consider also that "e are only assi nin the %alue o$ & to a at the moment o$ the assi nment operation& There$ore a later #han e o$ & "ill not a$$e#t the ne" %alue o$ a& *or e:ample, let us ha%e a loo- at the $ollo"in #ode 1 2 ha%e in#luded the e%olution o$ the #ontent stored in the %ariables as #omments:

// assignment operator #include <iostream> using namespace std; int main () { int a0 &; a * -!; & * B; a * &; & * E; cout cout cout cout " << << << << "aA"; a; " &A"; &;

aAB &AE

// // // // //

aAI0 aA-!0 aA-!0 aAB0 aAB0

&AI &AI &AB &AB &AE

return !;

This #ode "ill i%e us as result that the %alue #ontained in a is B and the one #ontained in & is E& ,oti#e ho" a "as not a$$e#ted by the $inal modi$i#ation o$ &, e%en thou h "e de#lared a * & earlier .that is be#ause o$ the right-to-left rule0& ' property that C// has o%er other pro rammin lan ua es is that the assi nment operation #an be used as the r%alue .or part o$ an r%alue0 $or another assi nment operation& *or e:ample:

a * , + (& * +);
is e;ui%alent to:

& * +; a * , + &;
that means: $irst assi n + to %ariable & and then assi n to a the %alue , plus the result o$ the pre%ious assi nment o$ & .i&e& @0, lea%in a "ith a $inal %alue o$ E& The $ollo"in e:pression is also %alid in C//:

a * & * c * +;
2t assi ns + to the all the three %ariables: a, & and c&

Arithmetic operators 0 +4 4 -4 54 6 2
The $i%e arithmeti#al operations supported by the C// lan ua e are: / 'ddition 1 >ubtra#tion I 5ultipli#ation H Di%ision M 5odulo )perations o$ addition, subtra#tion, multipli#ation and di%ision literally #orrespond "ith their respe#ti%e mathemati#al operators& The only one that you mi ht not be so used to see may be moduloL "hose operator is the per#enta e si n .L0& 5odulo is the operation that i%es the remainder o$ a di%ision o$ t"o %alues& *or e:ample, i$ "e "rite:

a * -- L D;
the %ariable a "ill #ontain the %alue ,, sin#e , is the remainder $rom di%idin -- bet"een D&

Compound assignment 0+34 34 -34 534 634 7734 8834 934 :34 ;32
=hen "e "ant to modi$y the %alue o$ a %ariable by per$ormin an operation on the %alue #urrently stored in that %ariable "e #an use #ompound assi nment operators: e<pression is e=ui"alent to

2alue +* increase; 2alue a .* +; a * a a /* &; a * a price %* units + -; price

* . / *

2alue + increase; +; &; price % (units + -);

and the same $or all other operators& *or e:ample:

// compound assignment operators #include <iostream> using namespace std; int main () { int a0 &*D; a * &; a+*,; a*a+, cout << a; return !; "

// e4ui2alent to

(ncrease and decrease 0++4

>hortenin e%en more some e:pressions, the in#rease operator . ++0 and the de#rease operator ...0 in#rease or redu#e by one the %alue stored in a %ariable& They are e;ui%alent to +*- and to .*-, respe#ti%ely& Thus:

c++; c+*-; c*c+-;


are all e;ui%alent in its $un#tionality: the three o$ them in#rease by one the %alue o$ #& 2n the early C #ompilers, the three pre%ious e:pressions probably produ#ed di$$erent e:e#utable #ode dependin on "hi#h one "as used& ,o"adays, this type o$ #ode optimiDation is enerally done automati#ally by the #ompiler, thus the three e:pressions should produ#e e:a#tly the same e:e#utable #ode& ' #hara#teristi# o$ this operator is that it #an be used both as a pre$i: and as a su$$i:& That means that it #an be "ritten either be$ore the %ariable identi$ier . ++a0 or a$ter it .a++0& 'lthou h in simple e:pressions li-e a++ or ++a both ha%e e:a#tly the same meanin , in other e:pressions in "hi#h the result o$ the in#rease or de#rease operation is e%aluated as a %alue in an outer e:pression they may ha%e an important di$$eren#e in their meanin : 2n the #ase that the in#rease operator is used as a pre$i: .//a0 the %alue is in#reased be$ore the result o$ the e:pression is e%aluated and there$ore the in#reased %alue is #onsidered in the outer e:pressionL in #ase that it is used as a su$$i: . a++0 the %alue stored in a is in#reased a$ter bein e%aluated and there$ore the %alue stored be$ore the in#rease operation is e%aluated in the outer e:pression& ,oti#e the di$$eren#e: ><ample ? ><ample @

?*D; ?*D; >*++?; >*?++; // > contains B0 ? contains B // > contains D0 ? contains B
2n 9:ample 1, ? is in#reased be$ore its %alue is #opied to >& =hile in 9:ample 2, the %alue o$ ? is #opied to > and then ? is in#reased&

.elational and e=uality operators 0 334 A34 74 84 734 83 2


2n order to e%aluate a #omparison bet"een t"o e:pressions "e #an use the relational and e;uality operators& The result o$ a relational operation is a 6oolean %alue that #an only be true or $alse, a##ordin to its 6oolean result&

=e may "ant to #ompare t"o e:pressions, $or e:ample, to -no" i$ they are e;ual or i$ one is reater than the other is& Eere is a list o$ the relational and e;uality operators that #an be used in C//: NN 9;ual to BN ,ot e;ual to O (reater than P Less than ON (reater than or e;ual to PN Less than or e;ual to Eere there are some e:amples:

(E (+ (D (C (+

** +) > B) * ,) >* C) < +)

// // // // //

e2aluates e2aluates e2aluates e2aluates e2aluates

to to to to to

falseF trueF trueF trueF falseF

)$ #ourse, instead o$ usin only numeri# #onstants, "e #an use any %alid e:pression, in#ludin %ariables& >uppose that a*,, &*D and c*C,

(a ** +) (a%& >* c) (&+B > a%c) ((&*,) ** a)

// // // //

e2aluates e2aluates e2aluates e2aluates

to to to to

false since a is not e4ual to +F true since (,%D >* C) is trueF false since (D+B > ,%C) is falseF trueF

6e #are$ulB The operator * .one e;ual si n0 is not the same as the operator ** .t"o e;ual si ns0, the $irst one is an assi nment operator .assi ns the %alue at its ri ht to the %ariable at its le$t0 and the other one .**0 is the e;uality operator that #ompares "hether both e:pressions in the t"o sides o$ it are e;ual to ea#h other& Thus, in the last e:pression ((&*,) ** a), "e $irst assi ned the %alue , to & and then "e #ompared it to a, that also stores the %alue ,, so the result o$ the operation is true&

/ogical operators 0 A4 994 ;; 2


The )perator is the C// operator to per$orm the 6oolean operation ,)T, it has only one operand, lo#ated at its ri ht, and the only thin that it does is to in%erse the %alue o$ it, produ#in $alse i$ its operand is true and true i$ its operand is $alse& 6asi#ally, it returns the opposite 6oolean %alue o$ e%aluatin its operand& *or e:ample:

(+ ** +) +) is trueF (C <* B) true false

// e2aluates to false &ecause t)e e1pression at its rig)t (+ ** // e2aluates to true &ecause (C <* B) (ould &e falseF // e2aluates to false // e2aluates to trueF

The lo i#al operators MM and NN are used "hen e%aluatin t"o e:pressions to obtain a sin le relational result& The operator MM #orresponds "ith 6oolean lo i#al operation ',D& This operation results true i$ both its t"o operands are true, and $alse other"ise& The $ollo"in panel sho"s the result o$ operator MM e%aluatin the e:pression a MM &: 99 OP>.A'O. a b a 99 b true true True true $alse *alse

$alse true *alse $alse $alse *alse The operator NN #orresponds "ith 6oolean lo i#al operation )+& This operation results true i$ either one o$ its t"o operands is true, thus bein $alse only "hen both operands are $alse themsel%es& Eere are the possible results o$ a NN &: ;; OP>.A'O. a b a ;; b true true True true $alse True $alse true True $alse $alse *alse *or e:ample:

( (+ ** +) MM (D > C) ) ( (+ ** +) NN (D > C) )

// e2aluates to false ( true MM false )F // e2aluates to true ( true NN false )F

Conditional operator 0 ? 2
The #onditional operator e%aluates an e:pression returnin a %alue i$ that e:pression is true and a di$$erent one i$ the e:pression is e%aluated as $alse& 2ts $ormat is:

condition I result- A result,


2$ condition is true the e:pression "ill return result-, i$ it is not it "ill return result,&

E**+ I B A D // returns E**++, I B A D // returns +>D I a A & // returns a>& I a A & // returns // conditional operator #include <iostream> using namespace std; int main () { int a0&0c; a*,; &*E; c * (a>&) I a A &; cout << c; return !; "

D0 since E is not e4ual to +F B0 since E is e4ual to ++,F t)e 2alue of a0 since + is greater t)an DF ()ic)e2er is greater0 a or &F E

2n this e:ample a "as , and & "as E, so the e:pression bein e%aluated .a>&0 "as not true, thus the $irst %alue spe#i$ied a$ter the ;uestion mar- "as dis#arded in $a%or o$ the se#ond %alue .the one a$ter the #olon0 "hi#h "as &, "ith a %alue o$ E&

Comma operator 0 4 2
The #omma operator .00 is used to separate t"o or more e:pressions that are in#luded "here only one e:pression is e:pe#ted& =hen the set o$ e:pressions has to be e%aluated $or a %alue, only the ri htmost e:pression is #onsidered& *or e:ample, the $ollo"in #ode:

a * (&*D0 &+,);
=ould $irst assi n the %alue D to &, and then assi n &+, to %ariable a& >o, at the end, %ariable a "ould #ontain the %alue + "hile %ariable & "ould #ontain %alue D&

!itBise Operators 0 94 ;4 :4 C4 884 77 2


6it"ise operators modi$y %ariables #onsiderin the bit patterns that represent the %alues they store& operator asm e=ui"alent description M ',D 6it"ise ',D

N H O << >>

)+ 8)+ ,)T >EL >E+

6it"ise 2n#lusi%e )+ 6it"ise 9:#lusi%e )+ Unary #omplement .bit in%ersion0 >hi$t Le$t >hi$t +i ht

><plicit type casting operator


Type #astin operators allo" you to #on%ert a datum o$ a i%en type to another& There are se%eral "ays to do this in C//& The simplest one, "hi#h has been inherited $rom the C lan ua e, is to pre#ede the e:pression to be #on%erted by the ne" type en#losed bet"een parentheses . ()0:

int i; float f * DF-B; i * (int) f;


The pre%ious #ode #on%erts the $loat number DF-B to an inte er %alue .D0, the remainder is lost& Eere, the type#astin operator "as (int)& 'nother "ay to do the same thin in C// is usin the $un#tional notation: pre#edin the e:pression to be #on%erted by the type and en#losin the e:pression bet"een parentheses:

i * int ( f );
6oth "ays o$ type #astin are %alid in C//&

si,eof02
This operator a##epts one parameter, "hi#h #an be either a type or a %ariable itsel$ and returns the siDe in bytes o$ that type or ob?e#t:

a * si3eof (c)ar);
This "ill assi n the %alue - to a be#ause c)ar is a one1byte lon type& The %alue returned by si3eof is a #onstant, so it is al"ays determined be$ore pro ram e:e#ution&

Other operators
Later in these tutorials, "e "ill see a $e" more operators, li-e the ones re$errin to pointers or the spe#i$i#s $or ob?e#t1oriented pro rammin & 9a#h one is treated in its respe#ti%e se#tion&

Precedence of operators
=hen "ritin #omple: e:pressions "ith se%eral operands, "e may ha%e some doubts about "hi#h operand is e%aluated $irst and "hi#h later& *or e:ample, in this e:pression:

a * + + E L ,
"e may doubt i$ it really means:

a * + + (E L ,) a * (+ + E) L ,

// (it) a result of C0 or // (it) a result of !

The #orre#t ans"er is the $irst o$ the t"o e:pressions, "ith a result o$ C& There is an established order "ith the priority o$ ea#h operator, and not only the arithmeti# ones .those "hose pre$eren#e #ome $rom mathemati#s0 but $or all the operators "hi#h #an appear in C//& *rom reatest to lo"est priority, the priority order is as $ollo"s: /e"el 1 2 Operator &escription s#ope post$i: unary .pre$i:0 indire#tion and re$eren#e .pointers0 unary si n operator type #astin pointer1to1member multipli#ati%e additi%e shi$t relational e;uality bit"ise ',D bit"ise 8)+ bit"ise )+ lo i#al ',D lo i#al )+ #onditional assi nment #omma Drouping Le$t1to1 ri ht Le$t1to1 ri ht +i ht1to1 le$t +i ht1to1 le$t Le$t1to1 ri ht Le$t1to1 ri ht Le$t1to1 ri ht Le$t1to1 ri ht Le$t1to1 ri ht Le$t1to1 ri ht Le$t1to1 ri ht Le$t1to1 ri ht Le$t1to1 ri ht Le$t1to1 ri ht Le$t1to1 ri ht +i ht1to1 le$t +i ht1to1 le$t Le$t1to1 ri ht

AA () PQ F .> ++ .. dynamic/cast static/cast reinterpret/cast const/cast typeid ++ .. O si3eof ne( delete % M + .

G @ ! 4 8 9 10 11 12 13 1G 1@ 1! 14 18

(type) F% .>% % / L + . << >> < > <* >* ** M H N MM NN IA * %* /* L* +* .* >>* <<* M* H* N* 0 *

(roupin de$ines the pre#eden#e order in "hi#h operators are e%aluated in the #ase that there are se%eral operators o$ the same le%el in an e:pression& 'll these pre#eden#e le%els $or operators #an be manipulated or be#ome more le ible by remo%in possible ambi uities usin parentheses si ns ( and ), as in this e:ample:

a * + + E L ,;
mi ht be "ritten either as:

a * + + (E L ,);
or

a * (+ + E) L ,;
dependin on the operation that "e "ant to per$orm& >o i$ you "ant to "rite #ompli#ated e:pressions and you are not #ompletely sure o$ the pre#eden#e le%els, al"ays in#lude parentheses& 2t "ill also be#ome a #ode easier to read&

!asic (nput5Output

Published by Juan Soulie


Last update on ,o% 1!, 2004 at 9:14am UTC

Until no", the e:ample pro rams o$ pre%ious se#tions pro%ided %ery little intera#tion "ith the user, i$ any at all& Usin the standard input and output library, "e "ill be able to intera#t "ith the user by printin messa es on the s#reen and ettin the userCs input $rom the -eyboard& C// uses a #on%enient abstra#tion #alled streams to per$orm input and output operations in se;uential media su#h as the s#reen or the -eyboard& ' stream is an ob?e#t "here a pro ram #an either insert or e:tra#t #hara#ters toH$rom it& =e do not really need to #are about many spe#i$i#ations about the physi#al media asso#iated "ith the stream 1 "e only need to -no" it "ill a##ept or pro%ide #hara#ters se;uentialy& The standard C// library in#ludes the header $ile iostream, "here the standard input and output stream ob?e#ts are de#lared&

Standard Output 0cout2


6y de$ault, the standard output o$ a pro ram is the s#reen, and the C// stream ob?e#t de$ined to a##ess it is cout&

cout is used in #on?un#tion "ith the insertion operator, "hi#h is "ritten as << .t"o <less than< si ns0& cout << "<utput sentence"; // prints <utput sentence on screen cout << -,!; // prints num&er -,! on screen cout << 1; // prints t)e content of 1 on screen
The << operator inserts the data that $ollo"s it into the stream pre#edin it& 2n the e:amples abo%e it inserted the #onstant strin <utput sentence, the numeri#al #onstant -,! and %ariable 1 into the standard output stream cout& ,oti#e that the senten#e in the $irst instru#tion is en#losed bet"een double ;uotes ."0 be#ause it is a #onstant strin o$ #hara#ters& =hene%er "e "ant to use #onstant strin s o$ #hara#ters "e must en#lose them bet"een double ;uotes . "0 so that they #an be #learly distin uished $rom %ariable names& *or e:ample, these t"o senten#es ha%e %ery di$$erent results:

cout << "Hello"; cout << Hello;

// prints Hello // prints t)e content of Hello 2aria&le

The insertion operator .<<0 may be used more than on#e in a sin le statement:

cout << "Hello0 " << "# am " << "a C++ statement";
This last statement "ould print the messa e Hello0 # am a C++ statement on the s#reen& The utility o$ repeatin the insertion operator .<<0 is demonstrated "hen "e "ant to print out a #ombination o$ %ariables and #onstants or more than one %ariable:

cout << "Hello0 # am " << age << " years old and my 3ipcode is " << 3ipcode;
2$ "e assume the age %ariable to #ontain the %alue ,B and the 3ipcode %ariable to #ontain G!!CB the output o$ the pre%ious statement "ould be:

Hello0 # am ,B years old and my 3ipcode is G!!CB


2t is important to noti#e that cout does not add a line brea- a$ter its output unless "e e:pli#itly indi#ate it, there$ore, the $ollo"in statements:

cout << ":)is is a sentenceF"; cout << ":)is is anot)er sentenceF";


"ill be sho"n on the s#reen one $ollo"in the other "ithout any line brea- bet"een them:

:)is is a sentenceF:)is is anot)er sentenceF


e%en thou h "e had "ritten them in t"o di$$erent insertions into cout& 2n order to per$orm a line brea- on the output "e must e:pli#itly insert a ne"1line #hara#ter into cout& 2n C// a ne"1line #hara#ter #an be spe#i$ied as Jn .ba#-slash, n0:

cout << "Rirst sentenceFJn "; cout << "7econd sentenceFJn:)ird sentenceF";
This produ#es the $ollo"in output:

Rirst sentenceF 7econd sentenceF :)ird sentenceF


'dditionally, to add a ne"1line, you may also use the endl manipulator& *or e:ample:

cout << "Rirst sentenceF" << endl; cout << "7econd sentenceF" << endl;
"ould print out:

Rirst sentenceF 7econd sentenceF


The endl manipulator produ#es a ne"line #hara#ter, e:a#tly as the insertion o$ $Jn$ does, but it also has an additional beha%ior "hen it is used "ith bu$$ered streams: the bu$$er is $lushed& 'ny"ay, cout "ill be an unbu$$ered stream in most #ases, so you #an enerally use both the Jn es#ape #hara#ter and the endl manipulator in order to spe#i$y a ne" line "ithout any di$$eren#e in its beha%ior&

Standard (nput 0cin2%


The standard input de%i#e is usually the -eyboard& Eandlin the standard input in C// is done by applyin the o%erloaded operator o$ e:tra#tion .>>0 on the cin stream& The operator must be $ollo"ed by the %ariable that "ill store the data that is oin to be e:tra#ted $rom the stream& *or e:ample:

int age; cin >> age;


The $irst statement de#lares a %ariable o$ type int #alled age, and the se#ond one "aits $or an input $rom cin .the -eyboard0 in order to store it in this inte er %ariable&

cin #an only pro#ess the input $rom the -eyboard on#e the 56:85; -ey has been pressed& There$ore, e%en i$ you re;uest a sin le #hara#ter, the e:tra#tion $rom cin "ill not pro#ess the input until the user presses 56:85; a$ter the #hara#ter has been introdu#ed&
Aou must al"ays #onsider the type o$ the %ariable that you are usin as a #ontainer "ith cin e:tra#tions& 2$ you re;uest an inte er you "ill et an inte er, i$ you re;uest a #hara#ter you "ill et a #hara#ter and i$ you re;uest a strin o$ #hara#ters you "ill et a strin o$ #hara#ters&

// i/o e1ample

Klease enter an integer 2alueA E!,

#include <iostream> using namespace std; int main () { int i; cout << "Klease enter an integer 2alueA "; cin >> i; cout << ":)e 2alue you entered is " << i; cout << " and its dou&le is " << i%, << "FJn"; return !; "

:)e 2alue you entered is E!, and its dou&le is -B!BF

The user o$ a pro ram may be one o$ the $a#tors that enerate errors e%en in the simplest pro rams that use cin .li-e the one "e ha%e ?ust seen0& >in#e i$ you re;uest an inte er %alue and the user introdu#es a name ."hi#h enerally is a strin o$ #hara#ters0, the result may #ause your pro ram to misoperate sin#e it is not "hat "e "ere e:pe#tin $rom the user& >o "hen you use the data input pro%ided by cin e:tra#tions you "ill ha%e to trust that the user o$ your pro ram "ill be #ooperati%e and that heHshe "ill not introdu#e hisHher name or somethin similar "hen an inte er %alue is re;uested& ' little ahead, "hen "e see the stringstream #lass "e "ill see a possible solution $or the errors that #an be #aused by this type o$ user input& Aou #an also use #in to re;uest more than one datum input $rom the user:

cin >> a >> &;


is e;ui%alent to:

cin >> a; cin >> &;


2n both #ases the user must i%e t"o data, one $or %ariable a and another one $or %ariable & that may be separated by any %alid blan- separator: a spa#e, a tab #hara#ter or a ne"line&

cin and strings


=e #an use cin to et strin s "ith the e:tra#tion operator .>>0 as "e do "ith $undamental data type %ariables:

cin >> mystring;


Eo"e%er, as it has been said, cin e:tra#tion stops readin as soon as i$ $inds any blan- spa#e #hara#ter, so in this #ase "e "ill be able to et ?ust one "ord $or ea#h e:tra#tion& This beha%ior may or may not be "hat "e "antL $or e:ample i$ "e "ant to et a senten#e $rom the user, this e:tra#tion operation "ould not be use$ul& 2n order to et entire lines, "e #an use the $un#tion getline, "hi#h is the more re#ommendable "ay to et user input "ith cin:

// cin (it) strings #include <iostream> #include <string> using namespace std;

W)at$s your nameI Suan 7ouli Hello Suan 7ouliF W)at is your fa2orite teamI :)e #sotopes # li'e :)e #sotopes too

int main () { string mystr; cout << "W)at$s your nameI "; getline (cin0 mystr); cout << "Hello " << mystr << "FJn"; cout << "W)at is your fa2orite teamI "; getline (cin0 mystr); cout << "# li'e " << mystr << " too Jn"; return !; "
,oti#e ho" in both #alls to getline "e used the same strin identi$ier .mystr0& =hat the pro ram does in the se#ond #all is simply to repla#e the pre%ious #ontent by the ne" one that is introdu#ed&

stringstream
The standard header $ile <sstream> de$ines a #lass #alled stringstream that allo"s a strin 1based ob?e#t to be treated as a stream& This "ay "e #an per$orm e:tra#tion or insertion operations $romHto strin s, "hi#h is espe#ially use$ul to #on%ert strin s to numeri#al %alues and %i#e %ersa& *or e:ample, i$ "e "ant to e:tra#t an inte er $rom a strin "e #an "rite:

string mystr ("-,!B"); int myint; stringstream(mystr) >> myint;


This de#lares a string ob?e#t "ith a %alue o$ "-,!B", and an int ob?e#t& Then "e use stringstreamCs #onstru#tor to #onstru#t an ob?e#t o$ this type $rom the strin ob?e#t& 6e#ause "e #an use stringstream ob?e#ts as i$ they "ere streams, "e #an e:tra#t an inte er $rom it as "e "ould ha%e done on cin by applyin the e:tra#tor operator .>>0 on it $ollo"ed by a %ariable o$ type int& '$ter this pie#e o$ #ode, the %ariable myint "ill #ontain the numeri#al %alue -,!B&

// stringstreams #include <iostream> #include <string> #include <sstream> using namespace std; int main () { string mystr; float price*!; int 4uantity*!; cout << "6nter priceA "; getline (cin0mystr); stringstream(mystr) >> price; cout << "6nter 4uantityA "; getline (cin0mystr); stringstream(mystr) >> 4uantity; cout << ":otal priceA " << price%4uantity << endl; return !; "

6nter priceA ,,F,+ 6nter 4uantityA E :otal priceA -++FE+

2n this e:ample, "e a#;uire numeri# %alues $rom the standard input indire#tly& 2nstead o$ e:tra#tin numeri# %alues dire#tly $rom the standard input, "e et lines $rom the standard input . cin0 into a strin ob?e#t .mystr0, and then "e e:tra#t the inte er %alues $rom this strin into a %ariable o$ type int .4uantity0& Usin this method, instead o$ dire#t e:tra#tions o$ inte er %alues, "e ha%e more #ontrol o%er "hat happens "ith the input o$ numeri# %alues $rom the user, sin#e "e are separatin the pro#ess o$ obtainin input $rom the user ."e no" simply as- $or lines0 "ith the interpretation o$ that input& There$ore, this method is usually pre$erred to et numeri#al %alues $rom the user in all pro rams that are intensi%e in user input&

Control Structures

Published by Juan Soulie


Last update on 5ay 2, 2004 at 10:1Gpm UTC

' pro ram is usually not limited to a linear se;uen#e o$ instru#tions& Durin its pro#ess it may bi$ur#ate, repeat #ode or ta-e de#isions& *or that purpose, C// pro%ides #ontrol stru#tures that ser%e to spe#i$y "hat has to be done by our pro ram, "hen and under "hi#h #ir#umstan#es& =ith the introdu#tion o$ #ontrol stru#tures "e are oin to ha%e to introdu#e a ne" #on#ept: the compound-statement or block& ' blo#- is a roup o$ statements "hi#h are separated by semi#olons .L0 li-e all C// statements, but rouped to ether in a blo#- en#losed in bra#es: { ":

{ statement-; statement,; statementD; "


5ost o$ the #ontrol stru#tures that "e "ill see in this se#tion re;uire a eneri# statement as part o$ its synta:& ' statement #an be either a simple statement .a simple instru#tion endin "ith a semi#olon0 or a #ompound statement .se%eral instru#tions rouped in a blo#-0, li-e the one ?ust des#ribed& 2n the #ase that "e "ant the statement to be a simple statement, "e do not need to en#lose it in bra#es .{"0& 6ut in the #ase that "e "ant the statement to be a #ompound statement it must be en#losed bet"een bra#es .{"0, $ormin a blo#-&

Conditional structure) if and else


The if -ey"ord is used to e:e#ute a statement or blo#- only i$ a #ondition is $ul$illed& 2ts $orm is:

if (condition) statement
=here condition is the e:pression that is bein e%aluated& 2$ this #ondition is true, statement is e:e#uted& 2$ it is $alse, statement is i nored .not e:e#uted0 and the pro ram #ontinues ri ht a$ter this #onditional stru#ture& *or e:ample, the $ollo"in #ode $ra ment prints 1 is -!! only i$ the %alue stored in the 1 %ariable is indeed -!!:

if (1 ** -!!) cout << "1 is -!!";


2$ "e "ant more than a sin le statement to be e:e#uted in #ase that the #ondition is true "e #an spe#i$y a blo#- usin bra#es { ":

if (1 ** -!!) { cout << "1 is "; cout << 1; "


=e #an additionally spe#i$y "hat "e "ant to happen i$ the #ondition is not $ul$illed by usin the -ey"ord else& 2ts $orm used in #on?un#tion "ith if is:

if (condition) statement- else statement,


*or e:ample:

if (1 ** -!!) cout << "1 is -!!"; else cout << "1 is not -!!";

prints on the s#reen 1 is -!! i$ indeed 1 has a %alue o$ -!!, but i$ it has not 1and only i$ not1 it prints out 1 is not -!!& The if + else stru#tures #an be #on#atenated "ith the intention o$ %eri$yin a ran e o$ %alues& The $ollo"in e:ample sho"s its use tellin i$ the %alue #urrently stored in 1 is positi%e, ne ati%e or none o$ them .i&e& Dero0:

if (1 > !) cout << "1 else if (1 < cout << "1 else cout << "1

is positi2e"; !) is negati2e"; is !";

+emember that in #ase that "e "ant more than a sin le statement to be e:e#uted, "e must roup them in a blo#- by en#losin them in bra#es { "&

(teration structures 0loops2


Loops ha%e as purpose to repeat a statement a #ertain number o$ times or "hile a #ondition is $ul$illed&

'he Bhile loop


2ts $ormat is:

()ile (e1pression) statement


and its $un#tionality is simply to repeat statement "hile the #ondition set in e:pression is true& *or e:ample, "e are oin to ma-e a pro ram to #ountdo"n usin a "hile1loop:

// custom countdo(n using ()ile #include <iostream> using namespace std; int main () { int n; cout << "6nter t)e starting num&er > "; cin >> n; ()ile (n>!) { cout << n << "0 "; ..n; " cout << "R#56 Jn"; return !;

6nter t)e starting num&er > T T0 E0 C0 +0 B0 D0 ,0 -0 R#56

"

=hen the pro ram starts the user is prompted to insert a startin number $or the #ountdo"n& Then the ()ile loop be ins, i$ the %alue entered by the user $ul$ills the #ondition n>! .that n is reater than Dero0 the blo#- that $ollo"s the #ondition "ill be e:e#uted and repeated "hile the #ondition . n>!0 remains bein true&

The "hole pro#ess o$ the pre%ious pro ram #an be interpreted a##ordin to the $ollo"in s#ript .be innin in main0:

1. 2. 3.

User assi ns a %alue to n The "hile #ondition is #he#-ed .n>!0& 't this point there are t"o posibilities: I #ondition is true: statement is e:e#uted .to step 30 I #ondition is $alse: i nore statement and #ontinue a$ter it .to step @0 9:e#ute statement:

G& @&

cout << n << "0 "; ..n; .prints the %alue o$ n on the s#reen and de#reases n by -0

9nd o$ blo#-& +eturn automati#ally to step 2 Continue the pro ram ri ht a$ter the blo#-: print *2+9B and end pro ram&

=hen #reatin a "hile1loop, "e must al"ays #onsider that it has to end at some point, there$ore "e must pro%ide "ithin the blo#- some method to $or#e the #ondition to be#ome $alse at some point, other"ise the loop "ill #ontinue loopin $ore%er& 2n this #ase "e ha%e in#luded ..n; that de#reases the %alue o$ the %ariable that is bein e%aluated in the #ondition . n0 by one 1 this "ill e%entually ma-e the #ondition .n>!0 to be#ome $alse a$ter a #ertain number o$ loop iterations: to be more spe#i$i#, "hen n be#omes !, that is "here our "hile1loop and our #ountdo"n end& )$ #ourse this is su#h a simple a#tion $or our #omputer that the "hole #ountdo"n is per$ormed instantly "ithout any pra#ti#al delay bet"een numbers&

'he do Bhile loop


2ts $ormat is:

do statement ()ile (condition);


2ts $un#tionality is e:a#tly the same as the "hile loop, e:#ept that condition in the do1"hile loop is e%aluated a$ter the e:e#ution o$ statement instead o$ be$ore, rantin at least one e:e#ution o$ statement e%en i$ condition is ne%er $ul$illed& *or e:ample, the $ollo"in e:ample pro ram e#hoes any number you enter until you enter !&

// num&er ec)oer #include <iostream> using namespace std; int main () { unsigned long n; do { cout << "6nter num&er (! to end)A "; cin >> n; cout << "@ou enteredA " << n << "Jn"; " ()ile (n * !); return !; "

6nter num&er @ou enteredA 6nter num&er @ou enteredA 6nter num&er @ou enteredA

(! to end)A -,DB+ -,DB+ (! to end)A -C!,EE -C!,EE (! to end)A ! !

The do1"hile loop is usually used "hen the #ondition that has to determine the end o$ the loop is determined "ithin the loop statement itsel$, li-e in the pre%ious #ase, "here the user input "ithin the blo#- is "hat is used to determine i$ the loop has to end& 2n $a#t i$ you ne%er enter the %alue ! in the pre%ious e:ample you #an be prompted $or more numbers $ore%er&

'he for loop


2ts $ormat is:

for (initiali3ation; condition; increase) statement;


and its main $un#tion is to repeat statement "hile condition remains true, li-e the "hile loop& 6ut in addition, the for loop pro%ides spe#i$i# lo#ations to #ontain an initiali3ation statement and an increase statement& >o this loop is spe#ially desi ned to per$orm a repetiti%e a#tion "ith a #ounter "hi#h is initialiDed and in#reased on ea#h iteration& 2t "or-s in the $ollo"in "ay:

1. initiali3ation is e:e#uted& (enerally it is an initial %alue settin


This is e:e#uted only on#e&

$or a #ounter %ariable&

2. condition is #he#-ed& 2$ it is true the loop #ontinues, other"ise the loop ends and
statement is s-ipped .not e:e#uted0&

3. statement is e:e#uted& 's usual, it #an be either a sin


bra#es { "&

le statement or a blo#- en#losed in

4.

$inally, "hate%er is spe#i$ied in the increase $ield is e:e#uted and the loop ets ba#- to step 2&

Eere is an e:ample o$ #ountdo"n usin a $or loop:

// countdo(n using a for loop #include <iostream> using namespace std; int main () { for (int n*-!; n>!; n..) { cout << n << "0 "; " cout << "R#56 Jn"; return !; "

-!0 G0 T0 E0 C0 +0 B0 D0 ,0 -0 R#56

The initiali3ation and increase $ields are optional& They #an remain empty, but in all #ases the semi#olon si ns bet"een them must be "ritten& *or e:ample "e #ould "rite: for (;n<-!;) i$ "e "anted to spe#i$y no initialiDation and no in#reaseL or for (;n<-!;n++) i$ "e "anted to in#lude an in#rease $ield but no initialiDation .maybe be#ause the %ariable "as already initialiDed be$ore0& )ptionally, usin the #omma operator .00 "e #an spe#i$y more than one e:pression in any o$ the $ields in#luded in a for loop, li-e in initiali3ation, $or e:ample& The #omma operator .00 is an e:pression separator, it ser%es to separate more than one e:pression "here only one is enerally e:pe#ted& *or e:ample, suppose that "e "anted to initialiDe more than one %ariable in our loop:

for ( n*!0 i*-!! ; n *i ; n++0 i.. ) { // ()ate2er )ereFFF "


This loop "ill e:e#ute $or @0 times i$ neither n or i are modi$ied "ithin the loop:

n starts "ith a %alue o$ !, and i "ith -!!, the #ondition is n *i .that n is not e;ual to i0& 6e#ause n is in#reased by one and i de#reased by one, the loopCs #ondition "ill be#ome $alse a$ter the @0th loop, "hen both n and i "ill be e;ual to +!&

Jump statements%

'he breaE statement


Usin &rea' "e #an lea%e a loop e%en i$ the #ondition $or its end is not $ul$illed& 2t #an be used to end an in$inite loop, or to $or#e it to end be$ore its natural end& *or e:ample, "e are oin to stop the #ount do"n be$ore its natural end .maybe be#ause o$ an en ine #he#- $ailureQ0:

// &rea' loop e1ample #include <iostream> using namespace std; int main () { int n; for (n*-!; n>!; n..) { cout << n << "0 "; if (n**D) { cout << "countdo(n a&orted "; &rea'; " " return !; "

-!0 G0 T0 E0 C0 +0 B0 D0 countdo(n a&orted

'he continue statement


The continue statement #auses the pro ram to s-ip the rest o$ the loop in the #urrent iteration as i$ the end o$ the statement blo#- had been rea#hed, #ausin it to ?ump to the start o$ the $ollo"in iteration& *or e:ample, "e are oin to s-ip the number @ in our #ountdo"n:

// continue loop e1ample #include <iostream> using namespace std; int main () { for (int n*-!; n>!; n..) { if (n**+) continue; cout << n << "0 "; " cout << "R#56 Jn"; return !; "

-!0 G0 T0 E0 C0 B0 D0 ,0 -0 R#56

'he goto statement


goto allo"s to ma-e an absolute ?ump to another point in the pro ram& Aou should use this $eature
"ith #aution sin#e its e:e#ution #auses an un#onditional ?ump i norin any type o$ nestin limitations& The destination point is identi$ied by a label, "hi#h is then used as an ar ument $or the oto statement& ' label is made o$ a %alid identi$ier $ollo"ed by a #olon .A0& (enerally spea-in , this instru#tion has no #on#rete use in stru#tured or ob?e#t oriented pro rammin aside $rom those that lo"1le%el pro rammin $ans may $ind $or it& *or e:ample, here is our #ountdo"n loop usin goto:

// goto loop e1ample #include <iostream> using namespace std; int main () { int n*-!; loopA cout << n << "0 "; n..; if (n>!) goto loop; cout << "R#56 Jn"; return !; "

-!0 G0 T0 E0 C0 +0 B0 D0 ,0 -0 R#56

'he e<it function


e1it is a $un#tion de$ined in the cstdli& library&
The purpose o$ e1it is to terminate the #urrent pro ram "ith a spe#i$i# e:it #ode& 2ts prototype is:

2oid e1it (int e1itcode);


The e1itcode is used by some operatin systems and may be used by #allin pro rams& 6y #on%ention, an e:it #ode o$ ! means that the pro ram $inished normally and any other %alue means that some error or une:pe#ted results happened&

'he selecti"e structure) sBitch%


The synta: o$ the s"it#h statement is a bit pe#uliar& 2ts ob?e#ti%e is to #he#- se%eral possible #onstant %alues $or an e:pression& >omethin similar to "hat "e did at the be innin o$ this se#tion "ith the #on#atenation o$ se%eral if and else if instru#tions& 2ts $orm is the $ollo"in :

s(itc) (e1pression) { case constant-A group of statements -; &rea'; case constant,A group of statements ,; &rea'; F F F defaultA default group of statements "

2t "or-s in the $ollo"in "ay: s"it#h e%aluates e1pression and #he#-s i$ it is e;ui%alent to constant-, i$ it is, it e:e#utes group of statements - until it $inds the &rea' statement& =hen it $inds this &rea' statement the pro ram ?umps to the end o$ the s(itc) sele#ti%e stru#ture& 2$ e:pression "as not e;ual to constant- it "ill be #he#-ed a ainst constant,& 2$ it is e;ual to this, it "ill e:e#ute group of statements , until a brea- -ey"ord is $ound, and then "ill ?ump to the end o$ the s(itc) sele#ti%e stru#ture& *inally, i$ the %alue o$ e1pression did not mat#h any o$ the pre%iously spe#i$ied #onstants .you #an in#lude as many case labels as %alues you "ant to #he#-0, the pro ram "ill e:e#ute the statements in#luded a$ter the defaultA label, i$ it e:ists .sin#e it is optional0& 6oth o$ the $ollo"in #ode $ra ments ha%e the same beha%ior: sBitch e<ample if else e=ui"alent

s(itc) (1) { if (1 ** -) { case -A cout << "1 is -"; cout << "1 is -"; " &rea'; else if (1 ** ,) { case ,A cout << "1 is ,"; cout << "1 is ,"; " &rea'; else { defaultA cout << "2alue of 1 un'no(n"; cout << "2alue of 1 un'no(n"; " "
The s(itc) statement is a bit pe#uliar "ithin the C// lan ua e be#ause it uses labels instead o$ blo#-s& This $or#es us to put &rea' statements a$ter the roup o$ statements that "e "ant to be e:e#uted $or a spe#i$i# #ondition& )ther"ise the remainder statements 1in#ludin those #orrespondin to other labels1 "ill also be e:e#uted until the end o$ the s(itc) sele#ti%e blo#- or a &rea' statement is rea#hed& *or e:ample, i$ "e did not in#lude a &rea' statement a$ter the $irst roup $or #ase one, the pro ram "ill not automati#ally ?ump to the end o$ the s(itc) sele#ti%e blo#- and it "ould #ontinue e:e#utin the rest o$ statements until it rea#hes either a &rea' instru#tion or the end o$ the s(itc) sele#ti%e blo#-& This ma-es unne#essary to in#lude bra#es { " surroundin the statements $or ea#h o$ the #ases, and it #an also be use$ul to e:e#ute the same blo#- o$ instru#tions $or di$$erent possible %alues $or the e:pression bein e%aluated& *or e:ample:

s(itc) (1) { case -A case ,A case DA cout << "1 is -0 , or D"; &rea'; defaultA cout << "1 is not -0 , nor D"; "
,oti#e that s"it#h #an only be used to #ompare an e:pression a ainst #onstants& There$ore "e #annot put %ariables as labels .$or e:ample case nA "here n is a %ariable0 or ran es .case (-FFD)A0 be#ause they are not %alid C// #onstants& 2$ you need to #he#- ran es or %alues that are not #onstants, use a #on#atenation o$ if and else if statements&

*unctions 0(2

Published by Juan Soulie


Last update on 5ay 23, 2004 at !:11pm UTC

Usin $un#tions "e #an stru#ture our pro rams in a more modular "ay, a##essin all the potential that stru#tured pro rammin #an o$$er to us in C//& ' $un#tion is a roup o$ statements that is e:e#uted "hen it is #alled $rom some point o$ the pro ram& The $ollo"in is its $ormat:

type name ( parameter-0 parameter,0 FFF) { statements "


"here:

type is the data type spe#i$ier o$ the data returned by the $un#tion& name is the identi$ier by "hi#h it "ill be possible to #all the $un#tion& parameters .as many as needed0: 9a#h parameter #onsists o$ a data type spe#i$ier $ollo"ed by an identi$ier, li-e any re ular %ariable de#laration .$or e:ample: int 10 and "hi#h a#ts
"ithin the $un#tion as a re ular lo#al %ariable& They allo" to pass ar uments to the $un#tion "hen it is #alled& The di$$erent parameters are separated by #ommas& statements is the $un#tionCs body& 2t is a blo#- o$ statements surrounded by bra#es { "&

Eere you ha%e the $irst $un#tion e:ample:

// function e1ample #include <iostream> using namespace std; int addition (int a0 int &) { int r; r*a+&; return (r); " int main () { int 3; 3 * addition (+0D); cout << ":)e result is " << 3; return !; "

:)e result is T

2n order to e:amine this #ode, $irst o$ all remember somethin said at the be innin o$ this tutorial: a C// pro ram al"ays be ins its e:e#ution by the main $un#tion& >o "e "ill be in there& =e #an see ho" the main $un#tion be ins by de#larin the %ariable 3 o$ type int& +i ht a$ter that, "e see a #all to a $un#tion #alled addition& Payin attention "e "ill be able to see the similarity bet"een the stru#ture o$ the #all to the $un#tion and the de#laration o$ the $un#tion itsel$ some #ode lines abo%e:

The parameters and ar uments ha%e a #lear #orresponden#e& =ithin the main $un#tion "e #alled to addition passin t"o %alues: + and D, that #orrespond to the int a and int & parameters de#lared $or $un#tion addition& 't the point at "hi#h the $un#tion is #alled $rom "ithin main, the #ontrol is lost by main and passed to $un#tion addition& The %alue o$ both ar uments passed in the #all . + and D0 are #opied to the lo#al %ariables int a and int & "ithin the $un#tion& *un#tion addition de#lares another lo#al %ariable .int r0, and by means o$ the e:pression r*a+&, it assi ns to r the result o$ a plus && 6e#ause the a#tual parameters passed $or a and & are + and D respe#ti%ely, the result is T& The $ollo"in line o$ #ode:

return (r);
$inaliDes $un#tion addition, and returns the #ontrol ba#- to the $un#tion that #alled it in the $irst pla#e .in this #ase, main0& 't this moment the pro ram $ollo"s it re ular #ourse $rom the same point at "hi#h it "as interrupted by the #all to addition& 6ut additionally, be#ause the return statement in $un#tion addition spe#i$ied a %alue: the #ontent o$ %ariable r .return (r);0, "hi#h at that moment had a %alue o$ T& This %alue be#omes the %alue o$ e%aluatin the $un#tion #all&

>o bein the %alue returned by a $un#tion the %alue i%en to the $un#tion #all itsel$ "hen it is e%aluated, the %ariable 3 "ill be set to the %alue returned by addition (+0 D), that is T& To e:plain it another "ay, you #an ima ine that the #all to a $un#tion . addition (+0D)0 is literally repla#ed by the %alue it returns .T0& The $ollo"in line o$ #ode in main is:

cout << ":)e result is " << 3;


That, as you may already e:pe#t, produ#es the printin o$ the result on the s#reen&

Scope of "ariables
The s#ope o$ %ariables de#lared "ithin a $un#tion or any other inner blo#- is only their o"n $un#tion or their o"n blo#- and #annot be used outside o$ them& *or e:ample, in the pre%ious e:ample it "ould ha%e been impossible to use the %ariables a, & or r dire#tly in $un#tion main sin#e they "ere %ariables lo#al to $un#tion addition& 'lso, it "ould ha%e been impossible to use the %ariable 3 dire#tly "ithin $un#tion addition, sin#e this "as a %ariable lo#al to the $un#tion main&

There$ore, the s#ope o$ lo#al %ariables is limited to the same blo#- le%el in "hi#h they are de#lared& ,e%ertheless, "e also ha%e the possibility to de#lare lobal %ariablesL These are %isible $rom any point o$ the #ode, inside and outside all $un#tions& 2n order to de#lare lobal %ariables you simply ha%e to de#lare the %ariable outside any $un#tion or blo#-L that means, dire#tly in the body o$ the pro ram& 'nd here is another e:ample about $un#tions:

// function e1ample #include <iostream> using namespace std; int su&traction (int a0 int &) { int r; r*a.&; return (r); " int main () { int 1*+0 y*D0 3; 3 * su&traction (E0,); cout << ":)e first result is " << 3 << $Jn$; cout << ":)e second result is " << su&traction (E0,) << $Jn$; cout << ":)e t)ird result is " << su&traction (10y) << $Jn$; 3* B + su&traction (10y);

:)e :)e :)e :)e

first result is + second result is + t)ird result is , fourt) result is C

cout << ":)e fourt) result is " << 3 << $Jn$; return !; "
2n this #ase "e ha%e #reated a $un#tion #alled su&traction& The only thin that this $un#tion does is to subtra#t both passed parameters and to return the result& ,e%ertheless, i$ "e e:amine $un#tion main "e "ill see that "e ha%e made se%eral #alls to $un#tion su&traction& =e ha%e used some di$$erent #allin methods so that you see other "ays or moments "hen a $un#tion #an be #alled& 2n order to $ully understand these e:amples you must #onsider on#e a ain that a #all to a $un#tion #ould be repla#ed by the %alue that the $un#tion #all itsel$ is oin to return& *or e:ample, the $irst #ase .that you should already -no" be#ause it is the same pattern that "e ha%e used in pre%ious e:amples0:

3 * su&traction (E0,); cout << ":)e first result is " << 3;


2$ "e repla#e the $un#tion #all by the %alue it returns .i&e&, +0, "e "ould ha%e:

3 * +; cout << ":)e first result is " << 3;


's "ell as

cout << ":)e second result is " << su&traction (E0,);


has the same result as the pre%ious #all, but in this #ase "e made the #all to su&traction dire#tly as an insertion parameter $or cout& >imply #onsider that the result is the same as i$ "e had "ritten:

cout << ":)e second result is " << +;


sin#e + is the %alue returned by su&traction (E0,)& 2n the #ase o$:

cout << ":)e t)ird result is " << su&traction (10y);


The only ne" thin that "e introdu#ed is that the parameters o$ su&traction are %ariables instead o$ #onstants& That is per$e#tly %alid& 2n this #ase the %alues passed to $un#tion su&traction are the %alues o$ 1 and y, that are + and D respe#ti%ely, i%in , as result& The $ourth #ase is more o$ the same& >imply note that instead o$:

3 * B + su&traction (10y);
"e #ould ha%e "ritten:

3 * su&traction (10y) + B;
"ith e:a#tly the same result& 2 ha%e s"it#hed pla#es so you #an see that the semi#olon si n . ;0 oes at the end o$ the "hole statement& 2t does not ne#essarily ha%e to o ri ht a$ter the $un#tion #all& The

e:planation mi ht be on#e a ain that you ima ine that a $un#tion #an be repla#ed by its returned %alue:

3 * B + ,; 3 * , + B;

*unctions Bith no type% 'he use of "oid%


2$ you remember the synta: o$ a $un#tion de#laration:

type name ( argument-0 argument, FFF) statement


you "ill see that the de#laration be ins "ith a type, that is the type o$ the $un#tion itsel$ .i&e&, the type o$ the datum that "ill be returned by the $un#tion "ith the return statement0& 6ut "hat i$ "e "ant to return no %alueQ 2ma ine that "e "ant to ma-e a $un#tion ?ust to sho" a messa e on the s#reen& =e do not need it to return any %alue& 2n this #ase "e should use the 2oid type spe#i$ier $or the $un#tion& This is a spe#ial spe#i$ier that indi#ates absen#e o$ type&

// 2oid function e1ample #include <iostream> using namespace std; 2oid printmessage () { cout << "#$m a function "; " int main () { printmessage (); return !; "

#$m a function

2oid #an also be used in the $un#tionCs parameter list to e:pli#itly spe#i$y that "e "ant the $un#tion to ta-e no a#tual parameters "hen it is #alled& *or e:ample, $un#tion printmessage #ould ha%e been
de#lared as:

2oid printmessage (2oid) { cout << "#$m a function "; "


'lthou h it is optional to spe#i$y 2oid in the parameter list& 2n C//, a parameter list #an simply be le$t blan- i$ "e "ant a $un#tion "ith no parameters& =hat you must al"ays remember is that the $ormat $or #allin a $un#tion in#ludes spe#i$yin its name and en#losin its parameters bet"een parentheses& The non1e:isten#e o$ parameters does not e:empt us $rom the obli ation to "rite the parentheses& *or that reason the #all to printmessage is:

printmessage ();
The parentheses #learly indi#ate that this is a #all to a $un#tion and not the name o$ a %ariable or some other C// statement& The $ollo"in #all "ould ha%e been in#orre#t:

printmessage;

*unctions 0((2

Published by Juan Soulie


Last update on 5ay 1G, 2004 at 8:30am UTC

Arguments passed by "alue and by reference%


Until no", in all the $un#tions "e ha%e seen, the ar uments passed to the $un#tions ha%e been passed by value& This means that "hen #allin a $un#tion "ith parameters, "hat "e ha%e passed to the $un#tion "ere #opies o$ their %alues but ne%er the %ariables themsel%es& *or e:ample, suppose that "e #alled our $irst $un#tion addition usin the $ollo"in #ode:

int 1*+0 y*D0 3; 3 * addition ( 1 0 y );


=hat "e did in this #ase "as to #all to $un#tion addition passin the %alues o$ 1 and y, i&e& + and D respe#ti%ely, but not the %ariables 1 and y themsel%es&

This "ay, "hen the $un#tion addition is #alled, the %alue o$ its lo#al %ariables a and & be#ome + and D respe#ti%ely, but any modi$i#ation to either a or & "ithin the $un#tion addition "ill not ha%e any e$$e#t in the %alues o$ 1 and y outside it, be#ause %ariables 1 and y "ere not themsel%es passed to the $un#tion, but only #opies o$ their %alues at the moment the $un#tion "as #alled& 6ut there mi ht be some #ases "here you need to manipulate $rom inside a $un#tion the %alue o$ an e:ternal %ariable& *or that purpose "e #an use ar uments passed by re$eren#e, as in the $un#tion dupli#ate o$ the $ollo"in e:ample:

// passing parameters &y reference #include <iostream> using namespace std; 2oid duplicate (intM a0 intM &0 intM c) { a%*,; &%*,; c%*,; " int main () { int 1*-0 y*D0 3*E; duplicate (10 y0 3); cout << "1*" << 1 << "0 y*" << y << "0 3*" << 3; return !; "

1*,0 y*C0 3*-B

The $irst thin that should #all your attention is that in the de#laration o$ duplicate the type o$ ea#h parameter "as $ollo"ed by an ampersand si n .M0& This ampersand is "hat spe#i$ies that their #orrespondin ar uments are to be passed by reference instead o$ by value&

=hen a %ariable is passed by re$eren#e "e are not passin a #opy o$ its %alue, but "e are someho" passin the %ariable itsel$ to the $un#tion and any modi$i#ation that "e do to the lo#al %ariables "ill ha%e an e$$e#t in their #ounterpart %ariables passed as ar uments in the #all to the $un#tion&

To e:plain it in another "ay, "e asso#iate a, & and c "ith the ar uments passed on the $un#tion #all .1, y and 30 and any #han e that "e do on a "ithin the $un#tion "ill a$$e#t the %alue o$ 1 outside it& 'ny #han e that "e do on & "ill a$$e#t y, and the same "ith c and 3& That is "hy our pro ramCs output, that sho"s the %alues stored in 1, y and 3 a$ter the #all to duplicate, sho"s the %alues o$ all the three %ariables o$ main doubled& 2$ "hen de#larin the $ollo"in $un#tion:

2oid duplicate (intM a0 intM &0 intM c)


"e had de#lared it this "ay:

2oid duplicate (int a0 int &0 int c)


i&e&, "ithout the ampersand si ns .M0, "e "ould ha%e not passed the %ariables by re$eren#e, but a #opy o$ their %alues instead, and there$ore, the output on s#reen o$ our pro ram "ould ha%e been the %alues o$ 1, y and 3 "ithout ha%in been modi$ied& Passin by re$eren#e is also an e$$e#ti%e "ay to allo" a $un#tion to return more than one %alue& *or e:ample, here is a $un#tion that returns the pre%ious and ne:t numbers o$ the $irst parameter passed&

// more t)an one returning 2alue #include <iostream> using namespace std; 2oid pre2ne1t (int 10 intM pre20 intM ne1t) { pre2 * 1.-; ne1t * 1+-; " int main () { int 1*-!!0 y0 3; pre2ne1t (10 y0 3); cout << "Kre2ious*" << y << "0 ;e1t*" << 3; return !; "

Kre2ious*GG0 ;e1t*-!-

&efault "alues in parameters%


=hen de#larin a $un#tion "e #an spe#i$y a de$ault %alue $or ea#h parameter& This %alue "ill be used i$ the #orrespondin ar ument is le$t blan- "hen #allin to the $un#tion& To do that, "e simply ha%e to use the assi nment operator and a %alue $or the ar uments in the $un#tion de#laration& 2$ a %alue $or

that parameter is not passed "hen the $un#tion is #alled, the de$ault %alue is used, but i$ a %alue is spe#i$ied this de$ault %alue is i nored and the passed %alue is used instead& *or e:ample:

// default 2alues in functions #include <iostream> using namespace std; int di2ide (int a0 int &*,) { int r; r*a/&; return (r); " int main () { cout << di2ide (-,); cout << endl; cout << di2ide (,!0B); return !; "

C +

's "e #an see in the body o$ the pro ram there are t"o #alls to $un#tion di2ide& 2n the $irst one:

di2ide (-,)
"e ha%e only spe#i$ied one ar ument, but the $un#tion di2ide allo"s up to t"o& >o the $un#tion di2ide has assumed that the se#ond parameter is , sin#e that is "hat "e ha%e spe#i$ied to happen i$ this parameter "as not passed .noti#e the $un#tion de#laration, "hi#h $inishes "ith int &*,, not ?ust int &0& There$ore the result o$ this $un#tion #all is C .-,/,0& 2n the se#ond #all:

di2ide (,!0B)
there are t"o parameters, so the de$ault %alue $or & .int &*,0 is i nored and & ta-es the %alue passed as ar ument, that is B, ma-in the result returned e;ual to + .,!/B0&

O"erloaded functions%
2n C// t"o di$$erent $un#tions #an ha%e the same name i$ their parameter types or number are di$$erent& That means that you #an i%e the same name to more than one $un#tion i$ they ha%e either a di$$erent number o$ parameters or di$$erent types in their parameters& *or e:ample:

// o2erloaded function #include <iostream> using namespace std; int operate (int a0 int &) { return (a%&); " float operate (float a0 float &) { return (a/&); " int main () {

-! ,F+

int 1*+0y*,; float n*+F!0m*,F!; cout << operate (10y); cout << "Jn"; cout << operate (n0m); cout << "Jn"; return !; "
2n this #ase "e ha%e de$ined t"o $un#tions "ith the same name, operate, but one o$ them a##epts t"o parameters o$ type int and the other one a##epts them o$ type float& The #ompiler -no"s "hi#h one to #all in ea#h #ase by e:aminin the types passed as ar uments "hen the $un#tion is #alled& 2$ it is #alled "ith t"o ints as its ar uments it #alls to the $un#tion that has t"o int parameters in its prototype and i$ it is #alled "ith t"o $loats it "ill #all to the one "hi#h has t"o float parameters in its prototype& 2n the $irst #all to operate the t"o ar uments passed are o$ type int, there$ore, the $un#tion "ith the $irst prototype is #alledL This $un#tion returns the result o$ multiplyin both parameters& =hile the se#ond #all passes t"o ar uments o$ type float, so the $un#tion "ith the se#ond prototype is #alled& This one has a di$$erent beha%ior: it di%ides one parameter by the other& >o the beha%ior o$ a #all to operate depends on the type o$ the ar uments passed be#ause the $un#tion has been overloaded& ,oti#e that a $un#tion #annot be o%erloaded only by its return type& 't least one o$ its parameters must ha%e a di$$erent type&

inline functions%
The inline spe#i$ier indi#ates the #ompiler that inline substitution is pre$erred to the usual $un#tion #all me#hanism $or a spe#i$i# $un#tion& This does not #han e the beha%ior o$ a $un#tion itsel$, but is used to su est to the #ompiler that the #ode enerated by the $un#tion body is inserted at ea#h point the $un#tion is #alled, instead o$ bein inserted only on#e and per$orm a re ular #all to it, "hi#h enerally in%ol%es some additional o%erhead in runnin time& The $ormat $or its de#laration is:

inline type name ( arguments FFF ) { instructions FFF "


and the #all is ?ust li-e the #all to any other $un#tion& Aou do not ha%e to in#lude the inline -ey"ord "hen #allin the $un#tion, only in its de#laration& 5ost #ompilers already optimiDe #ode to enerate inline $un#tions "hen it is more #on%enient& This spe#i$ier only indi#ates the #ompiler that inline is pre$erred $or this $un#tion&

.ecursi"ity%
+e#ursi%ity is the property that $un#tions ha%e to be #alled by themsel%es& 2t is use$ul $or many tas-s, li-e sortin or #al#ulate the $a#torial o$ numbers& *or e:ample, to obtain the $a#torial o$ a number .nB0 the mathemati#al $ormula "ould be:

* n % (n.-) % (n.,) % (n.D) FFF % -

more #on#retely, @B .$a#torial o$ @0 "ould be:

* + % B % D % , % - * -,!

and a re#ursi%e $un#tion to #al#ulate this in C// #ould be:

// factorial calculator #include <iostream>

Klease type a num&erA G G * DC,TT!

using namespace std; long factorial (long a) { if (a > -) return (a % factorial (a.-)); else return (-); " int main () { long num&er; cout << "Klease type a num&erA "; cin >> num&er; cout << num&er << " * " << factorial (num&er); return !; "
,oti#e ho" in $un#tion factorial "e in#luded a #all to itsel$, but only i$ the ar ument passed "as reater than 1, sin#e other"ise the $un#tion "ould per$orm an in$inite re#ursi%e loop in "hi#h on#e it arri%ed to ! it "ould #ontinue multiplyin by all the ne ati%e numbers .probably pro%o-in a sta#o%er$lo" error on runtime0& This $un#tion has a limitation be#ause o$ the data type "e used in its desi n . long0 $or more simpli#ity& The results i%en "ill not be %alid $or %alues mu#h reater than 10B or 1@B, dependin on the system you #ompile it&

&eclaring functions%
Until no", "e ha%e de$ined all o$ the $un#tions be$ore the $irst appearan#e o$ #alls to them in the sour#e #ode& These #alls "ere enerally in $un#tion main "hi#h "e ha%e al"ays le$t at the end o$ the sour#e #ode& 2$ you try to repeat some o$ the e:amples o$ $un#tions des#ribed so $ar, but pla#in the $un#tion main be$ore any o$ the other $un#tions that "ere #alled $rom "ithin it, you "ill most li-ely obtain #ompilin errors& The reason is that to be able to #all a $un#tion it must ha%e been de#lared in some earlier point o$ the #ode, li-e "e ha%e done in all our e:amples& 6ut there is an alternati%e "ay to a%oid "ritin the "hole #ode o$ a $un#tion be$ore it #an be used in main or in some other $un#tion& This #an be a#hie%ed by de#larin ?ust a prototype o$ the $un#tion be$ore it is used, instead o$ the entire de$inition& This de#laration is shorter than the entire de$inition, but si ni$i#ant enou h $or the #ompiler to determine its return type and the types o$ its parameters& 2ts $orm is:

type name ( argument/type-0 argument/type,0 FFF);


2t is identi#al to a $un#tion de$inition, e:#ept that it does not in#lude the body o$ the $un#tion itsel$ .i&e&, the $un#tion statements that in normal de$initions are en#losed in bra#es { "0 and instead o$ that "e end the prototype de#laration "ith a mandatory semi#olon . ;0& The parameter enumeration does not need to in#lude the identi$iers, but only the type spe#i$iers& The in#lusion o$ a name $or ea#h parameter as in the $un#tion de$inition is optional in the prototype de#laration& *or e:ample, "e #an de#lare a $un#tion #alled protofunction "ith t"o int parameters "ith any o$ the $ollo"in de#larations:

int protofunction (int first0 int second); int protofunction (int0 int);

'ny"ay, in#ludin a name $or ea#h %ariable ma-es the prototype more le ible&

// declaring functions prototypes #include <iostream> using namespace std; 2oid odd (int a); 2oid e2en (int a); int main () { int i; do { cout << ":ype a num&er (! to e1it)A "; cin >> i; odd (i); " ()ile (i *!); return !; " 2oid odd (int a) { if ((aL,) *!) cout << ";um&er is oddFJn"; else e2en (a); " 2oid e2en (int a) { if ((aL,)**!) cout << ";um&er is e2enFJn"; else odd (a); "

:ype a ;um&er :ype a ;um&er :ype a ;um&er :ype a ;um&er

num&er (! is oddF num&er (! is e2enF num&er (! is e2enF num&er (! is e2enF

to e1it)A G to e1it)A C to e1it)A -!D! to e1it)A !

This e:ample is indeed not an e:ample o$ e$$i#ien#y& 2 am sure that at this point you #an already ma-e a pro ram "ith the same result, but usin only hal$ o$ the #ode lines that ha%e been used in this e:ample& 'ny"ay this e:ample illustrates ho" prototypin "or-s& 5oreo%er, in this #on#rete e:ample the prototypin o$ at least one o$ the t"o $un#tions is ne#essary in order to #ompile the #ode "ithout errors& The $irst thin s that "e see are the de#laration o$ $un#tions odd and e2en:

2oid odd (int a); 2oid e2en (int a);


This allo"s these $un#tions to be used be$ore they are de$ined, $or e:ample, in main, "hi#h no" is lo#ated "here some people $ind it to be a more lo i#al pla#e $or the start o$ a pro ram: the be innin o$ the sour#e #ode& 'ny"ay, the reason "hy this pro ram needs at least one o$ the $un#tions to be de#lared be$ore it is de$ined is be#ause in odd there is a #all to e2en and in e2en there is a #all to odd& 2$ none o$ the t"o $un#tions had been pre%iously de#lared, a #ompilation error "ould happen, sin#e either odd "ould not not be %isible $rom e2en .be#ause it has still not been de#lared0, or e2en "ould not be %isible $rom odd .$or the same reason0&

Ea%in the prototype o$ all $un#tions to ether in the same pla#e "ithin the sour#e #ode is $ound pra#ti#al by some pro rammers, and this #an be easily a#hie%ed by de#larin all $un#tions prototypes at the be innin o$ a pro ram&

Arrays

Published by Juan Soulie


Last update on *eb @, 2004 at 9:G0am UTC

'n array is a series o$ elements o$ the same type pla#ed in #onti uous memory lo#ations that #an be indi%idually re$eren#ed by addin an inde: to a uni;ue identi$ier& That means that, $or e:ample, "e #an store @ %alues o$ type int in an array "ithout ha%in to de#lare @ di$$erent %ariables, ea#h one "ith a di$$erent identi$ier& 2nstead o$ that, usin an array "e #an store @ di$$erent %alues o$ the same type, int $or e:ample, "ith a uni;ue identi$ier& *or e:ample, an array to #ontain @ inte er %alues o$ type int #alled &illy #ould be represented li-e this:

"here ea#h blan- panel represents an element o$ the array, that in this #ase are inte er %alues o$ type int& These elements are numbered $rom ! to B sin#e in arrays the $irst inde: is al"ays !, independently o$ its len th& Li-e a re ular %ariable, an array must be de#lared be$ore it is used& ' typi#al de#laration $or an array in C// is:

type name PelementsQ;


"here type is a %alid type .li-e int, float&&&0, name is a %alid identi$ier and the elements $ield ."hi#h is al"ays en#losed in s;uare bra#-ets PQ0, spe#i$ies ho" many o$ these elements the array has to #ontain& There$ore, in order to de#laare an array #alled &illy as the one sho"n in the abo%e dia ram it is as simple as:

int &illy P+Q;


+O'>: The elements $ield "ithin bra#-ets PQ "hi#h represents the number o$ elements the array is oin to hold, must be a #onstant %alue, sin#e arrays are blo#-s o$ non1dynami# memory "hose siDe must be determined be$ore e:e#ution& 2n order to #reate arrays "ith a %ariable len th dynami# memory is needed, "hi#h is e:plained later in these tutorials&

(nitiali,ing arrays%
=hen de#larin a re ular array o$ lo#al s#ope ."ithin a $un#tion, $or e:ample0, i$ "e do not spe#i$y other"ise, its elements "ill not be initialiDed to any %alue by de$ault, so their #ontent "ill be undetermined until "e store some %alue in them& The elements o$ lobal and stati# arrays, on the other hand, are automati#ally initialiDed "ith their de$ault %alues, "hi#h $or all $undamental types this means they are $illed "ith Deros& 2n both #ases, lo#al and lobal, "hen "e de#lare an array, "e ha%e the possibility to assi n initial %alues to ea#h one o$ its elements by en#losin the %alues in bra#es { "& *or e:ample:

int &illy P+Q * { -C0 ,0 EE0 B!0 -,!E- ";


This de#laration "ould ha%e #reated an array li-e this:

The amount o$ %alues bet"een bra#es { " must not be lar er than the number o$ elements that "e de#lare $or the array bet"een s;uare bra#-ets P Q& *or e:ample, in the e:ample o$ array &illy "e ha%e de#lared that it has @ elements and in the list o$ initial %alues "ithin bra#es { " "e ha%e spe#i$ied @ %alues, one $or ea#h element& =hen an initialiDation o$ %alues is pro%ided $or an array, C// allo"s the possibility o$ lea%in the s;uare bra#-ets empty P Q& 2n this #ase, the #ompiler "ill assume a siDe $or the array that mat#hes the number o$ %alues in#luded bet"een bra#es { ":

int &illy PQ * { -C0 ,0 EE0 B!0 -,!E- ";


'$ter this de#laration, array &illy "ould be @ ints lon , sin#e "e ha%e pro%ided @ initialiDation %alues&

Accessing the "alues of an array%


2n any point o$ a pro ram in "hi#h an array is %isible, "e #an a##ess the %alue o$ any o$ its elements indi%idually as i$ it "as a normal %ariable, thus bein able to both read and modi$y its %alue& The $ormat is as simple as:

namePinde1Q
*ollo"in the pre%ious e:amples in "hi#h &illy had @ elements and ea#h o$ those elements "as o$ type int, the name "hi#h "e #an use to re$er to ea#h element is the $ollo"in :

*or e:ample, to store the %alue E+ in the third element o$ &illy, "e #ould "rite the $ollo"in statement:

&illyP,Q * E+;
and, $or e:ample, to pass the %alue o$ the third element o$ &illy to a %ariable #alled a, "e #ould "rite:

a * &illyP,Q;
There$ore, the e:pression &illyP,Q is $or all purposes li-e a %ariable o$ type int& ,oti#e that the third element o$ &illy is spe#i$ied &illyP,Q, sin#e the $irst one is &illyP!Q, the se#ond one is &illyP-Q, and there$ore, the third one is &illyP,Q& 6y this same reason, its last element is &illyPBQ& There$ore, i$ "e "rite billyR@S, "e "ould be a##essin the si:th element o$ &illy and there$ore e:#eedin the siDe o$ the array& 2n C// it is synta#ti#ally #orre#t to e:#eed the %alid ran e o$ indi#es $or an array& This #an #reate problems, sin#e a##essin out1o$1ran e elements do not #ause #ompilation errors but #an #ause runtime errors& The reason "hy this is allo"ed "ill be seen $urther ahead "hen "e be in to use pointers& 't this point it is important to be able to #learly distin uish bet"een the t"o uses that bra#-ets P Q ha%e related to arrays& They per$orm t"o di$$erent tas-s: one is to spe#i$y the siDe o$ arrays "hen

they are de#laredL and the se#ond one is to spe#i$y indi#es $or #on#rete array elements& Do not #on$use these t"o possible uses o$ bra#-ets P Q "ith arrays&

int &illyP+Q; &illyP,Q * E+;

// declaration of a ne( array // access to an element of t)e arrayF

2$ you read #are$ully, you "ill see that a type spe#i$ier al"ays pre#edes a %ariable or array de#laration, "hile it ne%er pre#edes an a##ess& >ome other %alid operations "ith arrays:

&illyP!Q * a; &illyPaQ * E+; & * &illy Pa+,Q; &illyP&illyPaQQ * &illyP,Q + +; // arrays e1ample #include <iostream> using namespace std; int &illy PQ * {-C0 ,0 EE0 B!0 -,!E-"; int n0 result*!; int main () { for ( n*! ; n<+ ; n++ ) { result +* &illyPnQ; " cout << result; return !; "

-,,!C

#ultidimensional arrays
5ultidimensional arrays #an be des#ribed as <arrays o$ arrays<& *or e:ample, a bidimensional array #an be ima ined as a bidimensional table made o$ elements, all o$ them o$ a same uni$orm data type&

Uimmy represents a bidimensional array o$ 3 per @ elements o$ type int& The "ay to de#lare this
array in C// "ould be:

int Uimmy PDQP+Q;


and, $or e:ample, the "ay to re$eren#e the se#ond element %erti#ally and $ourth horiDontally in an e:pression "ould be:

UimmyP-QPDQ

.remember that array indi#es al"ays be in by Dero0& 5ultidimensional arrays are not limited to t"o indi#es .i&e&, t"o dimensions0& They #an #ontain as many indi#es as needed& 6ut be #are$ulB The amount o$ memory needed $or an array rapidly in#reases "ith ea#h dimension& *or e:ample:

c)ar century P-!!QPDC+QP,BQPC!QPC!Q;


de#lares an array "ith a c)ar element $or ea#h se#ond in a #entury, that is more than 3 billion #hars& >o this de#laration "ould #onsume more than 3 i abytes o$ memoryB 5ultidimensional arrays are ?ust an abstra#tion $or pro rammers, sin#e "e #an obtain the same results "ith a simple array ?ust by puttin a $a#tor bet"een its indi#es:

int Uimmy PDQP+Q; int Uimmy P-+Q;

// is e4ui2alent to // (D % + * -+)

=ith the only di$$eren#e that "ith multidimensional arrays the #ompiler remembers the depth o$ ea#h ima inary dimension $or us& Ta-e as e:ample these t"o pie#es o$ #ode, "ith both e:a#tly the same result& )ne uses a bidimensional array and the other one uses a simple array: multidimensional array pseudo multidimensional array

#define W#V:H + #define H6#WH: D int Uimmy PH6#WH:QPW#V:HQ; int n0m;

#define W#V:H + #define H6#WH: D int Uimmy PH6#WH: % W#V:HQ; int n0m;

int main () int main () { { for (n*!;n<H6#WH:;n++) for (n*!;n<H6#WH:;n++) for (m*!;m<W#V:H;m++) for (m*!;m<W#V:H;m++) { { UimmyPnQPmQ*(n+-)%(m+-); UimmyPn%W#V:H+mQ*(n+-)%(m+-); " " return !; return !; " "
,one o$ the t"o sour#e #odes abo%e produ#e any output on the s#reen, but both assi n %alues to the memory blo#- #alled ?immy in the $ollo"in "ay:

=e ha%e used <de$ined #onstants< .#define0 to simpli$y possible $uture modi$i#ations o$ the pro ram& *or e:ample, in #ase that "e de#ided to enlar e the array to a hei ht o$ G instead o$ 3 it #ould be done simply by #han in the line:

#define H6#WH: D
to:

#define H6#WH: B
"ith no need to ma-e any other modi$i#ations to the pro ram&

Arrays as parameters
't some moment "e may need to pass an array to a $un#tion as a parameter& 2n C// it is not possible to pass a #omplete blo#- o$ memory by %alue as a parameter to a $un#tion, but "e are allo"ed to pass its address& 2n pra#ti#e this has almost the same e$$e#t and it is a mu#h $aster and more e$$i#ient operation& 2n order to a##ept arrays as parameters the only thin that "e ha%e to do "hen de#larin the $un#tion is to spe#i$y in its parameters the element type o$ the array, an identi$ier and a pair o$ %oid bra#-ets PQ& *or e:ample, the $ollo"in $un#tion:

2oid procedure (int argPQ)


a##epts a parameter o$ type <array o$ int< #alled arg& 2n order to pass to this $un#tion an array de#lared as:

int myarray PB!Q;


it "ould be enou h to "rite a #all li-e this:

procedure (myarray);
Eere you ha%e a #omplete e:ample:

// arrays as parameters #include <iostream> using namespace std; 2oid printarray (int argPQ0 int lengt)) { for (int n*!; n<lengt); n++) cout << argPnQ << " "; cout << "Jn"; " int main () { int firstarrayPQ * {+0 -!0 -+"; int secondarrayPQ * {,0 B0 C0 T0 -!"; printarray (firstarray0D); printarray (secondarray0+); return !; "

+ -! -+ , B C T -!

's you #an see, the $irst parameter .int argPQ0 a##epts any array "hose elements are o$ type int, "hate%er its len th& *or that reason "e ha%e in#luded a se#ond parameter that tells the $un#tion the len th o$ ea#h array that "e pass to it as its $irst parameter& This allo"s the for loop that prints out the array to -no" the ran e to iterate in the passed array "ithout oin out o$ ran e& 2n a $un#tion de#laration it is also possible to in#lude multidimensional arrays& The $ormat $or a tridimensional array parameter is:

&ase/typePQPdept)QPdept)Q
$or e:ample, a $un#tion "ith a multidimensional array as ar ument #ould be:

2oid procedure (int myarrayPQPDQPBQ)


,oti#e that the $irst bra#-ets PQ are le$t blan- "hile the $ollo"in ones are not& This is so be#ause the #ompiler must be able to determine "ithin the $un#tion "hi#h is the depth o$ ea#h additional dimension& 'rrays, both simple or multidimensional, passed as $un#tion parameters are a ;uite #ommon sour#e o$ errors $or no%i#e pro rammers& 2 re#ommend the readin o$ the #hapter about Pointers $or a better understandin on ho" arrays operate&

Character Se=uences
*or e:ample, the $ollo"in array:

Published by Juan Soulie


Last update on 5ar 1G, 2004 at 10:04am UTC

's you may already -no", the C// >tandard Library implements a po"er$ul strin #lass, "hi#h is %ery use$ul to handle and manipulate strin s o$ #hara#ters& Eo"e%er, be#ause strin s are in $a#t se;uen#es o$ #hara#ters, "e #an represent them also as plain arrays o$ c)ar elements&

c)ar Uenny P,!Q;


is an array that #an store up to 20 elements o$ type c)ar& 2t #an be represented as:

There$ore, in this array, in theory, "e #an store se;uen#es o$ #hara#ters up to 20 #hara#ters lon & 6ut "e #an also store shorter se;uen#es& *or e:ample, Uenny #ould store at some point in a pro ram either the se;uen#e "Hello" or the se;uen#e "=erry c)ristmas", sin#e both are shorter than 20 #hara#ters& There$ore, sin#e the array o$ #hara#ters #an store shorter se;uen#es than its total len th, a spe#ial #hara#ter is used to si nal the end o$ the %alid se;uen#e: the null character, "hose literal #onstant #an be "ritten as $J!$ .ba#-slash, Dero0& )ur array o$ 20 elements o$ type c)ar, #alled Uenny, #an be represented storin the #hara#ters se;uen#es "Hello" and "=erry C)ristmas" as:

,oti#e ho" a$ter the %alid #ontent a null #hara#ter . $J!$0 has been in#luded in order to indi#ate the end o$ the se;uen#e& The panels in ray #olor represent c)ar elements "ith undetermined %alues&

(nitiali,ation of null terminated character se=uences


6e#ause arrays o$ #hara#ters are ordinary arrays they $ollo" all their same rules& *or e:ample, i$ "e "ant to initialiDe an array o$ #hara#ters "ith some predetermined se;uen#e o$ #hara#ters "e #an do it ?ust li-e any other array:

c)ar my(ordPQ * { $H$0 $e$0 $l$0 $l$0 $o$0 $J!$ ";


2n this #ase "e "ould ha%e de#lared an array o$ ! elements o$ type c)ar initialiDed "ith the #hara#ters that $orm the "ord "Hello" plus a null #hara#ter $J!$ at the end& 6ut arrays o$ c)ar elements ha%e an additional method to initialiDe their %alues: usin strin literals& 2n the e:pressions "e ha%e used in some e:amples in pre%ious #hapters, #onstants that represent entire strin s o$ #hara#ters ha%e already sho"ed up se%eral times& These are spe#i$ied en#losin the te:t to be#ome a strin literal bet"een double ;uotes .<0& *or e:ample:

"t)e result isA "

is a #onstant strin literal that "e ha%e probably used already& Double ;uoted strin s ."0 are literal #onstants "hose type is in $a#t a null1terminated array o$ #hara#ters& >o strin literals en#losed bet"een double ;uotes al"ays ha%e a null #hara#ter . $J!$0 automati#ally appended at the end& There$ore "e #an initialiDe the array o$ c)ar elements #alled my(ord "ith a null1terminated se;uen#e o$ #hara#ters by either one o$ these t"o methods:

c)ar my(ord PQ * { $H$0 $e$0 $l$0 $l$0 $o$0 $J!$ "; c)ar my(ord PQ * "Hello";
2n both #ases the array o$ #hara#ters my(ord is de#lared "ith a siDe o$ ! elements o$ type c)ar: the @ #hara#ters that #ompose the "ord "Hello" plus a $inal null #hara#ter .$J!$0 "hi#h spe#i$ies the end o$ the se;uen#e and that, in the se#ond #ase, "hen usin double ;uotes . "0 it is appended automati#ally& Please noti#e that "e are tal-in about initialiDin an array o$ #hara#ters in the moment it is bein de#lared, and not about assi nin %alues to them on#e they ha%e already been de#lared& 2n $a#t be#ause this type o$ null1terminated arrays o$ #hara#ters are re ular arrays "e ha%e the same restri#tions that "e ha%e "ith any other array, so "e are not able to #opy blo#-s o$ data "ith an assi nment operation& 'ssumin myste1t is a c)arPQ %ariable, e:pressions "ithin a sour#e #ode li-e:

myste1t * "Hello"; myste1tPQ * "Hello";


"ould not be %alid, li-e neither "ould be:

myste1t * { $H$0 $e$0 $l$0 $l$0 $o$0 $J!$ ";


The reason $or this may be#ome more #omprehensible on#e you -no" a bit more about pointers, sin#e then it "ill be #lari$ied that an array is in $a#t a #onstant pointer pointin to a blo#- o$ memory&

Fsing null terminated se=uences of characters


,ull1terminated se;uen#es o$ #hara#ters are the natural "ay o$ treatin strin s in C//, so they #an be used as su#h in many pro#edures& 2n $a#t, re ular strin literals ha%e this type . c)arPQ0 and #an also be used in most #ases& *or e:ample, cin and cout support null1terminated se;uen#es as %alid #ontainers $or se;uen#es o$ #hara#ters, so they #an be used dire#tly to e:tra#t strin s o$ #hara#ters $rom cin or to insert them into cout& *or e:ample:

// null.terminated se4uences of c)aracters #include <iostream> using namespace std; int main () { c)ar 4uestionPQ * "Klease0 enter your first nameA "; c)ar greetingPQ * "Hello0 "; c)ar yourname PT!Q;

Klease0 enter your first nameA So)n Hello0 So)n

"

cout << 4uestion; cin >> yourname; cout << greeting << yourname << " "; return !;

's you #an see, "e ha%e de#lared three arrays o$ c)ar elements& The $irst t"o "ere initialiDed "ith strin literal #onstants, "hile the third one "as le$t uninitialiDed& 2n any #ase, "e ha%e to spe$i#i$y the siDe o$ the array: in the $irst t"o .4uestion and greeting0 the siDe "as impli#itly de$ined by the len th o$ the literal #onstant they "ere initialiDed to& =hile $or yourname "e ha%e e:pli#itly spe#i$ied that it has a siDe o$ 80 #hars& *inally, se;uen#es o$ #hara#ters stored in c)ar arrays #an easily be #on%erted into string ob?e#ts ?ust by usin the assi nment operator:

string mystring; c)ar myntcsPQ*"some te1t"; mystring * myntcs;

Pointers

Published by Juan Soulie


Last update on Jun 2@, 2004 at 4:10am UTC

=e ha%e already seen ho" %ariables are seen as memory #ells that #an be a##essed usin their identi$iers& This "ay "e did not ha%e to #are about the physi#al lo#ation o$ our data "ithin memory, "e simply used its identi$ier "hene%er "e "anted to re$er to our %ariable& The memory o$ your #omputer #an be ima ined as a su##ession o$ memory #ells, ea#h one o$ the minimal siDe that #omputers mana e .one byte0& These sin le1byte memory #ells are numbered in a #onse#uti%e "ay, so as, "ithin any blo#- o$ memory, e%ery #ell has the same number as the pre%ious one plus one& This "ay, ea#h #ell #an be easily lo#ated in the memory be#ause it has a uni;ue address and all the memory #ells $ollo" a su##essi%e pattern& *or e:ample, i$ "e are loo-in $or #ell 144! "e -no" that it is oin to be ri ht bet"een #ells 144@ and 1444, e:a#tly one thousand #ells a$ter 44! and e:a#tly one thousand #ells be$ore #ell 244!&

.eference operator 092


's soon as "e de#lare a %ariable, the amount o$ memory needed is assi ned $or it at a spe#i$i# lo#ation in memory .its memory address0& =e enerally do not a#ti%ely de#ide the e:a#t lo#ation o$ the %ariable "ithin the panel o$ #ells that "e ha%e ima ined the memory to be 1 *ortunately, that is a tas- automati#ally per$ormed by the operatin system durin runtime& Eo"e%er, in some #ases "e may be interested in -no"in the address "here our %ariable is bein stored durin runtime in order to operate "ith relati%e positions to it& The address that lo#ates a %ariable "ithin memory is "hat "e #all a reference to that %ariable& This re$eren#e to a %ariable #an be obtained by pre#edin the identi$ier o$ a %ariable "ith an ampersand si n .M0, -no"n as re$eren#e operator, and "hi#h #an be literally translated as <address o$<& *or e:ample:

ted * Mandy;
This "ould assi n to ted the address o$ %ariable andy, sin#e "hen pre#edin the name o$ the %ariable andy "ith the re$eren#e operator .M0 "e are no lon er tal-in about the #ontent o$ the %ariable itsel$, but about its re$eren#e .i&e&, its address in memory0& *or no" on "e are oin to assume that andy is pla#ed durin runtime in the memory address -EEC& This number .-EEC0 is ?ust and arbitrary assumption "e are in%entin ri ht no" in order to help #lari$y some #on#epts in this tutorial, but in reality, "e #annot -no" be$ore runtime the real %alue the address o$ a %ariable "ill ha%e in memory& Consider the $ollo"in #ode $ra ment:

andy * ,+; fred * andy; ted * Mandy;


The %alues #ontained in ea#h %ariable a$ter the e:e#ution o$ this, are sho"n in the $ollo"in dia ram:

*irst, "e ha%e assi ned the %alue 2@ to andy .a %ariable "hose address in memory "e ha%e assumed to be 144!0& The se#ond statement #opied to fred the #ontent o$ %ariable andy ."hi#h is 2@0& This is a standard assi nment operation, as "e ha%e done so many times be$ore& *inally, the third statement #opies to ted not the %alue #ontained in andy but a re$eren#e to it .i&e&, its address, "hi#h "e ha%e assumed to be -EEC0& The reason is that in this third assi nment operation "e ha%e pre#eded the identi$ier andy "ith the re$eren#e operator .M0, so "e "ere no lon er re$errin to the %alue o$ andy but to its re$eren#e .its address in memory0& The %ariable that stores the re$eren#e to another %ariable .li-e ted in the pre%ious e:ample0 is "hat "e #all a pointer& Pointers are a %ery po"er$ul $eature o$ the C// lan ua e that has many uses in ad%an#ed pro rammin & *arther ahead, "e "ill see ho" this type o$ %ariable is used and de#lared&

&ereference operator 0-2


=e ha%e ?ust seen that a %ariable "hi#h stores a re$eren#e to another %ariable is #alled a pointer& Pointers are said to <point to< the %ariable "hose re$eren#e they store& Usin a pointer "e #an dire#tly a##ess the %alue stored in the %ariable "hi#h it points to& To do this, "e simply ha%e to pre#ede the pointerCs identi$ier "ith an asteris- .I0, "hi#h a#ts as dere$eren#e operator and that #an be literally translated to <%alue pointed by<& There$ore, $ollo"in "ith the %alues o$ the pre%ious e:ample, i$ "e "rite:

&et) * %ted;
.that "e #ould read as: <&et) e;ual to %alue pointed by ted<0 &et) "ould ta-e the %alue ,+, sin#e ted is -EEC, and the %alue pointed by 144! is 2@&

Aou must #learly di$$erentiate that the e:pression ted re$ers to the %alue -EEC, "hile %ted ."ith an asteris- % pre#edin the identi$ier0 re$ers to the %alue stored at address -EEC, "hi#h in this #ase is

,+& ,oti#e the di$$eren#e o$ in#ludin or not in#ludin the dere$eren#e operator .2 ha%e in#luded an
e:planatory #ommentary o$ ho" ea#h o$ these t"o e:pressions #ould be read0:

&et) * ted; &et) * %ted;

// &et) e4ual to ted ( -EEC ) // &et) e4ual to 2alue pointed &y ted ( ,+ )

,oti#e the di$$eren#e bet"een the re$eren#e and dere$eren#e operators:

T is the re$eren#e operator and #an be read as <address o$< I is the dere$eren#e operator and #an be read as <%alue pointed by<

Thus, they ha%e #omplementary .or opposite0 meanin s& ' %ariable re$eren#ed "ith M #an be dere$eren#ed "ith %& 9arlier "e per$ormed the $ollo"in t"o assi nment operations:

andy * ,+; ted * Mandy;


+i ht a$ter these t"o statements, all o$ the $ollo"in e:pressions "ould i%e true as result:

andy ** ,+ Mandy ** -EEC ted ** -EEC %ted ** ,+


The $irst e:pression is ;uite #lear #onsiderin that the assi nment operation per$ormed on andy "as andy*,+& The se#ond one uses the re$eren#e operator .M0, "hi#h returns the address o$ %ariable andy, "hi#h "e assumed it to ha%e a %alue o$ -EEC& The third one is some"hat ob%ious sin#e the se#ond e:pression "as true and the assi nment operation per$ormed on ted "as ted*Mandy& The $ourth e:pression uses the dere$eren#e operator . %0 that, as "e ha%e ?ust seen, #an be read as <%alue pointed by<, and the %alue pointed by ted is indeed ,+& >o, a$ter all that, you may also in$er that $or as lon as the address pointed by ted remains un#han ed the $ollo"in e:pression "ill also be true:

%ted ** andy

&eclaring "ariables of pointer types


Due to the ability o$ a pointer to dire#tly re$er to the %alue that it points to, it be#omes ne#essary to spe#i$y in its de#laration "hi#h data type a pointer is oin point to& 2t is not the same thin to point to a c)ar than to point to an int or a float& The de#laration o$ pointers $ollo"s this $ormat:

type % name;
"here type is the data type o$ the %alue that the pointer is intended to point to& This type is not the type o$ the pointer itsel$B but the type o$ the data the pointer points to& *or e:ample:

int % num&er; c)ar % c)aracter; float % greatnum&er;

These are three de#larations o$ pointers& 9a#h one is intended to point to a di$$erent data type, but in $a#t all o$ them are pointers and all o$ them "ill o##upy the same amount o$ spa#e in memory .the siDe in memory o$ a pointer depends on the plat$orm "here the #ode is oin to run0& ,e%ertheless, the data to "hi#h they point to do not o##upy the same amount o$ spa#e nor are o$ the same type: the $irst one points to an int, the se#ond one to a c)ar and the last one to a float& There$ore, althou h these three e:ample %ariables are all o$ them pointers "hi#h o##upy the same siDe in memory, they are said to ha%e di$$erent types: int%, c)ar% and float% respe#ti%ely, dependin on the type they point to& 2 "ant to emphasiDe that the asteris- si n .%0 that "e use "hen de#larin a pointer only means that it is a pointer .it is part o$ its type #ompound spe#i$ier0, and should not be #on$used "ith the dere$eren#e operator that "e ha%e seen a bit earlier, but "hi#h is also "ritten "ith an asteris- . %0& They are simply t"o di$$erent thin s represented "ith the same si n& ,o" ha%e a loo- at this #ode:

// my first pointer #include <iostream> using namespace std; int main () { int first2alue0 second2alue; int % mypointer; mypointer * Mfirst2alue; %mypointer * -!; mypointer * Msecond2alue; %mypointer * ,!; cout << "first2alue is " << first2alue << endl; cout << "second2alue is " << second2alue << endl; return !; "

first2alue is -! second2alue is ,!

,oti#e that e%en thou h "e ha%e ne%er dire#tly set a %alue to either first2alue or second2alue, both end up "ith a %alue set indire#tly throu h the use o$ mypointer& This is the pro#edure: *irst, "e ha%e assi ned as %alue o$ mypointer a re$eren#e to first2alue usin the re$eren#e operator .M0& 'nd then "e ha%e assi ned the %alue 10 to the memory lo#ation pointed by mypointer, that be#ause at this moment is pointin to the memory lo#ation o$ first2alue, this in $a#t modi$ies the %alue o$ first2alue& 2n order to demonstrate that a pointer may ta-e se%eral di$$erent %alues durin the same pro ram 2 ha%e repeated the pro#ess "ith second2alue and that same pointer, mypointer& Eere is an e:ample a little bit more elaborated:

// more pointers #include <iostream> using namespace std; int main () { int first2alue * +0 second2alue * -+; int % p-0 % p,;

first2alue is -! second2alue is ,!

p- * Mfirst2alue; // p- * address of first2alue p, * Msecond2alue; // p, * address of second2alue %p- * -!; // 2alue pointed &y p- * -! %p, * %p-; // 2alue pointed &y p, * 2alue pointed &y pp- * p,; // p- * p, (2alue of pointer is copied) %p- * ,!; // 2alue pointed &y p- * ,! cout << "first2alue is " << first2alue << endl; cout << "second2alue is " << second2alue << endl; return !; "
2 ha%e in#luded as a #omment on ea#h line ho" the #ode #an be read: ampersand . M0 as <address o$< and asteris- .%0 as <%alue pointed by<& ,oti#e that there are e:pressions "ith pointers p- and p,, both "ith and "ithout dere$eren#e operator .%0& The meanin o$ an e:pression usin the dere$eren#e operator .%0 is %ery di$$erent $rom one that does not: =hen this operator pre#edes the pointer name, the e:pression re$ers to the %alue bein pointed, "hile "hen a pointer name appears "ithout this operator, it re$ers to the %alue o$ the pointer itsel$ .i&e& the address o$ "hat the pointer is pointin to0& 'nother thin that may #all your attention is the line:

int % p-0 % p,;


This de#lares the t"o pointers used in the pre%ious e:ample& 6ut noti#e that there is an asteris- .I0 $or ea#h pointer, in order $or both to ha%e type int% .pointer to int0& )ther"ise, the type $or the se#ond %ariable de#lared in that line "ould ha%e been int .and not int%0 be#ause o$ pre#eden#e relationships& 2$ "e had "ritten:

int % p-0 p,; p- "ould indeed ha%e int% type, but p, "ould ha%e type int .spa#es do not matter at all $or this
purpose0& This is due to operator pre#eden#e rules& 6ut any"ay, simply rememberin that you ha%e to put one asteris- per pointer is enou h $or most pointer users&

Pointers and arrays


The #on#ept o$ array is %ery mu#h bound to the one o$ pointer& 2n $a#t, the identi$ier o$ an array is e;ui%alent to the address o$ its $irst element, as a pointer is e;ui%alent to the address o$ the $irst element that it points to, so in $a#t they are the same #on#ept& *or e:ample, supposin these t"o de#larations:

int num&ers P,!Q; int % p;


The $ollo"in assi nment operation "ould be %alid:

p * num&ers;

'$ter that, p and num&ers "ould be e;ui%alent and "ould ha%e the same properties& The only di$$eren#e is that "e #ould #han e the %alue o$ pointer p by another one, "hereas num&ers "ill al"ays point to the $irst o$ the 20 elements o$ type int "ith "hi#h it "as de$ined& There$ore, unli-e p, "hi#h is an ordinary pointer, num&ers is an array, and an array #an be #onsidered a constant pointer& There$ore, the $ollo"in allo#ation "ould not be %alid:

num&ers * p;
6e#ause num&ers is an array, so it operates as a #onstant pointer, and "e #annot assi n %alues to #onstants& Due to the #hara#teristi#s o$ %ariables, all e:pressions that in#lude pointers in the $ollo"in e:ample are per$e#tly %alid:

// more pointers #include <iostream> using namespace std; int main () { int num&ersP+Q; int % p; p * num&ers; %p * -!; p++; %p * ,!; p * Mnum&ersP,Q; %p * D!; p * num&ers + D; %p * B!; p * num&ers; %(p+B) * +!; for (int n*!; n<+; n++) cout << num&ersPnQ << "0 "; return !; "

-!0 ,!0 D!0 B!0 +!0

2n the #hapter about arrays "e used bra#-ets . PQ0 se%eral times in order to spe#i$y the inde: o$ an element o$ the array to "hi#h "e "anted to re$er& =ell, these bra#-et si n operators PQ are also a dere$eren#e operator -no"n as offset operator& They dere$eren#e the %ariable they $ollo" ?ust as % does, but they also add the number bet"een bra#-ets to the address bein dere$eren#ed& *or e:ample:

aP+Q * !; %(a++) * !;

// a Poffset of +Q * ! // pointed &y (a++) * !

These t"o e:pressions are e;ui%alent and %alid both i$ a is a pointer or i$ a is an array&

Pointer initiali,ation
=hen de#larin pointers "e may "ant to e:pli#itly spe#i$y "hi#h %ariable "e "ant them to point to:

int num&er; int %tommy * Mnum&er;


The beha%ior o$ this #ode is e;ui%alent to:

int num&er; int %tommy; tommy * Mnum&er;


=hen a pointer initialiDation ta-es pla#e "e are al"ays assi nin the re$eren#e %alue to "here the pointer points .tommy0, ne%er the %alue bein pointed .%tommy0& Aou must #onsider that at the

moment o$ de#larin a pointer, the asteris- .%0 indi#ates only that it is a pointer, it is not the dere$eren#e operator .althou h both use the same si n: I0& +emember, they are t"o di$$erent $un#tions o$ one si n& Thus, "e must ta-e #are not to #on$use the pre%ious #ode "ith:

int num&er; int %tommy; %tommy * Mnum&er;


that is in#orre#t, and any"ay "ould not ha%e mu#h sense in this #ase i$ you thin- about it& 's in the #ase o$ arrays, the #ompiler allo"s the spe#ial #ase that "e "ant to initialiDe the #ontent at "hi#h the pointer points "ith #onstants at the same moment the pointer is de#lared:

c)ar % terry * ")ello";


2n this #ase, memory spa#e is reser%ed to #ontain ")ello" and then a pointer to the $irst #hara#ter o$ this memory blo#- is assi ned to terry& 2$ "e ima ine that ")ello" is stored at the memory lo#ations that start at addresses 1402, "e #an represent the pre%ious de#laration as:

2t is important to indi#ate that terry #ontains the %alue 1402, and not $)$ nor ")ello", althou h 1402 indeed is the address o$ both o$ these& The pointer terry points to a se;uen#e o$ #hara#ters and #an be read as i$ it "as an array .remember that an array is ?ust li-e a #onstant pointer0& *or e:ample, "e #an a##ess the $i$th element o$ the array "ith any o$ these t"o e:pression:

%(terry+B) terryPBQ
6oth e:pressions ha%e a %alue o$ $o$ .the $i$th element o$ the array0&

Pointer arithmetics
To #ondu#t arithmeti#al operations on pointers is a little di$$erent than to #ondu#t them on re ular inte er data types& To be in "ith, only addition and subtra#tion operations are allo"ed to be #ondu#ted "ith them, the others ma-e no sense in the "orld o$ pointers& 6ut both addition and subtra#tion ha%e a di$$erent beha%ior "ith pointers a##ordin to the siDe o$ the data type to "hi#h they point& =hen "e sa" the di$$erent $undamental data types, "e sa" that some o##upy more or less spa#e than others in the memory& *or e:ample, letCs assume that in a i%en #ompiler $or a spe#i$i# ma#hine, c)ar ta-es 1 byte, s)ort ta-es 2 bytes and long ta-es G& >uppose that "e de$ine three pointers in this #ompiler:

c)ar %myc)ar;

s)ort %mys)ort; long %mylong;


and that "e -no" that they point to memory lo#ations -!!!, ,!!! and D!!! respe#ti%ely& >o i$ "e "rite:

myc)ar++; mys)ort++; mylong++; myc)ar, as you may e:pe#t, "ould #ontain the %alue -!!-& 6ut not so ob%iously, mys)ort "ould #ontain the %alue ,!!,, and mylong "ould #ontain D!!B, e%en thou h they ha%e ea#h been in#reased
only on#e& The reason is that "hen addin one to a pointer "e are ma-in it to point to the $ollo"in element o$ the same type "ith "hi#h it has been de$ined, and there$ore the siDe in bytes o$ the type pointed is added to the pointer&

This is appli#able both "hen addin and subtra#tin any number to a pointer& 2t "ould happen e:a#tly the same i$ "e "rite:

myc)ar * myc)ar + -; mys)ort * mys)ort + -; mylong * mylong + -;


6oth the in#rease .++0 and de#rease ...0 operators ha%e reater operator pre#eden#e than the dere$eren#e operator .%0, but both ha%e a spe#ial beha%ior "hen used as su$$i: .the e:pression is e%aluated "ith the %alue it had be$ore bein in#reased0& There$ore, the $ollo"in e:pression may lead to #on$usion:

%p++
6e#ause ++ has reater pre#eden#e than %, this e:pression is e;ui%alent to %(p++)& There$ore, "hat it does is to in#rease the %alue o$ p .so it no" points to the ne:t element0, but be#ause // is used as post$i: the "hole e:pression is e%aluated as the %alue pointed by the ori inal re$eren#e .the address the pointer pointed to be$ore bein in#reased0& ,oti#e the di$$eren#e "ith:

(%p)++

Eere, the e:pression "ould ha%e been e%aluated as the %alue pointed by p in#reased by one& The %alue o$ p .the pointer itsel$0 "ould not be modi$ied ."hat is bein modi$ied is "hat it is bein pointed to by this pointer0& 2$ "e "rite:

%p++ * %4++;
6e#ause ++ has a hi her pre#eden#e than %, both p and 4 are in#reased, but be#ause both in#rease operators .++0 are used as post$i: and not pre$i:, the %alue assi ned to %p is %4 be$ore both p and 4 are in#reased& 'nd then both are in#reased& 2t "ould be rou hly e;ui%alent to:

%p * %4; ++p; ++4;


Li-e al"ays, 2 re#ommend you to use parentheses () in order to a%oid une:pe#ted results and to i%e more le ibility to the #ode&

Pointers to pointers
C// allo"s the use o$ pointers that point to pointers, that these, in its turn, point to data .or e%en to other pointers0& 2n order to do that, "e only need to add an asteris- . %0 $or ea#h le%el o$ re$eren#e in their de#larations:

c)ar a; c)ar % &; c)ar %% c; a * $3$; & * Ma; c * M&;


This, supposin the randomly #hosen memory lo#ations $or ea#h %ariable o$ E,D!, T!G, and -!+!,, #ould be represented as:

The %alue o$ ea#h %ariable is "ritten inside ea#h #ellL under the #ells are their respe#ti%e addresses in memory& The ne" thin in this e:ample is %ariable c, "hi#h #an be used in three di$$erent le%els o$ indire#tion, ea#h one o$ them "ould #orrespond to a di$$erent %alue:

c has type c)ar%% and a %alue o$ T!G, %c has type c)ar% and a %alue o$ E,D! %%c has type c)ar and a %alue o$ $3$

"oid pointers
The 2oid type o$ pointer is a spe#ial type o$ pointer& 2n C//, 2oid represents the absen#e o$ type, so %oid pointers are pointers that point to a %alue that has no type .and thus also an undetermined len th and undetermined dere$eren#e properties0&

This allo"s %oid pointers to point to any data type, $rom an inte er %alue or a $loat to a strin o$ #hara#ters& 6ut in e:#han e they ha%e a reat limitation: the data pointed by them #annot be dire#tly dere$eren#ed ."hi#h is lo i#al, sin#e "e ha%e no type to dere$eren#e to0, and $or that reason "e "ill al"ays ha%e to #ast the address in the %oid pointer to some other pointer type that points to a #on#rete data type be$ore dere$eren#in it& )ne o$ its uses may be to pass eneri# parameters to a $un#tion:

// increaser #include <iostream> using namespace std; 2oid increase (2oid% data0 int psi3e) { if ( psi3e ** si3eof(c)ar) ) { c)ar% pc)ar; pc)ar*(c)ar%)data; ++ (%pc)ar); " else if (psi3e ** si3eof(int) ) { int% pint; pint*(int%)data; ++ (%pint); " " int main () { c)ar a * $1$; int & * -C!,; increase (Ma0si3eof(a)); increase (M&0si3eof(&)); cout << a << "0 " << & << endl; return !; "

y0 -C!D

si3eof is an operator inte rated in the C// lan ua e that returns the siDe in bytes o$ its parameter& *or non1dynami# data types this %alue is a #onstant& There$ore, $or e:ample, si3eof(c)ar) is -, be#ause c)ar type is one byte lon &

+ull pointer
' null pointer is a re ular pointer o$ any pointer type "hi#h has a spe#ial %alue that indi#ates that it is not pointin to any %alid re$eren#e or memory address& This %alue is the result o$ type1#astin the inte er %alue Dero to any pointer type&

int % p; p * !;

// p )as a null pointer 2alue

Do not #on$use null pointers "ith %oid pointers& ' null pointer is a %alue that any pointer may ta-e to represent that it is pointin to <no"here<, "hile a %oid pointer is a spe#ial type o$ pointer that #an point to some"here "ithout a spe#i$i# type& )ne re$ers to the %alue stored in the pointer itsel$ and the other to the type o$ data it points to&

Pointers to functions
C// allo"s operations "ith pointers to $un#tions& The typi#al use o$ this is $or passin a $un#tion as an ar ument to another $un#tion, sin#e these #annot be passed dere$eren#ed& 2n order to de#lare a pointer to a $un#tion "e ha%e to de#lare it li-e the prototype o$ the $un#tion e:#ept that the name o$ the $un#tion is en#losed bet"een parentheses () and an asteris- .%0 is inserted be$ore the name:

// pointer to functions #include <iostream> using namespace std;

int addition (int a0 int &) { return (a+&); " int su&traction (int a0 int &) { return (a.&); " int operation (int 10 int y0 int (%functocall)(int0int)) { int g; g * (%functocall)(10y); return (g); " int main () { int m0n; int (%minus)(int0int) * su&traction; m * operation (E0 +0 addition); n * operation (,!0 m0 minus); cout <<n; return !;

"

2n the e:ample, minus is a pointer to a $un#tion that has t"o parameters o$ type int& 2t is immediately assi ned to point to the $un#tion su&traction, all in a sin le line:

int (% minus)(int0int) * su&traction;

&ynamic #emory

Published by Juan Soulie


Last update on Jan 18, 2008 at 1:@0pm UTC

Until no", in all our pro rams, "e ha%e only had as mu#h memory a%ailable as "e de#lared $or our %ariables, ha%in the siDe o$ all o$ them to be determined in the sour#e #ode, be$ore the e:e#ution o$ the pro ram& 6ut, "hat i$ "e need a %ariable amount o$ memory that #an only be determined durin runtimeQ *or e:ample, in the #ase that "e need some user input to determine the ne#essary amount o$ memory spa#e& The ans"er is dynamic memory, $or "hi#h C// inte rates the operators ne( and delete&

Operators neB and neBGH


2n order to re;uest dynami# memory "e use the operator ne(& ne( is $ollo"ed by a data type spe#i$ier and 1i$ a se;uen#e o$ more than one element is re;uired1 the number o$ these "ithin bra#-ets PQ& 2t returns a pointer to the be innin o$ the ne" blo#- o$ memory allo#ated& 2ts $orm is:

pointer * ne( type pointer * ne( type Pnum&er/of/elementsQ


The $irst e:pression is used to allo#ate memory to #ontain one sin le element o$ type type& The se#ond one is used to assi n a blo#- .an array0 o$ elements o$ type type, "here num&er/of/elements is an inte er %alue representin the amount o$ these& *or e:ample:

int % &o&&y; &o&&y * ne( int P+Q;


2n this #ase, the system dynami#ally assi ns spa#e $or $i%e elements o$ type int and returns a pointer to the $irst element o$ the se;uen#e, "hi#h is assi ned to &o&&y& There$ore, no", &o&&y points to a %alid blo#- o$ memory "ith spa#e $or $i%e elements o$ type int&

The $irst element pointed by bobby #an be a##essed either "ith the e:pression &o&&yP!Q or the e:pression %&o&&y& 6oth are e;ui%alent as has been e:plained in the se#tion about pointers& The se#ond element #an be a##essed either "ith &o&&yP-Q or %(&o&&y+-) and so on&&& Aou #ould be "onderin the di$$eren#e bet"een de#larin a normal array and assi nin dynami# memory to a pointer, as "e ha%e ?ust done& The most important di$$eren#e is that the siDe o$ an array has to be a #onstant %alue, "hi#h limits its siDe to "hat "e de#ide at the moment o$ desi nin the pro ram, be$ore its e:e#ution, "hereas the dynami# memory allo#ation allo"s us to assi n memory durin the e:e#ution o$ the pro ram .runtime0 usin any %ariable or #onstant %alue as its siDe& The dynami# memory re;uested by our pro ram is allo#ated by the system $rom the memory heap& Eo"e%er, #omputer memory is a limited resour#e, and it #an be e:hausted& There$ore, it is important to ha%e some me#hanism to #he#- i$ our re;uest to allo#ate memory "as su##ess$ul or not& C// pro%ides t"o standard methods to #he#- i$ the allo#ation "as su##ess$ul:

)ne is by handlin e:#eptions& Usin this method an e:#eption o$ type &ad/alloc is thro"n "hen the allo#ation $ails& 9:#eptions are a po"er$ul C// $eature e:plained later in these tutorials& 6ut $or no" you should -no" that i$ this e:#eption is thro"n and it is not handled by a spe#i$i# handler, the pro ram e:e#ution is terminated& This e:#eption method is the de$ault method used by ne", and is the one used in a de#laration li-e:

&o&&y * ne( int P+Q;

// if it fails an e1ception is t)ro(n

The other method is -no"n as not)ro(, and "hat happens "hen it is used is that "hen a memory allo#ation $ails, instead o$ thro"in a &ad/alloc e:#eption or terminatin the pro ram, the pointer returned by ne( is a null pointer, and the pro ram #ontinues its e:e#ution& This method #an be spe#i$ied by usin a spe#ial ob?e#t #alled not)ro(, de#lared in header <ne(>, as ar ument $or ne(:

&o&&y * ne( (not)ro() int P+Q;


2n this #ase, i$ the allo#ation o$ this blo#- o$ memory $ailed, the $ailure #ould be dete#ted by #he#-in i$ &o&&y too- a null pointer %alue:

int % &o&&y; &o&&y * ne( (not)ro() int P+Q; if (&o&&y ** !) { // error assigning memoryF :a'e measuresF ";
This not)ro( method re;uires more "or- than the e:#eption method, sin#e the %alue returned has to be #he#-ed a$ter ea#h and e%ery memory allo#ation, but 2 "ill use it in our e:amples due to its simpli#ity& 'ny"ay this method #an be#ome tedious $or lar er pro?e#ts, "here the e:#eption method is enerally pre$erred& The e:#eption method "ill be e:plained in detail later in this tutorial&

Operator delete and deleteGH


>in#e the ne#essity o$ dynami# memory is usually limited to spe#i$i# moments "ithin a pro ram, on#e it is no lon er needed it should be $reed so that the memory be#omes a%ailable a ain $or other re;uests o$ dynami# memory& This is the purpose o$ the operator delete, "hose $ormat is:

delete pointer; delete PQ pointer;


The $irst e:pression should be used to delete memory allo#ated $or a sin le element, and the se#ond one $or memory allo#ated $or arrays o$ elements& The %alue passed as ar ument to delete must be either a pointer to a memory blo#- pre%iously allo#ated "ith ne(, or a null pointer .in the #ase o$ a null pointer, delete produ#es no e$$e#t0&

// remem&.o.matic #include <iostream> #include <ne(> using namespace std; int main () { int i0n; int % p; cout << "Ho( many num&ers (ould you li'e to typeI ";

Ho( many num&ers (ould you li'e to typeI + 6nter num&er A E+ 6nter num&er A BDC 6nter num&er A -!CE 6nter num&er A T 6nter num&er A D, @ou )a2e enteredA E+0 BDC0 -!CE0 T0 D,0

cin >> i; p* ne( (not)ro() intPiQ; if (p ** !) cout << "6rrorA memory could not &e allocated"; else { for (n*!; n<i; n++) { cout << "6nter num&erA "; cin >> pPnQ; " cout << "@ou )a2e enteredA "; for (n*!; n<i; n++) cout << pPnQ << "0 "; deletePQ p; " return !; "
,oti#e ho" the %alue "ithin bra#-ets in the ne( statement is a %ariable %alue entered by the user . i0, not a #onstant %alue:

p* ne( (not)ro() intPiQ;


6ut the user #ould ha%e entered a %alue $or i so bi that our system #ould not handle it& *or e:ample, "hen 2 tried to i%e a %alue o$ 1 billion to the <Eo" many numbers< ;uestion, my system #ould not allo#ate that mu#h memory $or the pro ram and 2 ot the te:t messa e "e prepared $or this #ase .6rrorA memory could not &e allocated0& +emember that in the #ase that "e tried to allo#ate the memory "ithout spe#i$yin the nothro" parameter in the ne" e:pression, an e:#eption "ould be thro"n, "hi#h i$ itCs not handled terminates the pro ram& 2t is a ood pra#ti#e to al"ays #he#- i$ a dynami# memory blo#- "as su##ess$ully allo#ated& There$ore, i$ you use the not)ro( method, you should al"ays #he#- the %alue o$ the pointer returned& )ther"ise, use the e:#eption method, e%en i$ you do not handle the e:#eption& This "ay, the pro ram "ill terminate at that point "ithout #ausin the une:pe#ted results o$ #ontinuin e:e#utin a #ode that assumes a blo#- o$ memory to ha%e been allo#ated "hen in $a#t it has not&

&ynamic memory in A+S( C


)perators ne( and delete are e:#lusi%e o$ C//& They are not a%ailable in the C lan ua e& 6ut usin pure C lan ua e, dynami# memory #an also be used throu h the $un#tions mallo#, #allo#, reallo# and $ree, de$ined in the <cstdli&> header $ile, and sin#e C// is a superset o$ C, these $un#tions are also a%ailable to C// pro rammers .see #stdlib $or more in$o0& The memory blo#-s allo#ated by these $un#tions are not ne#essarily #ompatible "ith those returned by ne", so ea#h one should be manipulated "ith its o"n set o$ $un#tions or operators&

&ata Structures
&ata structures

Published by Juan Soulie


Last update on Jan 18, 2008 at 11:@2am UTC

=e ha%e already learned ho" roups o$ se;uential data #an be used in C//& 6ut this is some"hat restri#ti%e, sin#e in many o##asions "hat "e "ant to store are not mere se;uen#es o$ elements all o$ the same data type, but sets o$ di$$erent elements "ith di$$erent data types&

' data stru#ture is a roup o$ data elements rouped to ether under one name& These data elements, -no"n as members, #an ha%e di$$erent types and di$$erent len ths& Data stru#tures are de#lared in C/ / usin the $ollo"in synta:: stru#t stru#tureUname J memberUtype1 memberUname1L memberUtype2 memberUname2L memberUtype3 memberUname3L & & K ob?e#tUnamesL "here structure/name is a name $or the stru#ture type, o&Uect/name #an be a set o$ %alid identi$iers $or ob?e#ts that ha%e the type o$ this stru#ture& =ithin bra#es { " there is a list "ith the data members, ea#h one is spe#i$ied "ith a type and a %alid identi$ier as its name& The $irst thin "e ha%e to -no" is that a data stru#ture #reates a ne" type: )n#e a data stru#ture is de#lared, a ne" type "ith the identi$ier spe#i$ied as structure/name is #reated and #an be used in the rest o$ the pro ram as i$ it "as any other type& *or e:ample:

struct product { int (eig)t; float price; " ; product apple; product &anana0 melon;
=e ha%e $irst de#lared a stru#ture type #alled product "ith t"o members: (eig)t and price, ea#h o$ a di$$erent $undamental type& =e ha%e then used this name o$ the stru#ture type . product0 to de#lare three ob?e#ts o$ that type: apple, &anana and melon as "e "ould ha%e done "ith any $undamental data type& )n#e de#lared, product has be#ome a ne" %alid type name li-e the $undamental ones int, c)ar or s)ort and $rom that point on "e are able to de#lare ob?e#ts .%ariables0 o$ this #ompound ne" type, li-e "e ha%e done "ith apple, &anana and melon& +i ht at the end o$ the struct de#laration, and be$ore the endin semi#olon, "e #an use the optional $ield o&Uect/name to dire#tly de#lare ob?e#ts o$ the stru#ture type& *or e:ample, "e #an also de#lare the stru#ture ob?e#ts apple, &anana and melon at the moment "e de$ine the data stru#ture type this "ay:

struct product { int (eig)t; float price; " apple0 &anana0 melon;

2t is important to #learly di$$erentiate bet"een "hat is the stru#ture type name, and "hat is an ob?e#t .%ariable0 that has this stru#ture type& =e #an instantiate many ob?e#ts .i&e& %ariables, li-e apple, &anana and melon0 $rom a sin le stru#ture type .product0& )n#e "e ha%e de#lared our three ob?e#ts o$ a determined stru#ture type . apple, &anana and melon0 "e #an operate dire#tly "ith their members& To do that "e use a dot . F0 inserted bet"een the ob?e#t name and the member name& *or e:ample, "e #ould operate "ith any o$ these elements as i$ they "ere standard %ariables o$ their respe#ti%e types:

appleF(eig)t appleFprice &ananaF(eig)t &ananaFprice melonF(eig)t melonFprice


9a#h one o$ these has the data type #orrespondin to the member they re$er to: appleF(eig)t, &ananaF(eig)t and melonF(eig)t are o$ type int, "hile appleFprice, &ananaFprice and melonFprice are o$ type float& LetCs see a real e:ample "here you #an see ho" a stru#ture type #an be used in the same "ay as $undamental types:

// e1ample a&out structures #include <iostream> #include <string> #include <sstream> using namespace std; struct mo2ies/t { string title; int year; " mine0 yours; 2oid printmo2ie (mo2ies/t mo2ie); int main () { string mystr; mineFtitle * ",!!- > 7pace <dyssey"; mineFyear * -GCT; cout << "6nter titleA "; getline (cin0yoursFtitle); cout << "6nter yearA "; getline (cin0mystr); stringstream(mystr) >> yoursFyear; cout << "=y fa2orite mo2ie isAJn "; printmo2ie (mine); cout << ">nd yours isAJn "; printmo2ie (yours); return !; " 2oid printmo2ie (mo2ies/t mo2ie) { cout << mo2ieFtitle;

6nter titleA >lien 6nter yearA -GEG =y fa2orite mo2ie isA ,!!- > 7pace <dyssey (-GCT) >nd yours isA >lien (-GEG)

cout << " (" << mo2ieFyear << ")Jn"; "


The e:ample sho"s ho" "e #an use the members o$ an ob?e#t as re ular %ariables& *or e:ample, the member yoursFyear is a %alid %ariable o$ type int, and mineFtitle is a %alid %ariable o$ type string& The ob?e#ts mine and yours #an also be treated as %alid %ariables o$ type mo2ies/t, $or e:ample "e ha%e passed them to the $un#tion printmo2ie as "e "ould ha%e done "ith re ular %ariables& There$ore, one o$ the most important ad%anta es o$ data stru#tures is that "e #an either re$er to their members indi%idually or to the entire stru#ture as a blo#- "ith only one identi$ier& Data stru#tures are a $eature that #an be used to represent databases, espe#ially i$ "e #onsider the possibility o$ buildin arrays o$ them:

// array of structures #include <iostream> #include <string> #include <sstream> using namespace std; #define ;/=<X#67 D struct mo2ies/t { string title; int year; " films P;/=<X#67Q; 2oid printmo2ie (mo2ies/t mo2ie); int main () { string mystr; int n; for (n*!; n<;/=<X#67; n++) { cout << "6nter titleA "; getline (cin0filmsPnQFtitle); cout << "6nter yearA "; getline (cin0mystr); stringstream(mystr) >> filmsPnQFyear; " cout << "Jn@ou )a2e entered t)ese mo2iesAJn"; for (n*!; n<;/=<X#67; n++) printmo2ie (filmsPnQ); return !; " 2oid printmo2ie (mo2ies/t mo2ie) { cout << mo2ieFtitle; cout << " (" << mo2ieFyear << ")Jn"; "

6nter 6nter 6nter 6nter 6nter 6nter

titleA ?lade 5unner yearA -GT, titleA =atri1 yearA -GGG titleA :a1i Vri2er yearA -GEC

@ou )a2e entered t)ese mo2iesA ?lade 5unner (-GT,) =atri1 (-GGG) :a1i Vri2er (-GEC)

Pointers to structures
Li-e any other type, stru#tures #an be pointed by its o"n type o$ pointers:

struct mo2ies/t { string title; int year; "; mo2ies/t amo2ie; mo2ies/t % pmo2ie;
Eere amo2ie is an ob?e#t o$ stru#ture type mo2ies/t, and pmo2ie is a pointer to point to ob?e#ts o$ stru#ture type mo2ies/t& >o, the $ollo"in #ode "ould also be %alid:

pmo2ie * Mamo2ie;
The %alue o$ the pointer pmo2ie "ould be assi ned to a re$eren#e to the ob?e#t amo2ie .its memory address0& =e "ill no" o "ith another e:ample that in#ludes pointers, "hi#h "ill ser%e to introdu#e a ne" operator: the arro" operator ..>0:

// pointers to structures #include <iostream> #include <string> #include <sstream> using namespace std; struct mo2ies/t { string title; int year; "; int main () { string mystr; mo2ies/t amo2ie; mo2ies/t % pmo2ie; pmo2ie * Mamo2ie; cout << "6nter titleA "; getline (cin0 pmo2ie.>title); cout << "6nter yearA "; getline (cin0 mystr); (stringstream) mystr >> pmo2ie.>year; cout << "Jn@ou )a2e enteredAJn"; cout << pmo2ie.>title; cout << " (" << pmo2ie.>year << ")Jn"; " return !;

6nter titleA #n2asion of t)e &ody snatc)ers 6nter yearA -GET @ou )a2e enteredA #n2asion of t)e &ody snatc)ers (-GET)

The pre%ious #ode in#ludes an important introdu#tion: the arro" operator . .>0& This is a dere$eren#e operator that is used e:#lusi%ely "ith pointers to ob?e#ts "ith members& This operator ser%es to a##ess a member o$ an ob?e#t to "hi#h "e ha%e a re$eren#e& 2n the e:ample "e used:

pmo2ie.>title
=hi#h is $or all purposes e;ui%alent to:

(%pmo2ie)Ftitle
6oth e:pressions pmo2ie.>title and (%pmo2ie)Ftitle are %alid and both mean that "e are e%aluatin the member title o$ the data stru#ture pointed by a pointer #alled pmo2ie& 2t must be #learly di$$erentiated $rom:

%pmo2ieFtitle
"hi#h is e;ui%alent to:

%(pmo2ieFtitle)
'nd that "ould a##ess the %alue pointed by a hypotheti#al pointer member #alled title o$ the stru#ture ob?e#t pmo2ie ."hi#h in this #ase "ould not be a pointer0& The $ollo"in panel summariDes possible #ombinations o$ pointers and stru#ture members: ><pression What is e"aluated >=ui"alent a&b 5ember b o$ ob?e#t a a1Ob 5ember b o$ ob?e#t pointed by a .Ia0&b Ia&b Falue pointed by member b o$ ob?e#t a I.a&b0

+esting structures
>tru#tures #an also be nested so that a %alid element o$ a stru#ture #an also be in its turn another stru#ture&

struct mo2ies/t { string title; int year; "; struct friends/t { string name; string email; mo2ies/t fa2orite/mo2ie; " c)arlie0 maria; friends/t % pfriends * Mc)arlie;
'$ter the pre%ious de#laration "e #ould use any o$ the $ollo"in e:pressions:

c)arlieFname mariaFfa2orite/mo2ieFtitle c)arlieFfa2orite/mo2ieFyear pfriends.>fa2orite/mo2ieFyear


."here, by the "ay, the last t"o e:pressions re$er to the same member0&

Other &ata 'ypes


&efined data types 0typedef2

Published by Juan Soulie


Last update on Jan 18, 2008 at 11:@Gam UTC

C// allo"s the de$inition o$ our o"n types based on other e:istin data types& =e #an do this usin the -ey"ord typedef, "hose $ormat is:

typedef e1isting/type ne(/type/name ;


"here e1isting/type is a C// $undamental or #ompound type and ne(/type/name is the name $or the ne" type "e are de$inin & *or e:ample:

typedef typedef typedef typedef

c)ar C; unsigned int W<5V; c)ar % pC)ar; c)ar field P+!Q;

2n this #ase "e ha%e de$ined $our data types: C, W<5V, pC)ar and field as c)ar, unsigned int, c)ar% and c)arP+!Q respe#ti%ely, that "e #ould per$e#tly use in de#larations later as any other %alid type:

C myc)ar0 anot)erc)ar0 %ptc-; W<5V my(ord; pC)ar ptc,; field name; typedef does not #reate di$$erent types& 2t only #reates synonyms o$ e:istin types& That means that the type o$ my(ord #an be #onsidered to be either W<5V or unsigned int, sin#e both are in $a#t the
same type&

typedef #an be use$ul to de$ine an alias $or a type that is $re;uently used "ithin a pro ram& 2t is also
use$ul to de$ine types "hen it is possible that "e "ill need to #han e the type in later %ersions o$ our pro ram, or i$ a type you "ant to use has a name that is too lon or #on$usin &

Fnions
Unions allo" one same portion o$ memory to be a##essed as di$$erent data types, sin#e all o$ them are in $a#t the same lo#ation in memory& 2ts de#laration and use is similar to the one o$ stru#tures but its $un#tionality is totally di$$erent:

union union/name { mem&er/type- mem&er/name-; mem&er/type, mem&er/name,; mem&er/typeD mem&er/nameD; F F " o&Uect/names;
'll the elements o$ the union de#laration o##upy the same physi#al spa#e in memory& 2ts siDe is the one o$ the reatest element o$ the de#laration& *or e:ample:

union mytypes/t { c)ar c; int i; float f;

" mytypes;
de$ines three elements:

mytypesFc mytypesFi mytypesFf


ea#h one "ith a di$$erent data type& >in#e all o$ them are re$errin to the same lo#ation in memory, the modi$i#ation o$ one o$ the elements "ill a$$e#t the %alue o$ all o$ them& =e #annot store di$$erent %alues in them independent o$ ea#h other& )ne o$ the uses a union may ha%e is to unite an elementary type "ith an array or stru#tures o$ smaller elements& *or e:ample:

union mi1/t { long l; struct { s)ort )i; s)ort lo; " s; c)ar cPBQ; " mi1;
de$ines three names that allo" us to a##ess the same roup o$ G bytes: mi1Fl, mi1Fs and mi1Fc and "hi#h "e #an use a##ordin to ho" "e "ant to a##ess these bytes, as i$ they "ere a sin le long1 type data, as i$ they "ere t"o s)ort elements or as an array o$ c)ar elements, respe#ti%ely& 2 ha%e mi:ed types, arrays and stru#tures in the union so that you #an see the di$$erent "ays that "e #an a##ess the data& *or a little-endian system .most PC plat$orms0, this union #ould be represented as:

The e:a#t ali nment and order o$ the members o$ a union in memory is plat$orm dependant& There$ore be a"are o$ possible portability issues "ith this type o$ use&

Anonymous unions
2n C// "e ha%e the option to de#lare anonymous unions& 2$ "e de#lare a union "ithout any name, the union "ill be anonymous and "e "ill be able to a##ess its members dire#tly by their member names& *or e:ample, loo- at the di$$eren#e bet"een these t"o stru#ture de#larations: structure Bith regular union structure Bith anonymous union

struct { c)ar titleP+!Q; c)ar aut)orP+!Q; union { float dollars; int yens; " price; " &oo';

struct { c)ar titleP+!Q; c)ar aut)orP+!Q; union { float dollars; int yens; "; " &oo';

The only di$$eren#e bet"een the t"o pie#es o$ #ode is that in the $irst one "e ha%e i%en a name to the union .price0 and in the se#ond one "e ha%e not& The di$$eren#e is seen "hen "e a##ess the members dollars and yens o$ an ob?e#t o$ this type& *or an ob?e#t o$ the $irst type, it "ould be:

&oo'FpriceFdollars &oo'FpriceFyens
"hereas $or an ob?e#t o$ the se#ond type, it "ould be:

&oo'Fdollars &oo'Fyens
)n#e a ain 2 remind you that be#ause it is a union and not a stru#t, the members dollars and yens o##upy the same physi#al spa#e in the memory so they #annot be used to store t"o di$$erent %alues simultaneously& Aou #an set a %alue $or price in dollars or in yens, but not in both&

>numerations 0enum2
9numerations #reate ne" data types to #ontain somethin di$$erent that is not limited to the %alues $undamental data types may ta-e& 2ts $orm is the $ollo"in :

enum enumeration/name { 2alue-0 2alue,0 2alueD0 F F " o&Uect/names;

*or e:ample, "e #ould #reate a ne" type o$ %ariable #alled color to store #olors "ith the $ollo"in de#laration:

enum colors/t {&lac'0 &lue0 green0 cyan0 red0 purple0 yello(0 ()ite";
,oti#e that "e do not in#lude any $undamental data type in the de#laration& To say it someho", "e ha%e #reated a "hole ne" data type $rom s#rat#h "ithout basin it on any other e:istin type& The possible %alues that %ariables o$ this ne" type color/t may ta-e are the ne" #onstant %alues in#luded "ithin bra#es& *or e:ample, on#e the colors/t enumeration is de#lared the $ollo"in e:pressions "ill be %alid:

colors/t mycolor; mycolor * &lue; if (mycolor ** green) mycolor * red;


9numerations are type #ompatible "ith numeri# %ariables, so their #onstants are al"ays assi ned an inte er numeri#al %alue internally& 2$ it is not spe#i$ied, the inte er %alue e;ui%alent to the $irst possible %alue is e;ui%alent to ! and the $ollo"in ones $ollo" a /1 pro ression& Thus, in our data type colors/t that "e ha%e de$ined abo%e, &lac' "ould be e;ui%alent to !, &lue "ould be e;ui%alent to -, green to ,, and so on& =e #an e:pli#itly spe#i$y an inte er %alue $or any o$ the #onstant %alues that our enumerated type #an ta-e& 2$ the #onstant %alue that $ollo"s it is not i%en an inte er %alue, it is automati#ally assumed the same %alue as the pre%ious one plus one& *or e:ample:

enum mont)s/t { Uanuary*-0 fe&ruary0 marc)0 april0 may0 Uune0 Uuly0 august0

septem&er0 octo&er0 no2em&er0 decem&er" y,';


2n this #ase, %ariable y,' o$ enumerated type mont)s/t #an #ontain any o$ the 12 possible %alues that o $rom Uanuary to decem&er and that are e;ui%alent to %alues bet"een - and -, .not bet"een ! and --, sin#e "e ha%e made Uanuary e;ual to -0&

Classes 0(2

Published by Juan Soulie


Last update on Jan 28, 2008 at 8:@0am UTC

' class is an e:panded #on#ept o$ a data stru#ture: instead o$ holdin only data, it #an hold both data and $un#tions& 'n object is an instantiation o$ a #lass& 2n terms o$ %ariables, a #lass "ould be the type, and an ob?e#t "ould be the %ariable& Classes are enerally de#lared usin the -ey"ord class, "ith the $ollo"in $ormat:

class class/name { access/specifier/-A mem&er-; access/specifier/,A mem&er,; FFF " o&Uect/names;


=here class/name is a %alid identi$ier $or the #lass, o&Uect/names is an optional list o$ names $or ob?e#ts o$ this #lass& The body o$ the de#laration #an #ontain members, that #an be either data or $un#tion de#larations, and optionally a##ess spe#i$iers& 'll is %ery similar to the de#laration on data stru#tures, e:#ept that "e #an no" in#lude also $un#tions and members, but also this ne" thin #alled access specifier& 'n a##ess spe#i$ier is one o$ the $ollo"in three -ey"ords: pri2ate, pu&lic or protected& These spe#i$iers modi$y the a##ess ri hts that the members $ollo"in them a#;uire:

pri2ate members o$ a #lass are a##essible only $rom "ithin other members o$ the same #lass
or $rom their friends&

protected members are a##essible $rom members o$ their same #lass and $rom their $riends,
but also $rom members o$ their deri%ed #lasses& *inally, pu&lic members are a##essible $rom any"here "here the ob?e#t is %isible&

6y de$ault, all members o$ a #lass de#lared "ith the class -ey"ord ha%e pri%ate a##ess $or all its members& There$ore, any member that is de#lared be$ore one other #lass spe#i$ier automati#ally has pri%ate a##ess& *or e:ample:

class C5ectangle { int 10 y; pu&licA 2oid set/2alues (int0int); int area (2oid); " rect;
De#lares a #lass .i&e&, a type0 #alled C5ectangle and an ob?e#t .i&e&, a %ariable0 o$ this #lass #alled rect& This #lass #ontains $our members: t"o data members o$ type int .member 1 and member y0 "ith pri%ate a##ess .be#ause pri%ate is the de$ault a##ess le%el0 and t"o member $un#tions "ith publi# a##ess: set/2alues() and area(), o$ "hi#h $or no" "e ha%e only in#luded their de#laration, not their de$inition& ,oti#e the di$$eren#e bet"een the #lass name and the ob?e#t name: 2n the pre%ious e:ample, C5ectangle "as the #lass name .i&e&, the type0, "hereas re#t "as an ob?e#t o$ type C5ectangle& 2t is the same relationship int and a ha%e in the $ollo"in de#laration:

int a;
"here int is the type name .the #lass0 and a is the %ariable name .the ob?e#t0& '$ter the pre%ious de#larations o$ C5ectangle and rect, "e #an re$er "ithin the body o$ the pro ram to any o$ the publi# members o$ the ob?e#t rect as i$ they "ere normal $un#tions or normal %ariables, ?ust by puttin the ob?e#tCs name $ollo"ed by a dot . F0 and then the name o$ the member& 'll %ery similar to "hat "e did "ith plain data stru#tures be$ore& *or e:ample:

rectFset/2alues (D0B); myarea * rectFarea();


The only members o$ re#t that "e #annot a##ess $rom the body o$ our pro ram outside the #lass are 1 and y, sin#e they ha%e pri%ate a##ess and they #an only be re$erred $rom "ithin other members o$ that same #lass& Eere is the #omplete e:ample o$ #lass C+e#tan le:

// classes e1ample #include <iostream> using namespace std; class C5ectangle { int 10 y; pu&licA 2oid set/2alues (int0int); int area () {return (1%y);" "; 2oid C5ectangleAAset/2alues (int a0 int &) { 1 * a; y * &; " int main () { C5ectangle rect; rectFset/2alues (D0B); cout << "areaA " << rectFarea(); return !; "

areaA -,

The most important ne" thin in this #ode is the operator o$ s#ope . AA, t"o #olons0 in#luded in the de$inition o$ set/2alues()& 2t is used to de$ine a member o$ a #lass $rom outside the #lass de$inition itsel$& Aou may noti#e that the de$inition o$ the member $un#tion area() has been in#luded dire#tly "ithin the de$inition o$ the C5ectangle #lass i%en its e:treme simpli#ity, "hereas set/2alues() has only its prototype de#lared "ithin the #lass, but its de$inition is outside it& 2n this outside de#laration, "e must use the operator o$ s#ope .AA0 to spe#i$y that "e are de$inin a $un#tion that is a member o$ the #lass C5ectangle and not a re ular lobal $un#tion& The s#ope operator .AA0 spe#i$ies the #lass to "hi#h the member bein de#lared belon s, rantin e:a#tly the same s#ope properties as i$ this $un#tion de$inition "as dire#tly in#luded "ithin the #lass de$inition& *or e:ample, in the $un#tion set/2alues() o$ the pre%ious #ode, "e ha%e been able to use the %ariables 1 and y, "hi#h are pri%ate members o$ #lass C5ectangle, "hi#h means they are only a##essible $rom other members o$ their #lass&

The only di$$eren#e bet"een de$inin a #lass member $un#tion #ompletely "ithin its #lass or to in#lude only the prototype and later its de$inition, is that in the $irst #ase the $un#tion "ill automati#ally be #onsidered an inline member $un#tion by the #ompiler, "hile in the se#ond it "ill be a normal .not1 inline0 #lass member $un#tion, "hi#h in $a#t supposes no di$$eren#e in beha%ior& 5embers 1 and y ha%e pri%ate a##ess .remember that i$ nothin else is said, all members o$ a #lass de$ined "ith -ey"ord #lass ha%e pri%ate a##ess0& 6y de#larin them pri%ate "e deny a##ess to them $rom any"here outside the #lass& This ma-es sense, sin#e "e ha%e already de$ined a member $un#tion to set %alues $or those members "ithin the ob?e#t: the member $un#tion set/2alues()& There$ore, the rest o$ the pro ram does not need to ha%e dire#t a##ess to them& Perhaps in a so simple e:ample as this, it is di$$i#ult to see an utility in prote#tin those t"o %ariables, but in reater pro?e#ts it may be %ery important that %alues #annot be modi$ied in an une:pe#ted "ay .une:pe#ted $rom the point o$ %ie" o$ the ob?e#t0& )ne o$ the reater ad%anta es o$ a #lass is that, as any other type, "e #an de#lare se%eral ob?e#ts o$ it& *or e:ample, $ollo"in "ith the pre%ious e:ample o$ #lass C5ectangle, "e #ould ha%e de#lared the ob?e#t rect& in addition to the ob?e#t rect:

// e1ampleA one class0 t(o o&Uects #include <iostream> using namespace std; class C5ectangle { int 10 y; pu&licA 2oid set/2alues (int0int); int area () {return (1%y);" "; 2oid C5ectangleAAset/2alues (int a0 int &) { 1 * a; y * &; " int main () { C5ectangle rect0 rect&; rectFset/2alues (D0B); rect&Fset/2alues (+0C); cout << "rect areaA " << rectFarea() << endl; cout << "rect& areaA " << rect&Farea() << endl; return !; "

rect areaA -, rect& areaA D!

2n this #on#rete #ase, the #lass .type o$ the ob?e#ts0 to "hi#h "e are tal-in about is C5ectangle, o$ "hi#h there are t"o instan#es or ob?e#ts: rect and rect&& 9a#h one o$ them has its o"n member %ariables and member $un#tions& ,oti#e that the #all to rectFarea() does not i%e the same result as the #all to rect&Farea()& This is be#ause ea#h ob?e#t o$ #lass C+e#tan le has its o"n %ariables 1 and y, as they, in some "ay, ha%e also their o"n $un#tion members set/2alue() and area() that ea#h uses its ob?e#tCs o"n %ariables to operate& That is the basi# #on#ept o$ object-oriented programming: Data and $un#tions are both members o$ the ob?e#t& =e no lon er use sets o$ lobal %ariables that "e pass $rom one $un#tion to another as parameters, but instead "e handle ob?e#ts that ha%e their o"n data and $un#tions embedded as

members& ,oti#e that "e ha%e not had to i%e any parameters in any o$ the #alls to rectFarea or rect&Farea& Those member $un#tions dire#tly used the data members o$ their respe#ti%e ob?e#ts rect and rect&&

Constructors and destructors


)b?e#ts enerally need to initialiDe %ariables or assi n dynami# memory durin their pro#ess o$ #reation to be#ome operati%e and to a%oid returnin une:pe#ted %alues durin their e:e#ution& *or e:ample, "hat "ould happen i$ in the pre%ious e:ample "e #alled the member $un#tion area() be$ore ha%in #alled $un#tion set/2alues()Q Probably "e "ould ha%e otten an undetermined result sin#e the members 1 and y "ould ha%e ne%er been assi ned a %alue& 2n order to a%oid that, a #lass #an in#lude a spe#ial $un#tion #alled constructor, "hi#h is automati#ally #alled "hene%er a ne" ob?e#t o$ this #lass is #reated& This #onstru#tor $un#tion must ha%e the same name as the #lass, and #annot ha%e any return typeL not e%en 2oid& =e are oin to implement C5ectangle in#ludin a #onstru#tor:

// e1ampleA class constructor #include <iostream> using namespace std; class C5ectangle { int (idt)0 )eig)t; pu&licA C5ectangle (int0int); int area () {return ((idt)%)eig)t);" "; C5ectangleAAC5ectangle (int a0 int &) { (idt) * a; )eig)t * &; " int main () { C5ectangle rect (D0B); C5ectangle rect& (+0C); cout << "rect areaA " << rectFarea() << endl; cout << "rect& areaA " << rect&Farea() << endl; return !; "

rect areaA -, rect& areaA D!

's you #an see, the result o$ this e:ample is identi#al to the pre%ious one& 6ut no" "e ha%e remo%ed the member $un#tion set/2alues(), and ha%e in#luded instead a #onstru#tor that per$orms a similar a#tion: it initialiDes the %alues o$ 1 and y "ith the parameters that are passed to it& ,oti#e ho" these ar uments are passed to the #onstru#tor at the moment at "hi#h the ob?e#ts o$ this #lass are #reated:

C5ectangle rect (D0B); C5ectangle rect& (+0C);


Constru#tors #annot be #alled e:pli#itly as i$ they "ere re ular member $un#tions& They are only e:e#uted "hen a ne" ob?e#t o$ that #lass is #reated&

Aou #an also see ho" neither the #onstru#tor prototype de#laration ."ithin the #lass0 nor the latter #onstru#tor de$inition in#lude a return %alueL not e%en 2oid& The destructor $ul$ills the opposite $un#tionality& 2t is automati#ally #alled "hen an ob?e#t is destroyed, either be#ause its s#ope o$ e:isten#e has $inished .$or e:ample, i$ it "as de$ined as a lo#al ob?e#t "ithin a $un#tion and the $un#tion ends0 or be#ause it is an ob?e#t dynami#ally assi ned and it is released usin the operator delete& The destru#tor must ha%e the same name as the #lass, but pre#eded "ith a tilde si n . O0 and it must also return no %alue& The use o$ destru#tors is espe#ially suitable "hen an ob?e#t assi ns dynami# memory durin its li$etime and at the moment o$ bein destroyed "e "ant to release the memory that the ob?e#t "as allo#ated&

// e1ample on constructors and destructors #include <iostream> using namespace std; class C5ectangle { int %(idt)0 %)eig)t; pu&licA C5ectangle (int0int); OC5ectangle (); int area () {return (%(idt) % %)eig)t);" "; C5ectangleAAC5ectangle (int a0 int &) { (idt) * ne( int; )eig)t * ne( int; %(idt) * a; %)eig)t * &; " C5ectangleAAOC5ectangle () { delete (idt); delete )eig)t; " int main () { C5ectangle rect (D0B)0 rect& (+0C); cout << "rect areaA " << rectFarea() << endl; cout << "rect& areaA " << rect&Farea() << endl; return !; "

rect areaA -, rect& areaA D!

O"erloading Constructors
Li-e any other $un#tion, a #onstru#tor #an also be o%erloaded "ith more than one $un#tion that ha%e the same name but di$$erent types or number o$ parameters& +emember that $or o%erloaded $un#tions the #ompiler "ill #all the one "hose parameters mat#h the ar uments used in the $un#tion #all& 2n the #ase o$ #onstru#tors, "hi#h are automati#ally #alled "hen an ob?e#t is #reated, the one e:e#uted is the one that mat#hes the ar uments passed on the ob?e#t de#laration:

// o2erloading class constructors #include <iostream> using namespace std;

rect areaA -, rect& areaA ,+

class C5ectangle { int (idt)0 )eig)t; pu&licA C5ectangle (); C5ectangle (int0int); int area (2oid) {return ((idt)%)eig)t);" "; C5ectangleAAC5ectangle () { (idt) * +; )eig)t * +; " C5ectangleAAC5ectangle (int a0 int &) { (idt) * a; )eig)t * &; " int main () { C5ectangle rect (D0B); C5ectangle rect&; cout << "rect areaA " << rectFarea() << endl; cout << "rect& areaA " << rect&Farea() << endl; return !; "
2n this #ase, rect& "as de#lared "ithout any ar uments, so it has been initialiDed "ith the #onstru#tor that has no parameters, "hi#h initialiDes both (idt) and )eig)t "ith a %alue o$ @& (mportant) ,oti#e ho" i$ "e de#lare a ne" ob?e#t and "e "ant to use its de$ault #onstru#tor .the one "ithout parameters0, "e do not in#lude parentheses ():

C5ectangle rect&; // rig)t C5ectangle rect&(); // (rong

&efault constructor
2$ you do not de#lare any #onstru#tors in a #lass de$inition, the #ompiler assumes the #lass to ha%e a de$ault #onstru#tor "ith no ar uments& There$ore, a$ter de#larin a #lass li-e this one:

class C61ample { pu&licA int a0&0c; 2oid multiply (int n0 int m) { a*n; &*m; c*a%&; "; ";
The #ompiler assumes that C61ample has a de$ault #onstru#tor, so you #an de#lare ob?e#ts o$ this #lass by simply de#larin them "ithout any ar uments:

C61ample e1;
6ut as soon as you de#lare your o"n #onstru#tor $or a #lass, the #ompiler no lon er pro%ides an impli#it de$ault #onstru#tor& >o you ha%e to de#lare all ob?e#ts o$ that #lass a##ordin to the #onstru#tor prototypes you de$ined $or the #lass:

class C61ample { pu&licA int a0&0c; C61ample (int n0 int m) { a*n; &*m; "; 2oid multiply () { c*a%&; "; ";
Eere "e ha%e de#lared a #onstru#tor that ta-es t"o parameters o$ type int& There$ore the $ollo"in ob?e#t de#laration "ould be #orre#t:

C61ample e1 (,0D);
6ut,

C61ample e1;
=ould not be #orre#t, sin#e "e ha%e de#lared the #lass to ha%e an e:pli#it #onstru#tor, thus repla#in the de$ault #onstru#tor& 6ut the #ompiler not only #reates a de$ault #onstru#tor $or you i$ you do not spe#i$y your o"n& 2t pro%ides three spe#ial member $un#tions in total that are impli#itly de#lared i$ you do not de#lare your o"n& These are the copy constructor, the copy assignment operator, and the de$ault destru#tor& The #opy #onstru#tor and the #opy assi nment operator #opy all the data #ontained in another ob?e#t to the data members o$ the #urrent ob?e#t& *or C61ample, the #opy #onstru#tor impli#itly de#lared by the #ompiler "ould be somethin similar to:

C61ampleAAC61ample (const C61ampleM r2) { a*r2Fa; &*r2F&; c*r2Fc; "


There$ore, the t"o $ollo"in ob?e#t de#larations "ould be #orre#t:

C61ample e1 (,0D); C61ample e1, (e1);

// copy constructor (data copied from e1)

Pointers to classes
2t is per$e#tly %alid to #reate pointers that point to #lasses& =e simply ha%e to #onsider that on#e de#lared, a #lass be#omes a %alid type, so "e #an use the #lass name as the type $or the pointer& *or e:ample:

C5ectangle % prect;
is a pointer to an ob?e#t o$ #lass C5ectangle& 's it happened "ith data stru#tures, in order to re$er dire#tly to a member o$ an ob?e#t pointed by a pointer "e #an use the arro" operator ..>0 o$ indire#tion& Eere is an e:ample "ith some possible #ombinations:

// pointer to classes e1ample #include <iostream> using namespace std; class C5ectangle { int (idt)0 )eig)t; pu&licA

a areaA , %& areaA -, %c areaA , dP!Q areaA D! dP-Q areaA +C

2oid set/2alues (int0 int); int area (2oid) {return ((idt) % )eig)t);" "; 2oid C5ectangleAAset/2alues (int a0 int &) { (idt) * a; )eig)t * &; " int main () { C5ectangle a0 %&0 %c; C5ectangle % d * ne( C5ectangleP,Q; &* ne( C5ectangle; c* Ma; aFset/2alues (-0,); &.>set/2alues (D0B); d.>set/2alues (+0C); dP-QFset/2alues (E0T); cout << "a areaA " << aFarea() << endl; cout << "%& areaA " << &.>area() << endl; cout << "%c areaA " << c.>area() << endl; cout << "dP!Q areaA " << dP!QFarea() << endl; cout << "dP-Q areaA " << dP-QFarea() << endl; deletePQ d; delete &; return !; "
,e:t you ha%e a summary on ho" #an you read some pointer and #lass operators . %, M, F, .>, P Q0 that appear in the pre%ious e:ample: e<pression can be read as I: pointed by : T: address o$ : :&y member y o$ ob?e#t : :1Oy member y o$ ob?e#t pointed by : .I:0&y member y o$ ob?e#t pointed by : .e;ui%alent to the pre%ious one0 :R0S $irst ob?e#t pointed by : :R1S se#ond ob?e#t pointed by : :RnS .n/10th ob?e#t pointed by : 6e sure that you understand the lo i# under all o$ these e:pressions be$ore pro#eedin "ith the ne:t se#tions& 2$ you ha%e doubts, read a ain this se#tion andHor #onsult the pre%ious se#tions about pointers and data stru#tures&

Classes defined Bith struct and union


Classes #an be de$ined not only "ith -ey"ord class, but also "ith -ey"ords struct and union& The #on#epts o$ #lass and data stru#ture are so similar that both -ey"ords . struct and class0 #an be used in C// to de#lare #lasses .i&e& structs #an also ha%e $un#tion members in C//, not only

data members0& The only di$$eren#e bet"een both is that members o$ #lasses de#lared "ith the -ey"ord struct ha%e publi# a##ess by de$ault, "hile members o$ #lasses de#lared "ith the -ey"ord class ha%e pri%ate a##ess& *or all other purposes both -ey"ords are e;ui%alent& The #on#ept o$ unions is di$$erent $rom that o$ #lasses de#lared "ith struct and class, sin#e unions only store one data member at a time, but ne%ertheless they are also #lasses and #an thus also hold $un#tion members& The de$ault a##ess in union #lasses is publi#&

Classes 0((2
O"erloading operators
int a0 &0 c; a * & + c;

Published by Juan Soulie


Last update on Jul 14, 2004 at 4:G2am UTC

C// in#orporates the option to use standard operators to per$orm operations "ith #lasses in addition to "ith $undamental types& *or e:ample:

This is ob%iously %alid #ode in C//, sin#e the di$$erent %ariables o$ the addition are all $undamental types& ,e%ertheless, it is not so ob%ious that "e #ould per$orm an operation similar to the $ollo"in one:

struct { string product; float price; " a0 &0 c; a * & + c;


2n $a#t, this "ill #ause a #ompilation error, sin#e "e ha%e not de$ined the beha%ior our #lass should ha%e "ith addition operations& Eo"e%er, than-s to the C// $eature to o%erload operators, "e #an desi n #lasses able to per$orm operations usin standard operators& Eere is a list o$ all the operators that #an be o%erloaded: O"erloadable operators

+ . <<* >>* O M* delete

% / ** * H* N* ne(PQ

* < <* >* MM NN deletePQ

> ++ L*

+* .. PQ

.* L ()

%* M 0

/* H .>%

<< .>

>> N ne(

To o%erload an operator in order to use it "ith #lasses "e de#lare operator functions, "hi#h are re ular $un#tions "hose names are the operator -ey"ord $ollo"ed by the operator si n that "e "ant to o%erload& The $ormat is:

type operator sign (parameters) { /%FFF%/ "


Eere you ha%e an e:ample that o%erloads the addition operator .+0& =e are oin to #reate a #lass to store bidimensional %e#tors and then "e are oin to add t"o o$ them: a(D0-) and &(-0,)& The addition o$ t"o bidimensional %e#tors is an operation as simple as addin the t"o 1 #oordinates to obtain the resultin 1 #oordinate and addin the t"o y #oordinates to obtain the resultin y& 2n this #ase the result "ill be (D+-0-+,) * (B0D)&

// 2ectorsA o2erloading operators e1ample #include <iostream> using namespace std; class CXector { pu&licA int 10y; CXector () {"; CXector (int0int); CXector operator + (CXector); ";

B0D

CXectorAACXector (int a0 int &) { 1 * a; y * &; " CXector CXectorAAoperator+ (CXector param) { CXector temp; tempF1 * 1 + paramF1; tempFy * y + paramFy; return (temp); " int main () { CXector a (D0-); CXector & (-0,); CXector c; c * a + &; cout << cF1 << "0" << cFy; return !; "
2t may be a little #on$usin to see so many times the CXector identi$ier& 6ut, #onsider that some o$ them re$er to the #lass name .type0 CXector and some others are $un#tions "ith that name .#onstru#tors must ha%e the same name as the #lass0& Do not #on$use them:

CXector (int0 int); CXector operator+ (CXector);

// function name CXector (constructor) // function returns a CXector

The $un#tion operator+ o$ #lass CXector is the one that is in #har e o$ o%erloadin the addition operator .+0& This $un#tion #an be #alled either impli#itly usin the operator, or e:pli#itly usin the $un#tion name:

c * a + &; c * aFoperator+ (&);


6oth e:pressions are e;ui%alent& ,oti#e also that "e ha%e in#luded the empty #onstru#tor ."ithout parameters0 and "e ha%e de$ined it "ith an empty blo#-:

CXector () { ";
This is ne#essary, sin#e "e ha%e e:pli#itly de#lared another #onstru#tor:

CXector (int0 int);


'nd "hen "e e:pli#itly de#lare any #onstru#tor, "ith any number o$ parameters, the de$ault #onstru#tor "ith no parameters that the #ompiler #an de#lare automati#ally is not de#lared, so "e need to de#lare it oursel%es in order to be able to #onstru#t ob?e#ts o$ this type "ithout parameters& )ther"ise, the de#laration:

CXector c;
in#luded in main() "ould not ha%e been %alid&

'ny"ay, 2 ha%e to "arn you that an empty blo#- is a bad implementation $or a #onstru#tor, sin#e it does not $ul$ill the minimum $un#tionality that is enerally e:pe#ted $rom a #onstru#tor, "hi#h is the initialiDation o$ all the member %ariables in its #lass& 2n our #ase this #onstru#tor lea%es the %ariables 1 and y unde$ined& There$ore, a more ad%isable de$inition "ould ha%e been somethin similar to this:

CXector () { 1*!; y*!; ";


"hi#h in order to simpli$y and sho" only the point o$ the #ode 2 ha%e not in#luded in the e:ample& 's "ell as a #lass in#ludes a de$ault #onstru#tor and a #opy #onstru#tor e%en i$ they are not de#lared, it also in#ludes a de$ault de$inition $or the assi nment operator . *0 "ith the #lass itsel$ as parameter& The beha%ior "hi#h is de$ined by de$ault is to #opy the "hole #ontent o$ the data members o$ the ob?e#t passed as ar ument .the one at the ri ht side o$ the si n0 to the one at the le$t side:

CXector d (,0D); CXector e; e * d; // copy assignment operator


The #opy assi nment operator $un#tion is the only operator member $un#tion implemented by de$ault& )$ #ourse, you #an rede$ine it to any other $un#tionality that you "ant, li-e $or e:ample, #opy only #ertain #lass members or per$orm additional initialiDation pro#edures& The o%erload o$ operators does not $or#e its operation to bear a relation to the mathemati#al or usual meanin o$ the operator, althou h it is re#ommended& *or e:ample, the #ode may not be %ery intuiti%e i$ you use operator + to subtra#t t"o #lasses or operator** to $ill "ith Deros a #lass, althou h it is per$e#tly possible to do so& 'lthou h the prototype o$ a $un#tion operator+ #an seem ob%ious sin#e it ta-es "hat is at the ri ht side o$ the operator as the parameter $or the operator member $un#tion o$ the ob?e#t at its le$t side, other operators may not be so ob%ious& Eere you ha%e a table "ith a summary on ho" the di$$erent operator $un#tions ha%e to be de#lared .repla#e V by the operator in ea#h #ase0: ><pression Operator Va / 1 I T B W // 11 aV // 11 / 1 I H M X T Y P O NN BN PN ON PP OO TT aVb YY , aVb N /N 1N IN HN MN XN TN YN PPN OON RS a.b, #&&&0 .0 a1O: 1O #ember function '::operatorV.0 '::operatorV.int0 '::operatorV .60 Dlobal function operatorV.'0 operatorV.',int0 operatorV.',60

'::operatorV .60 1 '::operator.0 .6, C&&&0 1 '::operator1O.0 1

=here a is an ob?e#t o$ #lass >, & is an ob?e#t o$ #lass ? and c is an ob?e#t o$ #lass C& Aou #an see in this panel that there are t"o "ays to o%erload some #lass operators: as a member $un#tion and as a lobal $un#tion& 2ts use is indistin#t, ne%ertheless 2 remind you that $un#tions that are not members o$ a #lass #annot a##ess the pri%ate or prote#ted members o$ that #lass unless the lobal $un#tion is its $riend .$riendship is e:plained later0&

'he EeyBord this


The -ey"ord t)is represents a pointer to the ob?e#t "hose member $un#tion is bein e:e#uted& 2t is a pointer to the ob?e#t itsel$& )ne o$ its uses #an be to #he#- i$ a parameter passed to a member $un#tion is the ob?e#t itsel$& *or e:ample,

// t)is #include <iostream> using namespace std; class CVummy { pu&licA int isitme (CVummyM param); "; int CVummyAAisitme (CVummyM param) { if (Mparam ** t)is) return true; else return false; " int main () { CVummy a; CVummy% & * Ma; if ( &.>isitme(a) ) cout << "yes0 Ma is &"; return !; "

yes0 Ma is &

2t is also $re;uently used in operator* member $un#tions that return ob?e#ts by re$eren#e .a%oidin the use o$ temporary ob?e#ts0& *ollo"in "ith the %e#torCs e:amples seen be$ore "e #ould ha%e "ritten an operator* $un#tion similar to this one:

CXectorM CXectorAAoperator* (const CXectorM param) { 1*paramF1; y*paramFy; return %t)is; "
2n $a#t this $un#tion is %ery similar to the #ode that the #ompiler enerates impli#itly $or this #lass i$ "e do not in#lude an operator* member $un#tion to #opy ob?e#ts o$ this #lass&

Static members
' #lass #an #ontain static members, either data or $un#tions& >tati# data members o$ a #lass are also -no"n as <#lass %ariables<, be#ause there is only one uni;ue %alue $or all the ob?e#ts o$ that same #lass& Their #ontent is not di$$erent $rom one ob?e#t o$ this #lass to another& *or e:ample, it may be used $or a %ariable "ithin a #lass that #an #ontain a #ounter "ith the number o$ ob?e#ts o$ that #lass that are #urrently allo#ated, as in the $ollo"in e:ample:

// static mem&ers in classes #include <iostream> using namespace std; class CVummy { pu&licA static int n; CVummy () { n++; "; OCVummy () { n..; "; ";

E C

int CVummyAAn*!; int main () { CVummy a; CVummy &P+Q; CVummy % c * ne( CVummy; cout << aFn << endl; delete c; cout << CVummyAAn << endl; return !; "
2n $a#t, stati# members ha%e the same properties as lobal %ariables but they en?oy #lass s#ope& *or that reason, and to a%oid them to be de#lared se%eral times, "e #an only in#lude the prototype .its de#laration0 in the #lass de#laration but not its de$inition .its initialiDation0& 2n order to initialiDe a stati# data1member "e must in#lude a $ormal de$inition outside the #lass, in the lobal s#ope, as in the pre%ious e:ample:

int CVummyAAn*!;
6e#ause it is a uni;ue %ariable %alue $or all the ob?e#ts o$ the same #lass, it #an be re$erred to as a member o$ any ob?e#t o$ that #lass or e%en dire#tly by the #lass name .o$ #ourse this is only %alid $or stati# members0:

cout << aFn; cout << CVummyAAn;


These t"o #alls in#luded in the pre%ious e:ample are re$errin to the same %ariable: the stati# %ariable n "ithin #lass CVummy shared by all ob?e#ts o$ this #lass& )n#e a ain, 2 remind you that in $a#t it is a lobal %ariable& The only di$$eren#e is its name and possible a##ess restri#tions outside its #lass& Just as "e may in#lude stati# data "ithin a #lass, "e #an also in#lude stati# $un#tions& They represent the same: they are lobal $un#tions that are #alled as i$ they "ere ob?e#t members o$ a i%en #lass& They #an only re$er to stati# data, in no #ase to non1stati# members o$ the #lass, as "ell as they do not allo" the use o$ the -ey"ord t)is, sin#e it ma-es re$eren#e to an ob?e#t pointer and these $un#tions in $a#t are not members o$ any ob?e#t but dire#t members o$ the #lass&

*riendship and inheritance


*riend functions

Published by Juan Soulie


Last update on )#t 11, 2004 at 9:03am UTC

2n prin#iple, pri%ate and prote#ted members o$ a #lass #annot be a##essed $rom outside the same #lass in "hi#h they are de#lared& Eo"e%er, this rule does not a$$e#t friends& *riends are $un#tions or #lasses de#lared as su#h& 2$ "e "ant to de#lare an e:ternal $un#tion as $riend o$ a #lass, thus allo"in this $un#tion to ha%e a##ess to the pri%ate and prote#ted members o$ this #lass, "e do it by de#larin a prototype o$ this e:ternal $un#tion "ithin the #lass, and pre#edin it "ith the -ey"ord friend:

// friend functions #include <iostream> using namespace std; class C5ectangle { int (idt)0 )eig)t; pu&licA 2oid set/2alues (int0 int); int area () {return ((idt) % )eig)t);" friend C5ectangle duplicate (C5ectangle); "; 2oid C5ectangleAAset/2alues (int a0 int &) { (idt) * a; )eig)t * &; " C5ectangle duplicate (C5ectangle rectparam) { C5ectangle rectres; rectresF(idt) * rectparamF(idt)%,; rectresF)eig)t * rectparamF)eig)t%,; return (rectres); " int main () { C5ectangle rect0 rect&; rectFset/2alues (,0D); rect& * duplicate (rect); cout << rect&Farea(); return !; "

,B

The duplicate $un#tion is a $riend o$ C5ectangle& *rom "ithin that $un#tion "e ha%e been able to a##ess the members (idt) and )eig)t o$ di$$erent ob?e#ts o$ type C5ectangle, "hi#h are pri%ate members& ,oti#e that neither in the de#laration o$ duplicate() nor in its later use in main() ha%e

"e #onsidered duplicate a member o$ #lass C5ectangle& 2t isnCtB 2t simply has a##ess to its pri%ate and prote#ted members "ithout bein a member& The $riend $un#tions #an ser%e, $or e:ample, to #ondu#t operations bet"een t"o di$$erent #lasses& (enerally, the use o$ $riend $un#tions is out o$ an ob?e#t1oriented pro rammin methodolo y, so "hene%er possible it is better to use members o$ the same #lass to per$orm operations "ith them& >u#h as in the pre%ious e:ample, it "ould ha%e been shorter to inte rate duplicate() "ithin the #lass C5ectangle&

*riend classes
Just as "e ha%e the possibility to de$ine a $riend $un#tion, "e #an also de$ine a #lass as $riend o$ another one, rantin that $irst #lass a##ess to the prote#ted and pri%ate members o$ the se#ond one&

// friend class #include <iostream> using namespace std; class C74uare; class C5ectangle { int (idt)0 )eig)t; pu&licA int area () {return ((idt) % )eig)t);" 2oid con2ert (C74uare a); "; class C74uare { pri2ateA int side; pu&licA 2oid set/side (int a) {side*a;" friend class C5ectangle; "; 2oid C5ectangleAAcon2ert (C74uare a) { (idt) * aFside; )eig)t * aFside; " int main () { C74uare s4r; C5ectangle rect; s4rFset/side(B); rectFcon2ert(s4r); cout << rectFarea(); return !; "

-C

2n this e:ample, "e ha%e de#lared C5ectangle as a $riend o$ C74uare so that C5ectangle member $un#tions #ould ha%e a##ess to the prote#ted and pri%ate members o$ C74uare, more #on#retely to C74uareAAside, "hi#h des#ribes the side "idth o$ the s;uare& Aou may also see somethin ne" at the be innin o$ the pro ram: an empty de#laration o$ #lass C74uare& This is ne#essary be#ause "ithin the de#laration o$ C5ectangle "e re$er to C>;uare .as a parameter in con2ert()0& The de$inition o$ C74uare is in#luded later, so i$ "e did not in#lude a pre%ious empty de#laration $or C74uare this #lass "ould not be %isible $rom "ithin the de$inition o$ C5ectangle&

Consider that $riendships are not #orresponded i$ "e do not e:pli#itly spe#i$y so& 2n our e:ample, C5ectangle is #onsidered as a $riend #lass by C74uare, but C5ectangle does not #onsider C74uare to be a $riend, so C5ectangle #an a##ess the prote#ted and pri%ate members o$ C74uare but not the re%erse "ay& )$ #ourse, "e #ould ha%e de#lared also C74uare as $riend o$ C5ectangle i$ "e "anted to& 'nother property o$ $riendships is that they are not transitive: The $riend o$ a $riend is not #onsidered to be a $riend unless e:pli#itly spe#i$ied&

(nheritance betBeen classes


' -ey $eature o$ C// #lasses is inheritan#e& 2nheritan#e allo"s to #reate #lasses "hi#h are deri%ed $rom other #lasses, so that they automati#ally in#lude some o$ its <parentCs< members, plus its o"n& *or e:ample, "e are oin to suppose that "e "ant to de#lare a series o$ #lasses that des#ribe poly ons li-e our C5ectangle, or li-e C:riangle& They ha%e #ertain #ommon properties, su#h as both #an be des#ribed by means o$ only t"o sides: hei ht and base& This #ould be represented in the "orld o$ #lasses "ith a #lass CKolygon $rom "hi#h "e "ould deri%e the t"o other ones: C5ectangle and C:riangle&

The #lass CKolygon "ould #ontain members that are #ommon $or both types o$ poly on& 2n our #ase: (idt) and )eig)t& 'nd C5ectangle and C:riangle "ould be its deri%ed #lasses, "ith spe#i$i# $eatures that are di$$erent $rom one type o$ poly on to the other& Classes that are deri%ed $rom others inherit all the a##essible members o$ the base #lass& That means that i$ a base #lass in#ludes a member > and "e deri%e it to another #lass "ith another member #alled ?, the deri%ed #lass "ill #ontain both members > and ?& 2n order to deri%e a #lass $rom another, "e use a #olon . A0 in the de#laration o$ the deri%ed #lass usin the $ollo"in $ormat:

class deri2ed/class/nameA pu&lic &ase/class/name { /%FFF%/ ";


=here deri2ed/class/name is the name o$ the deri%ed #lass and &ase/class/name is the name o$ the #lass on "hi#h it is based& The pu&lic a##ess spe#i$ier may be repla#ed by any one o$ the other a##ess spe#i$iers protected and pri2ate& This a##ess spe#i$ier des#ribes the minimum a##ess le%el $or the members that are inherited $rom the base #lass&

// deri2ed classes #include <iostream> using namespace std; class CKolygon { protectedA int (idt)0 )eig)t; pu&licA

,! -!

";

2oid set/2alues (int a0 int &) { (idt)*a; )eig)t*&;"

class C5ectangleA pu&lic CKolygon { pu&licA int area () { return ((idt) % )eig)t); " "; class C:riangleA pu&lic CKolygon { pu&licA int area () { return ((idt) % )eig)t / ,); " "; int main () { C5ectangle rect; C:riangle trgl; rectFset/2alues (B0+); trglFset/2alues (B0+); cout << rectFarea() << endl; cout << trglFarea() << endl; return !; "
The ob?e#ts o$ the #lasses C5ectangle and C:riangle ea#h #ontain members inherited $rom CKolygon& These are: (idt), )eig)t and set/2alues()& The protected a##ess spe#i$ier is similar to pri2ate& 2ts only di$$eren#e o##urs in $a#t "ith inheritan#e& =hen a #lass inherits $rom another one, the members o$ the deri%ed #lass #an a##ess the prote#ted members inherited $rom the base #lass, but not its pri%ate members& >in#e "e "anted (idt) and )eig)t to be a##essible $rom members o$ the deri%ed #lasses C5ectangle and C:riangle and not only by members o$ CKolygon, "e ha%e used protected a##ess instead o$ pri2ate& =e #an summariDe the di$$erent a##ess types a##ordin to "ho #an a##ess them in the $ollo"in "ay: Access public protected pri"ate members o$ the same #lass yes yes yes members o$ deri%ed #lasses yes yes no not members yes no no =here <not members< represent any a##ess $rom outside the #lass, su#h as $rom main(), $rom another #lass or $rom a $un#tion& 2n our e:ample, the members inherited by C5ectangle and C:riangle ha%e the same a##ess permissions as they had in their base #lass CKolygon:

CKolygonAA(idt) C5ectangleAA(idt) CKolygonAAset/2alues() C5ectangleAAset/2alues()

// protected access // protected access // pu&lic access // pu&lic access

This is be#ause "e ha%e used the pu&lic -ey"ord to de$ine the inheritan#e relationship on ea#h o$ the deri%ed #lasses:

class C5ectangleA pu&lic CKolygon { FFF "


This pu&lic -ey"ord a$ter the #olon .A0 denotes the ma:imum a##ess le%el $or all the members inherited $rom the #lass that $ollo"s it .in this #ase CKolygon0& >in#e pu&lic is the most a##essible le%el, by spe#i$yin this -ey"ord the deri%ed #lass "ill inherit all the members "ith the same le%els they had in the base #lass& 2$ "e spe#i$y a more restri#ti%e a##ess le%el li-e protected, all publi# members o$ the base #lass are inherited as prote#ted in the deri%ed #lass& =hereas i$ "e spe#i$y the most restri#tin o$ all a##ess le%els: pri2ate, all the base #lass members are inherited as pri%ate& *or e:ample, i$ daug)ter "as a #lass deri%ed $rom mot)er that "e de$ined as:

class daug)terA protected mot)er;


This "ould set protected as the ma:imum a##ess le%el $or the members o$ daug)ter that it inherited $rom mot)er& That is, all members that "ere publi# in mot)er "ould be#ome prote#ted in daug)ter& )$ #ourse, this "ould not restri#t daug)ter to de#lare its o"n publi# members& That ma:imum a##ess le%el is only set $or the members inherited $rom mot)er& 2$ "e do not e:pli#itly spe#i$y any a##ess le%el $or the inheritan#e, the #ompiler assumes pri%ate $or #lasses de#lared "ith class -ey"ord and publi# $or those de#lared "ith struct&

What is inherited from the base class?


2n prin#iple, a deri%ed #lass inherits e%ery member o$ a base #lass e:#ept:

its #onstru#tor and its destru#tor its operatorN.0 members its $riends

'lthou h the #onstru#tors and destru#tors o$ the base #lass are not inherited themsel%es, its de$ault #onstru#tor .i&e&, its #onstru#tor "ith no parameters0 and its destru#tor are al"ays #alled "hen a ne" ob?e#t o$ a deri%ed #lass is #reated or destroyed& 2$ the base #lass has no de$ault #onstru#tor or you "ant that an o%erloaded #onstru#tor is #alled "hen a ne" deri%ed ob?e#t is #reated, you #an spe#i$y it in ea#h #onstru#tor de$inition o$ the deri%ed #lass:

deri2ed/constructor/name (parameters) A &ase/constructor/name (parameters) {FFF"


*or e:ample:

// constructors and deri2ed classes #include <iostream> using namespace std; class mot)er { pu&licA mot)er () { cout << "mot)erA no parametersJn"; " mot)er (int a)

mot)erA no parameters daug)terA int parameter mot)erA int parameter sonA int parameter

{ cout << "mot)erA int parameterJn"; " "; class daug)ter A pu&lic mot)er { pu&licA daug)ter (int a) { cout << "daug)terA int parameterJnJn"; " "; class son A pu&lic mot)er { pu&licA son (int a) A mot)er (a) { cout << "sonA int parameterJnJn"; " "; int main () { daug)ter cynt)ia (!); son daniel(!); return !; "
,oti#e the di$$eren#e bet"een "hi#h mot)erCs #onstru#tor is #alled "hen a ne" daug)ter ob?e#t is #reated and "hi#h "hen it is a son ob?e#t& The di$$eren#e is be#ause the #onstru#tor de#laration o$ daug)ter and son:

daug)ter (int a) son (int a) A mot)er (a)

// not)ing specifiedA call default // constructor specifiedA call t)is

#ultiple inheritance
2n C// it is per$e#tly possible that a #lass inherits members $rom more than one #lass& This is done by simply separatin the di$$erent base #lasses "ith #ommas in the deri%ed #lass de#laration& *or e:ample, i$ "e had a spe#i$i# #lass to print on s#reen . C<utput0 and "e "anted our #lasses C5ectangle and C:riangle to also inherit its members in addition to those o$ CKolygon "e #ould "rite:

class C5ectangleA pu&lic CKolygon0 pu&lic C<utput; class C:riangleA pu&lic CKolygon0 pu&lic C<utput;
here is the #omplete e:ample:

// multiple in)eritance #include <iostream> using namespace std; class CKolygon { protectedA int (idt)0 )eig)t; pu&licA 2oid set/2alues (int a0 int &) { (idt)*a; )eig)t*&;" "; class C<utput { pu&licA 2oid output (int i);

,! -!

"; 2oid C<utputAAoutput (int i) { cout << i << endl; " class C5ectangleA pu&lic CKolygon0 pu&lic C<utput { pu&licA int area () { return ((idt) % )eig)t); " "; class C:riangleA pu&lic CKolygon0 pu&lic C<utput { pu&licA int area () { return ((idt) % )eig)t / ,); " "; int main () { C5ectangle rect; C:riangle trgl; rectFset/2alues (B0+); trglFset/2alues (B0+); rectFoutput (rectFarea()); trglFoutput (trglFarea()); return !; "

Polymorphism

Published by Juan Soulie


Last update on )#t 22, 2004 at 8:24am UTC

6e$ore ettin into this se#tion, it is re#ommended that you ha%e a proper understandin o$ pointers and #lass inheritan#e& 2$ any o$ the $ollo"in statements seem stran e to you, you should re%ie" the indi#ated se#tions: Statement) ><plained in) int a::b.#0 JKL Classes a1Ob Data >tru#tures #lass a: publi# bL *riendship and inheritan#e

Pointers to base class


)ne o$ the -ey $eatures o$ deri%ed #lasses is that a pointer to a deri%ed #lass is type1#ompatible "ith a pointer to its base #lass& Polymorphism is the art o$ ta-in ad%anta e o$ this simple but po"er$ul and %ersatile $eature, that brin s )b?e#t )riented 5ethodolo ies to its $ull potential& =e are oin to start by re"ritin our pro ram about the re#tan le and the trian le o$ the pre%ious se#tion ta-in into #onsideration this pointer #ompatibility property:

// pointers to &ase class #include <iostream> using namespace std; class CKolygon { protectedA int (idt)0 )eig)t; pu&licA 2oid set/2alues (int a0 int &) { (idt)*a; )eig)t*&; " "; class C5ectangleA pu&lic CKolygon { pu&licA int area () { return ((idt) % )eig)t); " "; class C:riangleA pu&lic CKolygon { pu&licA int area () { return ((idt) % )eig)t / ,); " "; int main () { C5ectangle rect; C:riangle trgl; CKolygon % ppoly- * Mrect; CKolygon % ppoly, * Mtrgl; ppoly-.>set/2alues (B0+); ppoly,.>set/2alues (B0+); cout << rectFarea() << endl; cout << trglFarea() << endl; return !; "

,! -!

2n $un#tion main, "e #reate t"o pointers that point to ob?e#ts o$ #lass CKolygon .ppoly- and ppoly,0& Then "e assi n re$eren#es to rect and trgl to these pointers, and be#ause both are ob?e#ts o$ #lasses deri%ed $rom CKolygon, both are %alid assi nations& The only limitation in usin %ppoly- and %ppoly, instead o$ rect and trgl is that both %ppolyand %ppoly, are o$ type CKolygon% and there$ore "e #an only use these pointers to re$er to the members that C5ectangle and C:riangle inherit $rom CKolygon& *or that reason "hen "e #all the area() members at the end o$ the pro ram "e ha%e had to use dire#tly the ob?e#ts rect and trgl instead o$ the pointers %ppoly- and %ppoly,& 2n order to use area() "ith the pointers to #lass CKolygon, this member should also ha%e been de#lared in the #lass CKolygon, and not only in its deri%ed #lasses, but the problem is that C5ectangle and C:riangle implement di$$erent %ersions o$ area, there$ore "e #annot implement it in the base #lass& This is "hen %irtual members be#ome handy:

$irtual members
' member o$ a #lass that #an be rede$ined in its deri%ed #lasses is -no"n as a %irtual member& 2n order to de#lare a member o$ a #lass as %irtual, "e must pre#ede its de#laration "ith the -ey"ord 2irtual:

// 2irtual mem&ers #include <iostream> using namespace std; class CKolygon { protectedA int (idt)0 )eig)t; pu&licA 2oid set/2alues (int a0 int &) { (idt)*a; )eig)t*&; " 2irtual int area () { return (!); " "; class C5ectangleA pu&lic CKolygon { pu&licA int area () { return ((idt) % )eig)t); " "; class C:riangleA pu&lic CKolygon { pu&licA int area () { return ((idt) % )eig)t / ,); " "; int main () { C5ectangle rect; C:riangle trgl; CKolygon poly; CKolygon % ppoly- * Mrect; CKolygon % ppoly, * Mtrgl; CKolygon % ppolyD * Mpoly; ppoly-.>set/2alues (B0+); ppoly,.>set/2alues (B0+); ppolyD.>set/2alues (B0+); cout << ppoly-.>area() << endl; cout << ppoly,.>area() << endl; cout << ppolyD.>area() << endl;

,! -! !

return !; "
,o" the three #lasses .CKolygon, C5ectangle and C:riangle0 ha%e all the same members: (idt), )eig)t, set/2alues() and area()& The member $un#tion area() has been de#lared as %irtual in the base #lass be#ause it is later rede$ined in ea#h deri%ed #lass& Aou #an %eri$y i$ you "ant that i$ you remo%e this 2irtual -ey"ord $rom the de#laration o$ area() "ithin CKolygon, and then you run the pro ram the result "ill be ! $or the three poly ons instead o$ ,!, -! and !& That is be#ause instead o$ #allin the #orrespondin area() $un#tion $or ea#h ob?e#t .C5ectangleAAarea(), C:riangleAAarea() and CKolygonAAarea(), respe#ti%ely0, CKolygonAAarea() "ill be #alled in all #ases sin#e the #alls are %ia a pointer "hose type is CKolygon%& There$ore, "hat the 2irtual -ey"ord does is to allo" a member o$ a deri%ed #lass "ith the same name as one in the base #lass to be appropriately #alled $rom a pointer, and more pre#isely "hen the type o$ the pointer is a pointer to the base #lass but is pointin to an ob?e#t o$ the deri%ed #lass, as in the abo%e e:ample& ' #lass that de#lares or inherits a %irtual $un#tion is #alled a polymorphic class& ,ote that despite o$ its %irtuality, "e ha%e also been able to de#lare an ob?e#t o$ type CKolygon and to #all its o"n area() $un#tion, "hi#h al"ays returns 0&

Abstract base classes


'bstra#t base #lasses are somethin %ery similar to our CKolygon #lass o$ our pre%ious e:ample& The only di$$eren#e is that in our pre%ious e:ample "e ha%e de$ined a %alid area() $un#tion "ith a minimal $un#tionality $or ob?e#ts that "ere o$ #lass CKolygon .li-e the ob?e#t poly0, "hereas in an abstra#t base #lasses "e #ould lea%e that area() member $un#tion "ithout implementation at all& This is done by appendin *! .e;ual to Dero0 to the $un#tion de#laration& 'n abstra#t base CPoly on #lass #ould loo- li-e this:

// a&stract class CKolygon class CKolygon { protectedA int (idt)0 )eig)t; pu&licA 2oid set/2alues (int a0 int &) { (idt)*a; )eig)t*&; " 2irtual int area () *!; ";
,oti#e ho" "e appended *! to 2irtual int area () instead o$ spe#i$yin an implementation $or the $un#tion& This type o$ $un#tion is #alled a pure virtual function, and all #lasses that #ontain at least one pure %irtual $un#tion are abstract base classes& The main di$$eren#e bet"een an abstra#t base #lass and a re ular polymorphi# #lass is that be#ause in abstra#t base #lasses at least one o$ its members la#-s implementation "e #annot #reate instan#es .ob?e#ts0 o$ it& 6ut a #lass that #annot instantiate ob?e#ts is not totally useless& =e #an #reate pointers to it and ta-e ad%anta e o$ all its polymorphi# abilities& There$ore a de#laration li-e:

CKolygon poly;

"ould not be %alid $or the abstra#t base #lass "e ha%e ?ust de#lared, be#ause tries to instantiate an ob?e#t& ,e%ertheless, the $ollo"in pointers:

CKolygon % ppoly-; CKolygon % ppoly,;


"ould be per$e#tly %alid& This is so $or as lon as CKolygon in#ludes a pure %irtual $un#tion and there$ore itCs an abstra#t base #lass& Eo"e%er, pointers to this abstra#t base #lass #an be used to point to ob?e#ts o$ deri%ed #lasses& Eere you ha%e the #omplete e:ample:

// a&stract &ase class #include <iostream> using namespace std; class CKolygon { protectedA int (idt)0 )eig)t; pu&licA 2oid set/2alues (int a0 int &) { (idt)*a; )eig)t*&; " 2irtual int area (2oid) *!; "; class C5ectangleA pu&lic CKolygon { pu&licA int area (2oid) { return ((idt) % )eig)t); " "; class C:riangleA pu&lic CKolygon { pu&licA int area (2oid) { return ((idt) % )eig)t / ,); " "; int main () { C5ectangle rect; C:riangle trgl; CKolygon % ppoly- * Mrect; CKolygon % ppoly, * Mtrgl; ppoly-.>set/2alues (B0+); ppoly,.>set/2alues (B0+); cout << ppoly-.>area() << endl; cout << ppoly,.>area() << endl; return !; "

,! -!

2$ you re%ie" the pro ram you "ill noti#e that "e re$er to ob?e#ts o$ di$$erent but related #lasses usin a uni;ue type o$ pointer .CKolygon%0& This #an be tremendously use$ul& *or e:ample, no" "e #an #reate a $un#tion member o$ the abstra#t base #lass CKolygon that is able to print on s#reen the result o$ the area() $un#tion e%en thou h CKolygon itsel$ has no implementation $or this $un#tion:

// pure 2irtual mem&ers can &e called // from t)e a&stract &ase class #include <iostream>

,! -!

using namespace std; class CKolygon { protectedA int (idt)0 )eig)t; pu&licA 2oid set/2alues (int a0 int &) { (idt)*a; )eig)t*&; " 2irtual int area (2oid) *!; 2oid printarea (2oid) { cout << t)is.>area() << endl; " "; class C5ectangleA pu&lic CKolygon { pu&licA int area (2oid) { return ((idt) % )eig)t); " "; class C:riangleA pu&lic CKolygon { pu&licA int area (2oid) { return ((idt) % )eig)t / ,); " "; int main () { C5ectangle rect; C:riangle trgl; CKolygon % ppoly- * Mrect; CKolygon % ppoly, * Mtrgl; ppoly-.>set/2alues (B0+); ppoly,.>set/2alues (B0+); ppoly-.>printarea(); ppoly,.>printarea(); return !; "
Firtual members and abstra#t #lasses rant C// the polymorphi# #hara#teristi#s that ma-e ob?e#t1 oriented pro rammin su#h a use$ul instrument in bi pro?e#ts& )$ #ourse, "e ha%e seen %ery simple uses o$ these $eatures, but these $eatures #an be applied to arrays o$ ob?e#ts or dynami#ally allo#ated ob?e#ts& LetCs end "ith the same e:ample a ain, but this time "ith ob?e#ts that are dynami#ally allo#ated:

// dynamic allocation and polymorp)ism ,! #include <iostream> -! using namespace std; class CKolygon { protectedA int (idt)0 )eig)t; pu&licA 2oid set/2alues (int a0 int &) { (idt)*a; )eig)t*&; " 2irtual int area (2oid) *!; 2oid printarea (2oid) { cout << t)is.>area() << endl; " "; class C5ectangleA pu&lic CKolygon {

pu&licA int area (2oid) { return ((idt) % )eig)t); " "; class C:riangleA pu&lic CKolygon { pu&licA int area (2oid) { return ((idt) % )eig)t / ,); " "; int main () { CKolygon % ppoly- * ne( C5ectangle; CKolygon % ppoly, * ne( C:riangle; ppoly-.>set/2alues (B0+); ppoly,.>set/2alues (B0+); ppoly-.>printarea(); ppoly,.>printarea(); delete ppoly-; delete ppoly,; return !; "
,oti#e that the ppoly pointers:

CKolygon % ppoly- * ne( C5ectangle; CKolygon % ppoly, * ne( C:riangle;


are de#lared bein o$ type pointer to CKolygon but the ob?e#ts dynami#ally allo#ated ha%e been de#lared ha%in the deri%ed #lass type dire#tly&

'emplates
*unction templates

Published by Juan Soulie


Last update on ,o% 1!, 2004 at 9:3!am UTC

*un#tion templates are spe#ial $un#tions that #an operate "ith generic types& This allo"s us to #reate a $un#tion template "hose $un#tionality #an be adapted to more than one type or #lass "ithout repeatin the entire #ode $or ea#h type& 2n C// this #an be a#hie%ed usin template parameters& ' template parameter is a spe#ial -ind o$ parameter that #an be used to pass a type as ar ument: ?ust li-e re ular $un#tion parameters #an be used to pass %alues to a $un#tion, template parameters allo" to pass also types to a $un#tion& These $un#tion templates #an use these parameters as i$ they "ere any other re ular type& The $ormat $or de#larin $un#tion templates "ith type parameters is:

template <class identifier> function/declaration; template <typename identifier> function/declaration;


The only di$$eren#e bet"een both prototypes is the use o$ either the -ey"ord class or the -ey"ord typename& 2ts use is indistin#t, sin#e both e:pressions ha%e e:a#tly the same meanin and beha%e e:a#tly the same "ay& *or e:ample, to #reate a template $un#tion that returns the reater one o$ t"o ob?e#ts "e #ould use:

template <class my:ype> my:ype Wet=a1 (my:ype a0 my:ype &) { return (a>&IaA&); "
Eere "e ha%e #reated a template $un#tion "ith my:ype as its template parameter& This template parameter represents a type that has not yet been spe#i$ied, but that #an be used in the template $un#tion as i$ it "ere a re ular type& 's you #an see, the $un#tion template Wet=a1 returns the reater o$ t"o parameters o$ this still1unde$ined type& To use this $un#tion template "e use the $ollo"in $ormat $or the $un#tion #all:

function/name <type> (parameters);


*or e:ample, to #all Wet=a1 to #ompare t"o inte er %alues o$ type int "e #an "rite:

int 10y; Wet=a1 <int> (10y);


=hen the #ompiler en#ounters this #all to a template $un#tion, it uses the template to automati#ally enerate a $un#tion repla#in ea#h appearan#e o$ my:ype by the type passed as the a#tual template parameter .int in this #ase0 and then #alls it& This pro#ess is automati#ally per$ormed by the #ompiler and is in%isible to the pro rammer& Eere is the entire e:ample:

// function template #include <iostream> using namespace std;

C -!

template <class :> : Wet=a1 (: a0 : &) { : result; result * (a>&)I a A &; return (result); " int main () { int i*+0 U*C0 '; long l*-!0 m*+0 n; '*Wet=a1<int>(i0U); n*Wet=a1<long>(l0m); cout << ' << endl; cout << n << endl; return !; "
2n this #ase, "e ha%e used : as the template parameter name instead o$ my:ype be#ause it is shorter and in $a#t is a %ery #ommon template parameter name& 6ut you #an use any identi$ier you li-e& 2n the e:ample abo%e "e used the $un#tion template Wet=a1() t"i#e& The $irst time "ith ar uments o$ type int and the se#ond one "ith ar uments o$ type long& The #ompiler has instantiated and then #alled ea#h time the appropriate %ersion o$ the $un#tion& 's you #an see, the type : is used "ithin the Wet=a1() template $un#tion e%en to de#lare ne" ob?e#ts o$ that type:

: result;
There$ore, result "ill be an ob?e#t o$ the same type as the parameters a and & "hen the $un#tion template is instantiated "ith a spe#i$i# type& 2n this spe#i$i# #ase "here the eneri# type : is used as a parameter $or Wet=a1 the #ompiler #an $ind out automati#ally "hi#h data type has to instantiate "ithout ha%in to e:pli#itly spe#i$y it "ithin an le bra#-ets .li-e "e ha%e done be$ore spe#i$yin <int> and <long>0& >o "e #ould ha%e "ritten instead:

int i0U; Wet=a1 (i0U);


>in#e both i and U are o$ type int, and the #ompiler #an automati#ally $ind out that the template parameter #an only be int& This impli#it method produ#es e:a#tly the same result:

// function template ## #include <iostream> using namespace std; template <class :> : Wet=a1 (: a0 : &) { return (a>&IaA&); " int main () { int i*+0 U*C0 '; long l*-!0 m*+0 n; '*Wet=a1(i0U); n*Wet=a1(l0m);

C -!

cout << ' << endl; cout << n << endl; return !; "
,oti#e ho" in this #ase, "e #alled our $un#tion template Wet=a1() "ithout e:pli#itly spe#i$yin the type bet"een an le1bra#-ets <>& The #ompiler automati#ally determines "hat type is needed on ea#h #all& 6e#ause our template $un#tion in#ludes only one template parameter . class :0 and the $un#tion template itsel$ a##epts t"o parameters, both o$ this : type, "e #annot #all our $un#tion template "ith t"o ob?e#ts o$ di$$erent types as ar uments:

int i; long l; ' * Wet=a1 (i0l);


This "ould not be #orre#t, sin#e our Wet=a1 $un#tion template e:pe#ts t"o ar uments o$ the same type, and in this #all to it "e use ob?e#ts o$ t"o di$$erent types& =e #an also de$ine $un#tion templates that a##ept more than one type parameter, simply by spe#i$yin more template parameters bet"een the an le bra#-ets& *or e:ample:

template <class :0 class 8> : Wet=in (: a0 8 &) { return (a<&IaA&); "


2n this #ase, our $un#tion template Wet=in() a##epts t"o parameters o$ di$$erent types and returns an ob?e#t o$ the same type as the $irst parameter . :0 that is passed& *or e:ample, a$ter that de#laration "e #ould #all Wet=in() "ith:

int i0U; long l; i * Wet=in<int0long> (U0l);


or simply:

i * Wet=in (U0l);
e%en thou h U and l ha%e di$$erent types, sin#e the #ompiler #an determine the appropriate instantiation any"ay&

Class templates
=e also ha%e the possibility to "rite #lass templates, so that a #lass #an ha%e members that use template parameters as types& *or e:ample:

template <class :> class mypair { : 2alues P,Q; pu&licA mypair (: first0 : second) { 2aluesP!Q*first; 2aluesP-Q*second; " ";

The #lass that "e ha%e ?ust de$ined ser%es to store t"o elements o$ any %alid type& *or e:ample, i$ "e "anted to de#lare an ob?e#t o$ this #lass to store t"o inte er %alues o$ type int "ith the %alues 11@ and 3! "e "ould "rite:

mypair<int> myo&Uect (--+0 DC);


this same #lass "ould also be used to #reate an ob?e#t to store any other type:

mypair<dou&le> myfloats (DF!0 ,F-T);


The only member $un#tion in the pre%ious #lass template has been de$ined inline "ithin the #lass de#laration itsel$& 2n #ase that "e de$ine a $un#tion member outside the de#laration o$ the #lass template, "e must al"ays pre#ede that de$inition "ith the template <FFF> pre$i::

// class templates #include <iostream> using namespace std; template <class :> class mypair { : a0 &; pu&licA mypair (: first0 : second) {a*first; &*second;" : getma1 (); "; template <class :> : mypair<:>AAgetma1 () { : ret2al; ret2al * a>&I a A &; return ret2al; " int main () { mypair <int> myo&Uect (-!!0 E+); cout << myo&UectFgetma1(); return !; "

-!!

,oti#e the synta: o$ the de$inition o$ member $un#tion etma::

template <class :> : mypair<:>AAgetma1 ()


Con$used by so many :CsQ There are three :Cs in this de#laration: The $irst one is the template parameter& The se#ond : re$ers to the type returned by the $un#tion& 'nd the third : .the one bet"een an le bra#-ets0 is also a re;uirement: 2t spe#i$ies that this $un#tionCs template parameter is also the #lass template parameter&

'emplate speciali,ation
2$ "e "ant to de$ine a di$$erent implementation $or a template "hen a spe#i$i# type is passed as template parameter, "e #an de#lare a spe#ialiDation o$ that template&

*or e:ample, letCs suppose that "e ha%e a %ery simple #lass #alled mycontainer that #an store one element o$ any type and that it has ?ust one member $un#tion #alled increase, "hi#h in#reases its %alue& 6ut "e $ind that "hen it stores an element o$ type c)ar it "ould be more #on%enient to ha%e a #ompletely di$$erent implementation "ith a $un#tion member uppercase, so "e de#ide to de#lare a #lass template spe#ialiDation $or that type:

// template speciali3ation #include <iostream> using namespace std; // class templateA template <class :> class mycontainer { : element; pu&licA mycontainer (: arg) {element*arg;" : increase () {return ++element;" "; // class template speciali3ationA template <> class mycontainer <c)ar> { c)ar element; pu&licA mycontainer (c)ar arg) {element*arg;" c)ar uppercase () { if ((element>*$a$)MM(element<*$3$)) element+*$>$.$a$; return element; " "; int main () { mycontainer<int> myint (E); mycontainer<c)ar> myc)ar ($U$); cout << myintFincrease() << endl; cout << myc)arFuppercase() << endl; return !; "

T S

This is the synta: used in the #lass template spe#ialiDation:

template <> class mycontainer <c)ar> { FFF ";


*irst o$ all, noti#e that "e pre#ede the #lass template name "ith an empty template<> parameter list& This is to e:pli#itly de#lare it as a template spe#ialiDation& 6ut more important than this pre$i:, is the <c)ar> spe#ialiDation parameter a$ter the #lass template name& This spe#ialiDation parameter itsel$ identi$ies the type $or "hi#h "e are oin to de#lare a template #lass spe#ialiDation .c)ar0& ,oti#e the di$$eren#es bet"een the eneri# #lass template and the spe#ialiDation:

template <class :> class mycontainer { FFF "; template <> class mycontainer <c)ar> { FFF ";

The $irst line is the eneri# template, and the se#ond one is the spe#ialiDation& =hen "e de#lare spe#ialiDations $or a template #lass, "e must also de$ine all its members, e%en those e:a#tly e;ual to the eneri# template #lass, be#ause there is no <inheritan#e< o$ members $rom the eneri# template to the spe#ialiDation&

+on type parameters for templates


6esides the template ar uments that are pre#eded by the class or typename -ey"ords , "hi#h represent types, templates #an also ha%e re ular typed parameters, similar to those $ound in $un#tions& 's an e:ample, ha%e a loo- at this #lass template that is used to #ontain se;uen#es o$ elements:

// se4uence template #include <iostream> using namespace std; template <class :0 int ;> class myse4uence { : mem&loc' P;Q; pu&licA 2oid setmem&er (int 10 : 2alue); : getmem&er (int 1); "; template <class :0 int ;> 2oid myse4uence<:0;>AAsetmem&er (int 10 : 2alue) { mem&loc'P1Q*2alue; " template <class :0 int ;> : myse4uence<:0;>AAgetmem&er (int 1) { return mem&loc'P1Q; " int main () { myse4uence <int0+> myints; myse4uence <dou&le0+> myfloats; myintsFsetmem&er (!0-!!); myfloatsFsetmem&er (D0DF-B-C); cout << myintsFgetmem&er(!) << $Jn$; cout << myfloatsFgetmem&er(D) << $Jn$; return !; "

-!! DF-B-C

2t is also possible to set de$ault %alues or types $or #lass template parameters& *or e:ample, i$ the pre%ious #lass template de$inition had been:

template <class :*c)ar0 int ;*-!> class myse4uence {FF";


=e #ould #reate ob?e#ts usin the de$ault template parameters by de#larin :

myse4uence<> myse4;
=hi#h "ould be e;ui%alent to:

myse4uence<c)ar0-!> myse4;

'emplates and multiple file projects


*rom the point o$ %ie" o$ the #ompiler, templates are not normal $un#tions or #lasses& They are #ompiled on demand, meanin that the #ode o$ a template $un#tion is not #ompiled until an instantiation "ith spe#i$i# template ar uments is re;uired& 't that moment, "hen an instantiation is re;uired, the #ompiler enerates a $un#tion spe#i$i#ally $or those ar uments $rom the template& =hen pro?e#ts ro" it is usual to split the #ode o$ a pro ram in di$$erent sour#e #ode $iles& 2n these #ases, the inter$a#e and implementation are enerally separated& Ta-in a library o$ $un#tions as e:ample, the inter$a#e enerally #onsists o$ de#larations o$ the prototypes o$ all the $un#tions that #an be #alled& These are enerally de#lared in a <header $ile< "ith a &h e:tension, and the implementation .the de$inition o$ these $un#tions0 is in an independent $ile "ith #// #ode& 6e#ause templates are #ompiled "hen re;uired, this $or#es a restri#tion $or multi1$ile pro?e#ts: the implementation .de$inition0 o$ a template #lass or $un#tion must be in the same $ile as its de#laration& That means that "e #annot separate the inter$a#e in a separate header $ile, and that "e must in#lude both inter$a#e and implementation in any $ile that uses the templates& >in#e no #ode is enerated until a template is instantiated "hen re;uired, #ompilers are prepared to allo" the in#lusion more than on#e o$ the same template $ile "ith both de#larations and de$initions in a pro?e#t "ithout eneratin lin-a e errors&

+amespaces
The $ormat o$ namespa#es is:

Published by Juan Soulie


Last update on *eb 2, 2004 at 2:01pm UTC

,amespa#es allo" to roup entities li-e #lasses, ob?e#ts and $un#tions under a name& This "ay the lobal s#ope #an be di%ided in <sub1s#opes<, ea#h one "ith its o"n name&

namespace identifier { entities "


=here identifier is any %alid identi$ier and entities is the set o$ #lasses, ob?e#ts and $un#tions that are in#luded "ithin the namespa#e& *or e:ample:

namespace my;amespace { int a0 &; "


2n this #ase, the %ariables a and & are normal %ariables de#lared "ithin a namespa#e #alled my;amespace& 2n order to a##ess these %ariables $rom outside the my;amespace namespa#e "e ha%e to use the s#ope operator AA& *or e:ample, to a##ess the pre%ious %ariables $rom outside my;amespace "e #an "rite:

my;amespaceAAa my;amespaceAA&
The $un#tionality o$ namespa#es is espe#ially use$ul in the #ase that there is a possibility that a lobal ob?e#t or $un#tion uses the same identi$ier as another one, #ausin rede$inition errors& *or e:ample:

// namespaces #include <iostream> using namespace std; namespace first { int 2ar * +; " namespace second { dou&le 2ar * DF-B-C; " int main () { cout << firstAA2ar << endl; cout << secondAA2ar << endl; return !; "

+ DF-B-C

2n this #ase, there are t"o lobal %ariables "ith the same name: 2ar& )ne is de$ined "ithin the namespa#e first and the other one in second& ,o rede$inition errors happen than-s to namespa#es&

using
The -ey"ord using is used to introdu#e a name $rom a namespa#e into the #urrent de#larati%e re ion& *or e:ample:

// using #include <iostream> using namespace std; namespace first { int 1 * +; int y * -!; " namespace second { dou&le 1 * DF-B-C; dou&le y * ,FE-TD; " int main () { using firstAA1; using secondAAy; cout << 1 << endl; cout << y << endl; cout << firstAAy << endl; cout << secondAA1 << endl; return !; "

+ ,FE-TD -! DF-B-C

,oti#e ho" in this #ode, 1 ."ithout any name ;uali$ier0 re$ers to firstAA1 "hereas y re$ers to secondAAy, e:a#tly as our using de#larations ha%e spe#i$ied& =e still ha%e a##ess to firstAAy and secondAA1 usin their $ully ;uali$ied names& The -ey"ord usin #an also be used as a dire#ti%e to introdu#e an entire namespa#e:

// using #include <iostream> using namespace std; namespace first { int 1 * +; int y * -!; " namespace second { dou&le 1 * DF-B-C; dou&le y * ,FE-TD; " int main () { using namespace first; cout << 1 << endl; cout << y << endl; cout << secondAA1 << endl; cout << secondAAy << endl; return !; "

+ -! DF-B-C ,FE-TD

2n this #ase, sin#e "e ha%e de#lared that "e "ere using namespace first, all dire#t uses o$ 1 and y "ithout name ;uali$iers "ere re$errin to their de#larations in namespace first&

using and using namespace ha%e %alidity only in the same blo#- in "hi#h they are stated or in the
entire #ode i$ they are used dire#tly in the lobal s#ope& *or e:ample, i$ "e had the intention to $irst use the ob?e#ts o$ one namespa#e and then those o$ another one, "e #ould do somethin li-e:

// using namespace e1ample #include <iostream> using namespace std; namespace first { int 1 * +; " namespace second { dou&le 1 * DF-B-C; " int main () { { using namespace first; cout << 1 << endl; " { using namespace second; cout << 1 << endl; " return !; "

+ DF-B-C

+amespace alias
=e #an de#lare alternate names $or e:istin namespa#es a##ordin to the $ollo"in $ormat:

namespace ne(/name * current/name;

+amespace std
'll the $iles in the C// standard library de#lare all o$ its entities "ithin the std namespa#e& That is "hy "e ha%e enerally in#luded the using namespace std; statement in all pro rams that used any entity de$ined in iostream&

><ceptions

Published by Juan Soulie


Last update on ,o% 20, 2004 at 9:14am UTC

9:#eptions pro%ide a "ay to rea#t to e:#eptional #ir#umstan#es .li-e runtime errors0 in our pro ram by trans$errin #ontrol to spe#ial $un#tions #alled handlers& To #at#h e:#eptions "e must pla#e a portion o$ #ode under e:#eption inspe#tion& This is done by en#losin that portion o$ #ode in a try block& =hen an e:#eptional #ir#umstan#e arises "ithin that blo#-, an e:#eption is thro"n that trans$ers the #ontrol to the e:#eption handler& 2$ no e:#eption is thro"n, the #ode #ontinues normally and all handlers are i nored& ' e:#eption is thro"n by usin the thro" -ey"ord $rom inside the try blo#-& 9:#eption handlers are de#lared "ith the -ey"ord catc), "hi#h must be pla#ed immediately a$ter the try blo#-:

// e1ceptions #include <iostream> using namespace std; int main () { try { t)ro( ,!; " catc) (int e) { cout << ">n e1ception occurredF 61ception ;rF " << e << endl; " return !; "

>n e1ception occurredF 61ception ;rF ,!

The #ode under e:#eption handlin is en#losed in a try blo#-& 2n this e:ample this #ode simply thro"s an e:#eption:

t)ro( ,!;
' thro" e:pression a##epts one parameter .in this #ase the inte er %alue ,!0, "hi#h is passed as an ar ument to the e:#eption handler& The e:#eption handler is de#lared "ith the catc) -ey"ord& 's you #an see, it $ollo"s immediately the #losin bra#e o$ the try blo#-& The #at#h $ormat is similar to a re ular $un#tion that al"ays has at least one parameter& The type o$ this parameter is %ery important, sin#e the type o$ the ar ument passed by the thro" e:pression is #he#-ed a ainst it, and only in the #ase they mat#h, the e:#eption is #au ht& =e #an #hain multiple handlers .#at#h e:pressions0, ea#h one "ith a di$$erent parameter type& )nly the handler that mat#hes its type "ith the ar ument spe#i$ied in the thro" statement is e:e#uted& 2$ "e use an ellipsis .FFF0 as the parameter o$ catc), that handler "ill #at#h any e:#eption no matter "hat the type o$ the t)ro( e:#eption is& This #an be used as a de$ault handler that #at#hes all e:#eptions not #au ht by other handlers i$ it is spe#i$ied at last:

try { // code )ere " catc) (int param) { cout << "int e1ception"; "

catc) (c)ar param) { cout << "c)ar e1ception"; " catc) (FFF) { cout << "default e1ception"; "
2n this #ase the last handler "ould #at#h any e:#eption thro"n "ith any parameter that is neither an int nor a c)ar& '$ter an e:#eption has been handled the pro ram e:e#ution resumes a$ter the try.catc) blo#-, not a$ter the t)ro( statementB& 2t is also possible to nest try.catc) blo#-s "ithin more e:ternal try blo#-s& 2n these #ases, "e ha%e the possibility that an internal catc) blo#- $or"ards the e:#eption to its e:ternal le%el& This is done "ith the e:pression t)ro(; "ith no ar uments& *or e:ample:

try { try { // code )ere " catc) (int n) { t)ro(; " " catc) (FFF) { cout << "61ception occurred"; "

><ception specifications
=hen de#larin a $un#tion "e #an limit the e:#eption type it mi ht dire#tly or indire#tly thro" by appendin a t)ro( su$$i: to the $un#tion de#laration:

float myfunction (c)ar param) t)ro( (int);


This de#lares a $un#tion #alled myfunction "hi#h ta-es one a ument o$ type c)ar and returns an element o$ type float& The only e:#eption that this $un#tion mi ht thro" is an e:#eption o$ type int& 2$ it thro"s an e:#eption "ith a di$$erent type, either dire#tly or indire#tly, it #annot be #au ht by a re ular int1type handler& 2$ this t)ro( spe#i$ier is le$t empty "ith no type, this means the $un#tion is not allo"ed to thro" e:#eptions& *un#tions "ith no t)ro( spe#i$ier .re ular $un#tions0 are allo"ed to thro" e:#eptions "ith any type:

int myfunction (int param) t)ro((); // no e1ceptions allo(ed int myfunction (int param); // all e1ceptions allo(ed

Standard e<ceptions
The C// >tandard library pro%ides a base #lass spe#i$i#ally desi ned to de#lare ob?e#ts to be thro"n as e:#eptions& 2t is #alled e1ception and is de$ined in the <e1ception> header $ile under the namespace std& This #lass has the usual de$ault and #opy #onstru#tors, operators and destru#tors, plus an additional %irtual member $un#tion #alled ()at that returns a null1terminated #hara#ter se;uen#e .c)ar %0 and that #an be o%er"ritten in deri%ed #lasses to #ontain some sort o$ des#ription o$ the e:#eption&

// standard e1ceptions #include <iostream> #include <e1ception> using namespace std;

=y e1ception )appenedF

class mye1ceptionA pu&lic e1ception { 2irtual const c)ar% ()at() const t)ro(() { return "=y e1ception )appened"; " " mye1; int main () { try { t)ro( mye1; " catc) (e1ceptionM e) { cout << eF()at() << endl; " return !; "
=e ha%e pla#ed a handler that #at#hes e:#eption ob?e#ts by re$eren#e .noti#e the ampersand M a$ter the type0, there$ore this #at#hes also #lasses deri%ed $rom e1ception, li-e our mye1 ob?e#t o$ #lass mye1ception& 'll e:#eptions thro"n by #omponents o$ the C// >tandard library thro" e:#eptions deri%ed $rom this stdAAe1ception #lass& These are: e<ception badUallo# thro"n badU#ast thro"n badUe:#eption thro"n badUtypeid thro"n iosUbase::$ailure thro"n description by ne" on allo#ation $ailure by dynami#U#ast "hen $ails "ith a re$eren#ed type "hen an e:#eption type doesnCt mat#h any #at#h by typeid by $un#tions in the iostream library

*or e:ample, i$ "e use the operator ne( and the memory #annot be allo#ated, an e:#eption o$ type &ad/alloc is thro"n:

try { int % myarray* ne( intP-!!!Q; " catc) (&ad/allocM) { cout << "6rror allocating memoryF" << endl; "
2t is re#ommended to in#lude all dynami# memory allo#ations "ithin a try blo#- that #at#hes this type o$ e:#eption to per$orm a #lean a#tion instead o$ an abnormal pro ram termination, "hi#h is "hat happens "hen this type o$ e:#eption is thro"n and not #au ht& 2$ you "ant to $or#e a &ad/alloc e:#eption to see it in a#tion, you #an try to allo#ate a hu e arrayL )n my system, tryin to allo#ate 1 billion ints thre" a &ad/alloc e:#eption& 6e#ause &ad/alloc is deri%ed $rom the standard base #lass e1ception, "e #an handle that same e:#eption by #at#hin re$eren#es to the e1ception #lass:

// &ad/alloc standard e1ception #include <iostream> #include <e1ception> using namespace std; int main () { try { int% myarray* ne( intP-!!!Q; " catc) (e1ceptionM e) { cout << "7tandard e1ceptionA " << eF()at() << endl; " return !; "

'ype Casting
(mplicit con"ersion

Published by Juan Soulie


Last update on Jun 8, 2004 at 9:G!am UTC

Con%ertin an e:pression o$ a i%en type into another type is -no"n as type-casting& =e ha%e already seen some "ays to type #ast:

2mpli#it #on%ersions do not re;uire any operator& They are automati#ally per$ormed "hen a %alue is #opied to a #ompatible type& *or e:ample:

s)ort a*,!!!; int &; &*a;


Eere, the %alue o$ a has been promoted $rom s)ort to int and "e ha%e not had to spe#i$y any type1 #astin operator& This is -no"n as a standard #on%ersion& >tandard #on%ersions a$$e#t $undamental data types, and allo" #on%ersions su#h as the #on%ersions bet"een numeri#al types . s)ort to int, int to float, dou&le to int&&&0, to or $rom &ool, and some pointer #on%ersions& >ome o$ these #on%ersions may imply a loss o$ pre#ision, "hi#h the #ompiler #an si nal "ith a "arnin & This #an be a%oided "ith an e:pli#it #on%ersion& 2mpli#it #on%ersions also in#lude #onstru#tor or operator #on%ersions, "hi#h a$$e#t #lasses that in#lude spe#i$i# #onstru#tors or operator $un#tions to per$orm #on%ersions& *or e:ample:

class > {"; class ? { pu&licA ? (> a) {" "; > a; ? &*a;
Eere, a impli#it #on%ersion happened bet"een ob?e#ts o$ class > and class ?, be#ause ? has a #onstru#tor that ta-es an ob?e#t o$ #lass > as parameter& There$ore impli#it #on%ersions $rom > to ? are allo"ed&

><plicit con"ersion
C// is a stron 1typed lan ua e& 5any #on%ersions, spe#ially those that imply a di$$erent interpretation o$ the %alue, re;uire an e:pli#it #on%ersion& =e ha%e already seen t"o notations $or e:pli#it type #on%ersion: $un#tional and #1li-e #astin :

s)ort a*,!!!; int &; & * (int) a; & * int (a);

// c.li'e cast notation // functional notation

The $un#tionality o$ these e:pli#it #on%ersion operators is enou h $or most needs "ith $undamental data types& Eo"e%er, these operators #an be applied indis#riminately on #lasses and pointers to #lasses, "hi#h #an lead to #ode that "hile bein synta#ti#ally #orre#t #an #ause runtime errors& *or e:ample, the $ollo"in #ode is synta#ti#ally #orre#t:

// class type.casting #include <iostream> using namespace std; class CVummy { float i0U; ";

class C>ddition { int 10y; pu&licA C>ddition (int a0 int &) { 1*a; y*&; " int result() { return 1+y;" "; int main () { CVummy d; C>ddition % padd; padd * (C>ddition%) Md; cout << padd.>result(); return !; "
The pro ram de#lares a pointer to C>ddition, but then it assi ns to it a re$eren#e to an ob?e#t o$ another in#ompatible type usin e:pli#it type1#astin :

padd * (C>ddition%) Md;


Traditional e:pli#it type1#astin allo"s to #on%ert any pointer into any other pointer type, independently o$ the types they point to& The subse;uent #all to member result "ill produ#e either a run1time error or a une:pe#ted result& 2n order to #ontrol these types o$ #on%ersions bet"een #lasses, "e ha%e $our spe#i$i# #astin operators: dynamic/cast, reinterpret/cast, static/cast and const/cast& Their $ormat is to $ollo" the ne" type en#losed bet"een an le1bra#-ets . <>0 and immediately a$ter, the e:pression to be #on%erted bet"een parentheses&

dynamic/cast <ne(/type> (e1pression) reinterpret/cast <ne(/type> (e1pression) static/cast <ne(/type> (e1pression) const/cast <ne(/type> (e1pression)
The traditional type1#astin e;ui%alents to these e:pressions "ould be:

(ne(/type) e1pression ne(/type (e1pression)


but ea#h one "ith its o"n spe#ial #hara#teristi#s:

dynamicIcast
dynamic/cast #an be used only "ith pointers and re$eren#es to ob?e#ts& 2ts purpose is to ensure that
the result o$ the type #on%ersion is a %alid #omplete ob?e#t o$ the re;uested #lass& There$ore, dynamic/cast is al"ays su##ess$ul "hen "e #ast a #lass to one o$ its base #lasses:

class C?ase { "; class CVeri2edA pu&lic C?ase { "; C?ase &; C?ase% p&; CVeri2ed d; CVeri2ed% pd; p& * dynamic/cast<C?ase%>(Md); pd * dynamic/cast<CVeri2ed%>(M&); // o'A deri2ed.to.&ase // (rongA &ase.to.deri2ed

The se#ond #on%ersion in this pie#e o$ #ode "ould produ#e a #ompilation error sin#e base1to1deri%ed #on%ersions are not allo"ed "ith dynamic/cast unless the base #lass is polymorphi#& =hen a #lass is polymorphi#, dynamic/cast per$orms a spe#ial #he#-in durin runtime to ensure that the e:pression yields a %alid #omplete ob?e#t o$ the re;uested #lass:

// dynamic/cast #include <iostream> #include <e1ception> using namespace std; class C?ase { 2irtual 2oid dummy() {" "; class CVeri2edA pu&lic C?ase { int a; "; int main () { try { C?ase % p&a * ne( CVeri2ed; C?ase % p&& * ne( C?ase; CVeri2ed % pd; pd * dynamic/cast<CVeri2ed%>(p&a); if (pd**!) cout << ";ull pointer on first type.cast" << endl; pd * dynamic/cast<CVeri2ed%>(p&&); if (pd**!) cout << ";ull pointer on second type.cast" << endl;

;ull pointer on second type.cast

" catc) (e1ceptionM e) {cout << "61ceptionA " << eF()at();" return !; " Compatibility note) dynamic/cast re;uires the +un1Time Type 2n$ormation .+TT20 to -eep tra#- o$
dynami# types& >ome #ompilers support this $eature as an option "hi#h is disabled by de$ault& This must be enabled $or runtime type #he#-in usin dynamic/cast to "or- properly&

The #ode tries to per$orm t"o dynami# #asts $rom pointer ob?e#ts o$ type C?ase% .p&a and p&&0 to a pointer ob?e#t o$ type CVeri2ed%, but only the $irst one is su##ess$ul& ,oti#e their respe#ti%e initialiDations:

C?ase % p&a * ne( CVeri2ed; C?ase % p&& * ne( C?ase;


9%en thou h both are pointers o$ type C?ase%, p&a points to an ob?e#t o$ type CVeri2ed, "hile p&& points to an ob?e#t o$ type C?ase& Thus, "hen their respe#ti%e type1#astin s are per$ormed usin dynamic/cast, p&a is pointin to a $ull ob?e#t o$ #lass CVeri2ed, "hereas p&& is pointin to an ob?e#t o$ #lass C?ase, "hi#h is an in#omplete ob?e#t o$ #lass CVeri2ed& =hen dynamic/cast #annot #ast a pointer be#ause it is not a #omplete ob?e#t o$ the re;uired #lass 1as in the se#ond #on%ersion in the pre%ious e:ample1 it returns a null pointer to indi#ate the $ailure& 2$ dynamic/cast is used to #on%ert to a re$eren#e type and the #on%ersion is not possible, an e:#eption o$ type &ad/cast is thro"n instead&

dynamic/cast #an also #ast null pointers e%en bet"een pointers to unrelated #lasses, and #an also #ast pointers o$ any type to %oid pointers .2oid%0&

staticIcast
static/cast #an per$orm #on%ersions bet"een pointers to related #lasses, not only $rom the deri%ed
#lass to its base, but also $rom a base #lass to its deri%ed& This ensures that at least the #lasses are #ompatible i$ the proper ob?e#t is #on%erted, but no sa$ety #he#- is per$ormed durin runtime to #he#i$ the ob?e#t bein #on%erted is in $a#t a $ull ob?e#t o$ the destination type& There$ore, it is up to the pro rammer to ensure that the #on%ersion is sa$e& )n the other side, the o%erhead o$ the type1sa$ety #he#-s o$ dynamic/cast is a%oided&

class C?ase {"; class CVeri2edA pu&lic C?ase {"; C?ase % a * ne( C?ase; CVeri2ed % & * static/cast<CVeri2ed%>(a);
This "ould be %alid, althou h & "ould point to an in#omplete ob?e#t o$ the #lass and #ould lead to runtime errors i$ dere$eren#ed&

static/cast #an also be used to per$orm any other non1pointer #on%ersion that #ould also be
per$ormed impli#itly, li-e $or e:ample standard #on%ersion bet"een $undamental types:

dou&le d*DF-B-+G,C+; int i * static/cast<int>(d);


)r any #on%ersion bet"een #lasses "ith e:pli#it #onstru#tors or operator $un#tions as des#ribed in <impli#it #on%ersions< abo%e&

reinterpretIcast
reinterpret/cast #on%erts any pointer type to any other pointer type, e%en o$ unrelated #lasses&
The operation result is a simple binary #opy o$ the %alue $rom one pointer to the other& 'll pointer #on%ersions are allo"ed: neither the #ontent pointed nor the pointer type itsel$ is #he#-ed&

2t #an also #ast pointers to or $rom inte er types& The $ormat in "hi#h this inte er %alue represents a pointer is plat$orm1spe#i$i#& The only uarantee is that a pointer #ast to an inte er type lar e enou h to $ully #ontain it, is ranted to be able to be #ast ba#- to a %alid pointer& The #on%ersions that #an be per$ormed by reinterpret/cast but not by static/cast ha%e no spe#i$i# uses in C// are lo"1le%el operations, "hose interpretation results in #ode "hi#h is enerally system1spe#i$i#, and thus non1portable& *or e:ample:

class class > % a ? % &

> ? * *

{"; {"; ne( >; reinterpret/cast<?%>(a);

This is %alid C// #ode, althou h it does not ma-e mu#h sense, sin#e no" "e ha%e a pointer that points to an ob?e#t o$ an in#ompatible #lass, and thus dere$eren#in it is unsa$e&

constIcast
This type o$ #astin manipulates the #onstness o$ an ob?e#t, either to be set or to be remo%ed& *or e:ample, in order to pass a #onst ar ument to a $un#tion that e:pe#ts a non1#onstant parameter:

// const/cast #include <iostream> using namespace std; 2oid print (c)ar % str) { cout << str << endl;

sample te1t

" int main () { const c)ar % c * "sample te1t"; print ( const/cast<c)ar %> (c) ); return !; "

typeid
typeid allo"s to #he#- the type o$ an e:pression: typeid (e1pression)
This operator returns a re$eren#e to a #onstant ob?e#t o$ type type/info that is de$ined in the standard header $ile <typeinfo>& This returned %alue #an be #ompared "ith another one usin operators ** and * or #an ser%e to obtain a null1terminated #hara#ter se;uen#e representin the data type or #lass name by usin its name() member&

// typeid #include <iostream> #include <typeinfo> using namespace std; int main () { int % a0&; a*!; &*!; if (typeid(a) * typeid(&)) { cout << "a and & are of different typesAJn"; cout << "a isA " << typeid(a)Fname() << $Jn$; cout << "& isA " << typeid(&)Fname() << $Jn$; " return !; "

a and & are of different typesA a isA int % & isA int

=hen typeid is applied to #lasses typeid uses the +TT2 to -eep tra#- o$ the type o$ dynami# ob?e#ts& =hen typeid is applied to an e:pression "hose type is a polymorphi# #lass, the result is the type o$ the most deri%ed #omplete ob?e#t:

// typeid0 polymorp)ic class #include <iostream> #include <typeinfo> #include <e1ception> using namespace std; class C?ase { 2irtual 2oid f(){" "; class CVeri2ed A pu&lic C?ase {"; int main () { try { C?ase% a * ne( C?ase; C?ase% & * ne( CVeri2ed; cout << "a isA " << typeid(a)Fname() << $Jn$; cout << "& isA " <<

a isA class C?ase % & isA class C?ase % %a isA class C?ase %& isA class CVeri2ed

typeid(&)Fname() << $Jn$; cout << "%a isA " << typeid(%a)Fname() << $Jn$; cout << "%& isA " << typeid(%&)Fname() << $Jn$; " catc) (e1ceptionM e) { cout << "61ceptionA " << eF()at() << endl; " return !; "
,oti#e ho" the type that typeid #onsiders $or pointers is the pointer type itsel$ .both a and & are o$ type class C?ase %0& Eo"e%er, "hen typeid is applied to ob?e#ts .li-e %a and %&0 typeid yields their dynami# type .i&e& the type o$ their most deri%ed #omplete ob?e#t0& 2$ the type typeid e%aluates is a pointer pre#eded by the dere$eren#e operator . %0, and this pointer has a null %alue, typeid thro"s a &ad/typeid e:#eption&

Preprocessor directi"es

Published by Juan Soulie


Last update on 5ar 3, 2008 at !:03pm UTC

Prepro#essor dire#ti%es are lines in#luded in the #ode o$ our pro rams that are not pro ram statements but dire#ti%es $or the prepro#essor& These lines are al"ays pre#eded by a hash si n . #0& The prepro#essor is e:e#uted be$ore the a#tual #ompilation o$ #ode be ins, there$ore the prepro#essor di ests all these dire#ti%es be$ore any #ode is enerated by the statements& These prepro#essor dire#ti%es e:tend only a#ross a sin le line o$ #ode& 's soon as a ne"line #hara#ter is $ound, the prepro#essor dire#ti%e is #onsidered to end& ,o semi#olon .L0 is e:pe#ted at the end o$ a prepro#essor dire#ti%e& The only "ay a prepro#essor dire#ti%e #an e:tend throu h more than one line is by pre#edin the ne"line #hara#ter at the end o$ the line by a ba#-slash . J0&

macro definitions 01define4 1undef2


To de$ine prepro#essor ma#ros "e #an use #define& 2ts $ormat is:

#define identifier replacement


=hen the prepro#essor en#ounters this dire#ti%e, it repla#es any o##urren#e o$ identifier in the rest o$ the #ode by replacement& This replacement #an be an e:pression, a statement, a blo#- or simply anythin & The prepro#essor does not understand C//, it simply repla#es any o##urren#e o$ identifier by replacement&

#define :>?96/7#Y6 -!! int ta&le-P:>?96/7#Y6Q; int ta&le,P:>?96/7#Y6Q;


'$ter the prepro#essor has repla#ed :>?96/7#Y6, the #ode be#omes e;ui%alent to:

int ta&le-P-!!Q; int ta&le,P-!!Q;


This use o$ Zde$ine as #onstant de$iner is already -no"n by us $rom pre%ious tutorials, but #define #an "or- also "ith parameters to de$ine $un#tion ma#ros:

#define getma1(a0&) a>&IaA&


This "ould repla#e any o##urren#e o$ getma1 $ollo"ed by t"o ar uments by the repla#ement e:pression, but also repla#in ea#h ar ument by its identi$ier, e:a#tly as you "ould e:pe#t i$ it "as a $un#tion:

// function macro #include <iostream> using namespace std; #define getma1(a0&) ((a)>(&)I(a)A(&)) int main() { int 1*+0 y; y* getma1(10,);

+ E

cout << y << endl; cout << getma1(E01) << endl; return !; "
De$ined ma#ros are not a$$e#ted by blo#- stru#ture& ' ma#ro lasts until it is unde$ined "ith the Zunde$ prepro#essor dire#ti%e:

#define :>?96/7#Y6 -!! int ta&le-P:>?96/7#Y6Q; #undef :>?96/7#Y6 #define :>?96/7#Y6 ,!! int ta&le,P:>?96/7#Y6Q;
This "ould enerate the same #ode as:

int ta&le-P-!!Q; int ta&le,P,!!Q;


*un#tion ma#ro de$initions a##ept t"o spe#ial operators . # and ##0 in the repla#ement se;uen#e: 2$ the operator # is used be$ore a parameter is used in the repla#ement se;uen#e, that parameter is repla#ed by a strin literal .as i$ it "ere en#losed bet"een double ;uotes0

#define str(1) #1 cout << str(test);


This "ould be translated into:

cout << "test";


The operator ## #on#atenates t"o ar uments lea%in no blan- spa#es bet"een them:

#define glue(a0&) a ## & glue(c0out) << "test";


This "ould also be translated into:

cout << "test";


6e#ause prepro#essor repla#ements happen be$ore any C// synta: #he#-, ma#ro de$initions #an be a tri#-y $eature, but be #are$ul: #ode that relies hea%ily on #ompli#ated ma#ros may result obs#ure to other pro rammers, sin#e the synta: they e:pe#t is on many o##asions di$$erent $rom the re ular e:pressions pro rammers e:pe#t in C//&

Conditional inclusions 01ifdef4 1ifndef4 1if4 1endif4 1else and 1elif2


These dire#ti%es allo" to in#lude or dis#ard part o$ the #ode o$ a pro ram i$ a #ertain #ondition is met&

#ifdef allo"s a se#tion o$ a pro ram to be #ompiled only i$ the ma#ro that is spe#i$ied as the
parameter has been de$ined, no matter "hi#h its %alue is& *or e:ample:

#ifdef :>?96/7#Y6 int ta&leP:>?96/7#Y6Q;

#endif
2n this #ase, the line o$ #ode int ta&leP:>?96/7#Y6Q; is only #ompiled i$ :>?96/7#Y6 "as pre%iously de$ined "ith #define, independently o$ its %alue& 2$ it "as not de$ined, that line "ill not be in#luded in the pro ram #ompilation&

#ifndef ser%es $or the e:a#t opposite: the #ode bet"een #ifndef and #endif dire#ti%es is only
#ompiled i$ the spe#i$ied identi$ier has not been pre%iously de$ined& *or e:ample:

#ifndef :>?96/7#Y6 #define :>?96/7#Y6 -!! #endif int ta&leP:>?96/7#Y6Q;


2n this #ase, i$ "hen arri%in at this pie#e o$ #ode, the :>?96/7#Y6 ma#ro has not been de$ined yet, it "ould be de$ined to a %alue o$ 100& 2$ it already e:isted it "ould -eep its pre%ious %alue sin#e the #define dire#ti%e "ould not be e:e#uted& The #if, #else and #elif .i&e&, <else i$<0 dire#ti%es ser%e to spe#i$y some #ondition to be met in order $or the portion o$ #ode they surround to be #ompiled& The #ondition that $ollo"s #if or #elif #an only e%aluate #onstant e:pressions, in#ludin ma#ro e:pressions& *or e:ample:

#if :>?96/7#Y6>,!! #undef :>?96/7#Y6 #define :>?96/7#Y6 ,!! #elif :>?96/7#Y6<+! #undef :>?96/7#Y6 #define :>?96/7#Y6 +! #else #undef :>?96/7#Y6 #define :>?96/7#Y6 -!! #endif int ta&leP:>?96/7#Y6Q;
,oti#e ho" the "hole stru#ture o$ #if, #elif and #else #hained dire#ti%es ends "ith #endif& The beha%ior o$ #ifdef and #ifndef #an also be a#hie%ed by usin the spe#ial operators defined and defined respe#ti%ely in any #if or #elif dire#ti%e:

#if defined :>?96/7#Y6 #define :>?96/7#Y6 -!! #elif defined >55>@/7#Y6 #define :>?96/7#Y6 >55>@/7#Y6 int ta&leP:>?96/7#Y6Q;

/ine control 01line2


=hen "e #ompile a pro ram and some error happen durin the #ompilin pro#ess, the #ompiler sho"s an error messa e "ith re$eren#es to the name o$ the $ile "here the error happened and a line number, so it is easier to $ind the #ode eneratin the error& The #line dire#ti%e allo"s us to #ontrol both thin s, the line numbers "ithin the #ode $iles as "ell as the $ile name that "e "ant that appears "hen an error ta-es pla#e& 2ts $ormat is:

#line num&er "filename"


=here num&er is the ne" line number that "ill be assi ned to the ne:t #ode line& The line numbers o$ su##essi%e lines "ill be in#reased one by one $rom this point on&

"filename" is an optional parameter that allo"s to rede$ine the $ile name that "ill be sho"n& *or
e:ample:

#line ,! "assigning 2aria&le" int aI;


This #ode "ill enerate an error that "ill be sho"n as error in $ile "assigning 2aria&le", line 20&

>rror directi"e 01error2


This dire#ti%e aborts the #ompilation pro#ess "hen it is $ound, eneratin a #ompilation the error that #an be spe#i$ied as its parameter:

#ifndef //cplusplus #error > C++ compiler is re4uired #endif


This e:ample aborts the #ompilation pro#ess i$ the ma#ro name //cplusplus is not de$ined .this ma#ro name is de$ined by de$ault in all C// #ompilers0&

Source file inclusion 01include2


This dire#ti%e has also been used assiduously in other se#tions o$ this tutorial& =hen the prepro#essor $inds an #include dire#ti%e it repla#es it by the entire #ontent o$ the spe#i$ied $ile& There are t"o "ays to spe#i$y a $ile to be in#luded:

#include "file" #include <file>


The only di$$eren#e bet"een both e:pressions is the pla#es .dire#tories0 "here the #ompiler is oin to loo- $or the $ile& 2n the $irst #ase "here the $ile name is spe#i$ied bet"een double1;uotes, the $ile is sear#hed $irst in the same dire#tory that in#ludes the $ile #ontainin the dire#ti%e& 2n #ase that it is not there, the #ompiler sear#hes the $ile in the de$ault dire#tories "here it is #on$i ured to loo- $or the standard header $iles& 2$ the $ile name is en#losed bet"een an le1bra#-ets <> the $ile is sear#hed dire#tly "here the #ompiler is #on$i ured to loo- $or the standard header $iles& There$ore, standard header $iles are usually in#luded in an le1bra#-ets, "hile other spe#i$i# header $iles are in#luded usin ;uotes&

Pragma directi"e 01pragma2


This dire#ti%e is used to spe#i$y di%erse options to the #ompiler& These options are spe#i$i# $or the plat$orm and the #ompiler you use& Consult the manual or the re$eren#e o$ your #ompiler $or more in$ormation on the possible parameters that you #an de$ine "ith #pragma& 2$ the #ompiler does not support a spe#i$i# ar ument $or #pragma, it is i nored 1 no error is enerated&

Predefined macro names


The $ollo"in ma#ro names are de$ined at any time: macro "alue UUL2,9UU 2nte er %alue representin the #urrent line in the sour#e #ode $ile bein #ompiled& UU*2L9UU ' strin literal #ontainin the presumed name o$ the sour#e $ile bein #ompiled& ' strin literal in the $orm <5mm dd yyyy< #ontainin the date in "hi#h the #ompilation UUD'T9UU pro#ess be an&

' strin literal in the $orm <hh:mm:ss< #ontainin the time at "hi#h the #ompilation pro#ess be an& 'n inte er %alue& 'll C// #ompilers ha%e this #onstant de$ined to some %alue& 2$ the UU#plusplus #ompiler is $ully #ompliant "ith the C// standard its %alue is e;ual or reater than 199411L dependin on the %ersion o$ the standard they #omply& UUT259UU *or e:ample:

// standard macro names #include <iostream> using namespace std; int main() { cout << ":)is is t)e line num&er " << //9#;6//; cout << " of file " << //R#96// << "FJn"; cout << "#ts compilation &egan " << //V>:6//; cout << " at " << //:#=6// << "FJn"; cout << ":)e compiler gi2es a //cplusplus 2alue of " << //cplusplus; return !; "

(nput5Output Bith files



ofstream) >tream #lass to "rite on $iles ifstream) >tream #lass to read $rom $iles fstream) >tream #lass to both read and "rite $romHto $iles&

Published by Juan Soulie


Last update on Jun 1G, 2004 at 10:39pm UTC

C// pro%ides the $ollo"in #lasses to per$orm output and input o$ #hara#ters toH$rom $iles:

These #lasses are deri%ed dire#tly or indire#tly $rom the #lasses istream, and ostream& =e ha%e already used ob?e#ts "hose types "ere these #lasses: cin is an ob?e#t o$ #lass istream and cout is an ob?e#t o$ #lass ostream& Ther$ore, "e ha%e already been usin #lasses that are related to our $ile streams& 'nd in $a#t, "e #an use our $ile streams the same "ay "e are already used to use cin and cout, "ith the only di$$eren#e that "e ha%e to asso#iate these streams "ith physi#al $iles& LetCs see an e:ample:

// &asic file operations #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile; myfileFopen ("e1ampleFt1t"); myfile << "Writing t)is to a fileFJn"; myfileFclose(); return !; "

Pfile e1ampleFt1tQ Writing t)is to a file

This #ode #reates a $ile #alled e1ampleFt1t and inserts a senten#e into it in the same "ay "e are used to do "ith cout, but usin the $ile stream myfile instead& 6ut letCs o step by step:

Open a file
The $irst operation enerally per$ormed on an ob?e#t o$ one o$ these #lasses is to asso#iate it to a real $ile& This pro#edure is -no"n as to open a file& 'n open $ile is represented "ithin a pro ram by a stream ob?e#t .an instantiation o$ one o$ these #lasses, in the pre%ious e:ample this "as myfile0 and any input or output operation per$ormed on this stream ob?e#t "ill be applied to the physi#al $ile asso#iated to it& 2n order to open a $ile "ith a stream ob?e#t "e use its member $un#tion open():

open (filename0 mode);


=here filename is a null1terminated #hara#ter se;uen#e o$ type const c)ar % .the same type that strin literals ha%e0 representin the name o$ the $ile to be opened, and mode is an optional parameter "ith a #ombination o$ the $ollo"in $la s:

ios::in )pen $or input operations& ios::out )pen $or output operations& ios::binary )pen in binary mode& >et the initial position at the end o$ the $ile& ios::ate 2$ this $la is not set to any %alue, the initial position is the be innin o$ the $ile& 'll output operations are per$ormed at the end o$ the $ile, appendin the #ontent to the ios::app #urrent #ontent o$ the $ile& This $la #an only be used in streams open $or output1only operations& 2$ the $ile opened $or output operations already e:isted be$ore, its pre%ious #ontent is ios::trun# deleted and repla#ed by the ne" one& 'll these $la s #an be #ombined usin the bit"ise operator )+ .N0& *or e:ample, i$ "e "ant to open the $ile e1ampleF&in in binary mode to add data "e #ould do it by the $ollo"in #all to member $un#tion open():

ofstream myfile; myfileFopen ("e1ampleF&in"0 iosAAout N iosAAapp N iosAA&inary);


9a#h one o$ the open() member $un#tions o$ the #lasses ofstream, ifstream and fstream has a de$ault mode that is used i$ the $ile is opened "ithout a se#ond ar ument: class default mode parameter o$stream ios::out i$stream ios::in $stream ios::in Y ios::out *or ifstream and ofstream #lasses, iosAAin and iosAAout are automati#ally and respe#ti%elly assumed, e%en i$ a mode that does not in#lude them is passed as se#ond ar ument to the open() member $un#tion& The de$ault %alue is only applied i$ the $un#tion is #alled "ithout spe#i$yin any %alue $or the mode parameter& 2$ the $un#tion is #alled "ith any %alue in that parameter the de$ault mode is o%erridden, not #ombined& *ile streams opened in binary mode per$orm input and output operations independently o$ any $ormat #onsiderations& ,on1binary $iles are -no"n as text files, and some translations may o##ur due to $ormattin o$ some spe#ial #hara#ters .li-e ne"line and #arria e return #hara#ters0& >in#e the $irst tas- that is per$ormed on a $ile stream ob?e#t is enerally to open a $ile, these three #lasses in#lude a #onstru#tor that automati#ally #alls the open() member $un#tion and has the e:a#t same parameters as this member& There$ore, "e #ould also ha%e de#lared the pre%ious myfile ob?e#t and #ondu#ted the same openin operation in our pre%ious e:ample by "ritin :

ofstream myfile ("e1ampleF&in"0 iosAAout N iosAAapp N iosAA&inary);


Combinin ob?e#t #onstru#tion and stream openin in a sin le statement& 6oth $orms to open a $ile are %alid and e;ui%alent& To #he#- i$ a $ile stream "as su##ess$ul openin a $ile, you #an do it by #allin to member is/open() "ith no ar uments& This member $un#tion returns a bool %alue o$ true in the #ase that indeed the stream ob?e#t is asso#iated "ith an open $ile, or $alse other"ise:

if (myfileFis/open()) { /% o'0 proceed (it) output %/ "

Closing a file
=hen "e are $inished "ith our input and output operations on a $ile "e shall #lose it so that its resour#es be#ome a%ailable a ain& 2n order to do that "e ha%e to #all the streamCs member $un#tion close()& This member $un#tion ta-es no parameters, and "hat it does is to $lush the asso#iated bu$$ers and #lose the $ile:

myfileFclose();
)n#e this member $un#tion is #alled, the stream ob?e#t #an be used to open another $ile, and the $ile is a%ailable a ain to be opened by other pro#esses& 2n #ase that an ob?e#t is destru#ted "hile still asso#iated "ith an open $ile, the destru#tor automati#ally #alls the member $un#tion close()&

'e<t files
Te:t $ile streams are those "here "e do not in#lude the iosAA&inary $la in their openin mode& These $iles are desi ned to store te:t and thus all %alues that "e input or output $romHto them #an su$$er some $ormattin trans$ormations, "hi#h do not ne#essarily #orrespond to their literal binary %alue& Data output operations on te:t $iles are per$ormed in the same "ay "e operated "ith cout:

// (riting on a te1t file #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile ("e1ampleFt1t"); if (myfileFis/open()) { myfile << ":)is is a lineFJn"; myfile << ":)is is anot)er lineFJn"; myfileFclose(); " else cout << "8na&le to open file"; return !; "

Pfile e1ampleFt1tQ :)is is a lineF :)is is anot)er lineF

Data input $rom a $ile #an also be per$ormed in the same "ay that "e did "ith cin:

// reading a te1t file #include <iostream> #include <fstream> #include <string> using namespace std; int main () { string line; ifstream myfile ("e1ampleFt1t"); if (myfileFis/open()) { ()ile ( myfileFeof() ) { getline (myfile0line); cout << line << endl; "

:)is is a lineF :)is is anot)er lineF

myfileFclose(); " else cout << "8na&le to open file"; " return !;

This last e:ample reads a te:t $ile and prints out its #ontent on the s#reen& ,oti#e ho" "e ha%e used a ne" member $un#tion, #alled eof() that returns true in the #ase that the end o$ the $ile has been rea#hed& =e ha%e #reated a "hile loop that $inishes "hen indeed myfileFeof() be#omes true .i&e&, the end o$ the $ile has been rea#hed0&

ChecEing state flags


2n addition to eof(), "hi#h #he#-s i$ the end o$ $ile has been rea#hed, other member $un#tions e:ist to #he#- the state o$ a stream .all o$ them return a bool %alue0: bad02 +eturns true i$ a readin or "ritin operation $ails& *or e:ample in the #ase that "e try to "rite to a $ile that is not open $or "ritin or i$ the de%i#e "here "e try to "rite has no spa#e le$t& fail02 +eturns true in the same #ases as bad.0, but also in the #ase that a $ormat error happens, li-e "hen an alphabeti#al #hara#ter is e:tra#ted "hen "e are tryin to read an inte er number& +eturns true i$ a $ile open $or readin has rea#hed the end& good02 2t is the most eneri# state $la : it returns $alse in the same #ases in "hi#h #allin any o$ the pre%ious $un#tions "ould return true& 2n order to reset the state $la s #he#-ed by any o$ these member $un#tions "e ha%e ?ust seen "e #an use the member $un#tion clear(), "hi#h ta-es no parameters&

eof02

get and put stream pointers


'll iHo streams ob?e#ts ha%e, at least, one internal stream pointer:

ifstream, li-e istream, has a pointer -no"n as the get pointer that points to the element to be
read in the ne:t input operation&

ofstream, li-e ostream, has a pointer -no"n as the put pointer that points to the lo#ation "here the
ne:t element has to be "ritten& *inally, fstream, inherits both, the et and the put pointers, $rom iostream ."hi#h is itsel$ deri%ed $rom both istream and ostream0& These internal stream pointers that point to the readin or "ritin lo#ations "ithin a stream #an be manipulated usin the $ollo"in member $un#tions:

tellg02 and tellp02


These t"o member $un#tions ha%e no parameters and return a %alue o$ the member type pos/type, "hi#h is an inte er data type representin the #urrent position o$ the et stream pointer .in the #ase o$ tellg0 or the put stream pointer .in the #ase o$ tellp0&

seeEg02 and seeEp02


These $un#tions allo" us to #han e the position o$ the et and put stream pointers& 6oth $un#tions are o%erloaded "ith t"o di$$erent prototypes& The $irst prototype is:

see'g ( position ); see'p ( position );


Usin this prototype the stream pointer is #han ed to the absolute position position .#ountin $rom the be innin o$ the $ile0& The type $or this parameter is the same as the one returned by $un#tions tellg and tellp: the member type pos/type, "hi#h is an inte er %alue& The other prototype $or these $un#tions is:

see'g ( offset0 direction ); see'p ( offset0 direction );


Usin this prototype, the position o$ the et or put pointer is set to an o$$set %alue relati%e to some spe#i$i# point determined by the parameter direction& offset is o$ the member type off/type, "hi#h is also an inte er type& 'nd direction is o$ type see'dir, "hi#h is an enumerated type .enum0 that determines the point $rom "here o$$set is #ounted $rom, and that #an ta-e any o$ the $ollo"in %alues: ios::be o$$set #ounted $rom the be innin o$ the stream ios::#ur o$$set #ounted $rom the #urrent position o$ the stream pointer ios::end o$$set #ounted $rom the end o$ the stream The $ollo"in e:ample uses the member $un#tions "e ha%e ?ust seen to obtain the siDe o$ a $ile:

// o&taining file si3e #include <iostream> #include <fstream> using namespace std; int main () { long &egin0end; ifstream myfile ("e1ampleFt1t"); &egin * myfileFtellg(); myfileFsee'g (!0 iosAAend); end * myfileFtellg(); myfileFclose(); cout << "si3e isA " << (end.&egin) << " &ytesFJn"; return !; "

si3e isA B! &ytesF

!inary files
2n binary $iles, to input and output data "ith the e:tra#tion and insertion operators . << and >>0 and $un#tions li-e getline is not e$$i#ient, sin#e "e do not need to $ormat any data, and data may not use the separation #odes used by te:t $iles to separate elements .li-e spa#e, ne"line, et#&&&0& *ile streams in#lude t"o member $un#tions spe#i$i#ally desi ned to input and output binary data se;uentially: (rite and read& The $irst one .(rite0 is a member $un#tion o$ ostream inherited by ofstream& 'nd read is a member $un#tion o$ istream that is inherited by ifstream& )b?e#ts o$ #lass fstream ha%e both members& Their prototypes are:

(rite ( memory/&loc'0 si3e ); read ( memory/&loc'0 si3e );


=here memory/&loc' is o$ type <pointer to #har< .c)ar%0, and represents the address o$ an array o$ bytes "here the read data elements are stored or $rom "here the data elements to be "ritten are ta-en& The si3e parameter is an inte er %alue that spe#i$ies the number o$ #hara#ters to be read or "ritten $romHto the memory blo#-&

// reading a complete &inary file #include <iostream> #include <fstream> using namespace std; ifstreamAApos/type si3e; c)ar % mem&loc'; int main () { ifstream file ("e1ampleFt1t"0 iosAAinNiosAA&inaryNiosAAate); if (fileFis/open()) { si3e * fileFtellg(); mem&loc' * ne( c)ar Psi3eQ; fileFsee'g (!0 iosAA&eg); fileFread (mem&loc'0 si3e); fileFclose(); cout << "t)e complete file content is in memory"; deletePQ mem&loc'; " else cout << "8na&le to open file"; return !;

t)e complete file content is in memory

"

2n this e:ample the entire $ile is read and stored in a memory blo#-& LetCs e:amine ho" this is done: *irst, the $ile is open "ith the iosAAate $la , "hi#h means that the et pointer "ill be positioned at the end o$ the $ile& This "ay, "hen "e #all to member tellg(), "e "ill dire#tly obtain the siDe o$ the $ile& ,oti#e the type "e ha%e used to de#lare %ariable si3e:

ifstreamAApos/type si3e; ifstreamAApos/type is a spe#i$i# type used $or bu$$er and $ile positionin and is the type returned by fileFtellg()& This type is de$ined as an inte er type, there$ore "e #an #ondu#t on it the same
operations "e #ondu#t on any other inte er %alue, and #an sa$ely be #on%erted to another inte er type lar e enou h to #ontain the siDe o$ the $ile& *or a $ile "ith a siDe under 2(6 "e #ould use int:

int si3e; si3e * (int) fileFtellg();


)n#e "e ha%e obtained the siDe o$ the $ile, "e re;uest the allo#ation o$ a memory blo#- lar e enou h to hold the entire $ile:

mem&loc' * ne( c)arPsi3eQ;

+i ht a$ter that, "e pro#eed to set the et pointer at the be innin o$ the $ile .remember that "e opened the $ile "ith this pointer at the end0, then read the entire $ile, and $inally #lose it:

fileFsee'g (!0 iosAA&eg); fileFread (mem&loc'0 si3e); fileFclose();


't this point "e #ould operate "ith the data obtained $rom the $ile& )ur pro ram simply announ#es that the #ontent o$ the $ile is in memory and then terminates&

!uffers and Synchroni,ation


=hen "e operate "ith $ile streams, these are asso#iated to an internal bu$$er o$ type stream&uf& This bu$$er is a memory blo#- that a#ts as an intermediary bet"een the stream and the physi#al $ile& *or e:ample, "ith an ofstream, ea#h time the member $un#tion put ."hi#h "rites a sin le #hara#ter0 is #alled, the #hara#ter is not "ritten dire#tly to the physi#al $ile "ith "hi#h the stream is asso#iated& 2nstead o$ that, the #hara#ter is inserted in that streamCs intermediate bu$$er& =hen the bu$$er is $lushed, all the data #ontained in it is "ritten to the physi#al medium .i$ it is an output stream0 or simply $reed .i$ it is an input stream0& This pro#ess is #alled synchronization and ta-es pla#e under any o$ the $ollo"in #ir#umstan#es:

When the file is closed) be$ore #losin a $ile all bu$$ers that ha%e not yet been $lushed are syn#hroniDed and all pendin data is "ritten or read to the physi#al medium& When the buffer is full) 6u$$ers ha%e a #ertain siDe& =hen the bu$$er is $ull it is automati#ally syn#hroniDed& ><plicitly4 Bith manipulators) =hen #ertain manipulators are used on streams, an e:pli#it syn#hroniDation ta-es pla#e& These manipulators are: flus) and endl& ><plicitly4 Bith member function sync02) Callin streamCs member $un#tion sync(), "hi#h ta-es no parameters, #auses an immediate syn#hroniDation& This $un#tion returns an int %alue e;ual to .- i$ the stream has no asso#iated bu$$er or in #ase o$ $ailure& )ther"ise .i$ the stream bu$$er "as su##ess$ully syn#hroniDed0 it returns !&

C++ /anguage *AJ


*re=uently AsEed Juestions

Published by Juan Soulie


Last update on 5ar 3, 2008 at 9:G!pm UTC

What is C++? C// is a pro rammin lan ua e& 2t literally means <in#reased C<, re$le#tin its nature as an e%olution o$ the C lan ua e& (s it necessary to already EnoB another programming language before learning C++? ,ot ne#essarily& C// is a simple and #lear lan ua e in its e:pressions& 2t is true that a pie#e o$ #ode "ritten "ith C// may be seen by a stran er o$ pro rammin a bit more #rypti# than some other lan ua es due to the intensi%e use o$ spe#ial #hara#ters .JKRSITBY&&&0, but on#e one -no"s the meanin o$ su#h #hara#ters it #an be e%en more s#hemati# and #lear than other lan ua es that rely more on 9n lish "ords& 'lso, the simpli$i#ation o$ the inputHoutput inter$a#e o$ C// in #omparison to C and the in#orporation o$ the standard template library in the lan ua e, ma-es the #ommuni#ation and manipulation o$ data in a pro ram "ritten in C// as simple as in other lan ua es, "ithout losin the po"er it o$$ers& RdlS HoB can ( learn C++? There are many "ays& Dependin on the time you ha%e and your pre$eren#es& The lan ua e is tau ht in many types o$ a#ademi# $orms throu hout the "orld, and #an also be learnt by onesel$ "ith the help o$ tutorials and boo-s& The do#umentation se#tion o$ this =ebsite #ontains an online tutorial to help you a#hie%e the ob?e#ti%e o$ learnin this lan ua e& What is OOP) Object oriented programming? 2t is a pro rammin model that treats pro rammin $rom a perspe#ti%e "here ea#h #omponent is #onsidered an ob?e#t, "ith its o"n properties and methods, repla#in or #omplementin strutured pro rammin paradi m, "here the $o#us "as on pro#edures and parameters& (s C++ a propietary language? ,o& ,o one o"ns the C// lan ua e& 'nyone #an use the lan ua e royalty1$ree& What is A+S( C++? ',>21C// is the name by "hi#h the international ',>2H2>) standard $or the C// lan ua e is -no"n& 6ut be$ore this standard "as published, C// "as already "idely used and there$ore there is a lot o$ #ode out there "ritten in pre1standard C//& +e$errin to ',>21C// e:pli#itly di$$eren#iates it $rom pre1standard C// #ode, "hi#h is in#ompatible in some "ays& HoB may ( EnoB if my compiler supports A+S( C++? The standard "as published in 1998, $ollo"ed by a re%ision in 2003& >ome #ompilers older than the standard implement already some o$ its $eatures, and many ne"er #ompilers donCt implement all ',>21C// $eatures& 2$ you ha%e doubts on "hether your #ompiler "ill be able to #ompile ',>21C// #ode, you #an try to #ompile a pie#e o$ #ode "ith some o$ the ne" $eatures introdu#ed mainly a$ter the publi#ation o$ the standard& *or e:ample, the $ollo"in #ode $ra ment uses the &ool type, and uses namespa#es and templates&

#include <iostream> >;7# <Z using namespace std; template <class :> &ool ansisupported (: 1) { return true; " int main() { if (ansisupported(!)) cout << ">;7# <Z"; return !;

"
2$ your #ompiler is able to #ompile this pro ram, you "ill be able to #ompile most o$ the e:istin ',>21C// #ode& HoB can ( maEe BindoBed programs? Aou need a C// #ompiler that #an lin- #ode $or your "indo"in en%ironment .=indo"s, 8=indo", 5a#)>, &&&0& =indo"ed pro rams do not enerally use the #onsole to #ommuni#ate "ith the user& They use a set o$ $un#tions or #lasses to manipulate "indo"s instead, "hi#h are spe#i$i# to ea#h en%ironment& 'ny"ay the same prin#iples apply both $or #onsole and "indo"ed pro rams, e:#ept $or #ommuni#atin "ith the user& What is $isual C++? And Bhat does K"isual programmingK mean? Fisual C// is the name o$ a C// #ompiler "ith an inte rated en%ironment $rom 5i#roso$t& 2t in#ludes spe#ial tools that simpli$y the de%elopment o$ lar e appli#ations as "ell as spe#i$i# libraries that impro%e produ#ti%ity& The use o$ these tools is enerally -no"n as %isual pro rammin & )ther manu$a#turers also de%elop these types o$ tools and libraries, li-e 6orland C//, Fisual ' e, et#&&&

Você também pode gostar