Vous êtes sur la page 1sur 51

yet another insignificant programming notes...

| HOME
TABLE OF CONTENTS (HIDE)

1. Why OOP? 1.1 Traditional Procedural-Oriented languages 1. O!"ect-Oriented Programming #anguages 1.$ %enefits of OOP . OOP %asics .1 &lasses ' (nstances . ) &lass is a $-&ompartment %o* encapsulating +ata and ,unctions .$ &lass +efinition .- &reating (nstances of a &lass .. +ot /.0 Operator .1 +ata Mem!ers /2aria!les0 .3 Mem!er ,unctions .4 Putting them Together5 )n OOP E*ample .6 &onstructors .17 +efault )rguments for ,unctions .11 8pu!lic8 9s. 8pri9ate8 )ccess &ontrol Modifiers .1 (nformation Hiding and Encapsulation .1$ :etters and ;etters .1- <ey=ord 8this8 .1. 8const8 Mem!er ,unctions .11 &on9ention for :etters>;etters and &onstructors .13 +efault &onstructor .14 &onstructor?s Mem!er (nitiali@er #ist .16 A+estructor . 7 A&opy &onstructor . 1 A&opy )ssignment Operator /B0 $. ;eparating Header and (mplementation -. E*ample5 The &ircle &lass .. E*ample5 The Time &lass 1. E*ample5 The Point &lass 3. E*ample5 The )ccount &lass 4. E*ample5 The %all class 6. E*ample5 The )uthor and %ooC &lasses /for a %ooCstore0 6.1 #et?s start =ith the )uthor class 6. ) %ooC is =ritten !y an )uthor - Dsing an 8O!"ect8 +ata Mem!er 6.$ Pass-!y-Eeference for O!"ects ,unction Parameters )uthor and string

C++ Programming Language


Object Oriente! Programming (OOP) in C++
"# $%& OOP'
;uppose that you =ant to assem!le your o=n P&F you go to a hard=are store and picC up a mother!oardF a processorF some E)MsF a hard disCF a casingF a po=er supplyF and put them

together. Gou turn on the po=erF and the P& runs. Gou need not =orry =hether the mother!oard is a --layer or 1-layer !oardF =hether the hard disC has - or 1 platesH $ inches or . inches in diameterF =hether the E)M is made in Iapan or <oreaF and so on. Gou simply put the hard=are components together and e*pect the machine to run. Of courseF you ha9e to maCe sure that you ha9e the correct interfacesF i.e.F you picC an (+E hard disC rather than a ;&;( hard disCF if your mother!oard supports only (+EH you ha9e to select E)Ms =ith the correct speed ratingF and so on. Je9erthelessF it is not difficult to set up a machine from hard=are components. ;imilarlyF a car is assem!led from parts and componentsF such as chassisF doorsF engineF =heelsF !reaCF transmissionF etc. The components are reusa!leF e.g.F a =heel can !e used in many cars /of the same specifications0. Hard=areF such as computers and carsF are assem!led from partsF =hich are reusa!le components. Ho= a!out soft=are? &an you 8assem!le8 a soft=are application !y picCing a routine hereF a routine thereF and e*pect the program to run? The ans=er is o!9iously noK DnliCe hard=areF it is 9ery difficult to 8assem!le8 an application from software components. ;ince the ad9ent of computer 17 years agoF =e ha9e =ritten tons and tons of programs. Ho=e9erF for each ne= applicationF =e ha9e to re-in9ent the =heels and =rite the program from scratch. Why re-in9ent the =heels? "#" Tra!itiona( Proce!ura( Oriente! (anguage)

&an =e do this in traditional procedural-oriented programming language such as &F ,ortranF &o!olF or Pascal? Traditional procedural-oriented languages /such as & and Pascal0 suffer some nota!le dra=!acCs in creating reusa!le soft=are components5

1. The programs are made up of functions. ,unctions are often not reusable. (t is 9ery difficult to copy a function from one program and reuse in another program !ecause the the function is liCely to reference the headersF glo!al 9aria!les and other functions. (n other =ordsF functions are not =ell-encapsulated as a self-contained reusable unit. . The procedural languages are not suita!le of high-level abstraction for sol9ing real life pro!lems. ,or e*ampleF & programs uses constructs such as if-elseF for-loopF arrayF functionF pointerF =hich are lo=-le9el and hard to a!stract real pro!lems such as a &ustomer Eelationship Management /&EM0 system or a computer soccer game. /(magine using assem!ly codesF =hich is a 9ery lo= le9el codeF to =rite a computer soccer game. & is !etter !ut no much !etter.0 (n !riefF the traditional procedural-languages separate the data structures and algorithms of the soft=are entities. (n the early 1637sF the D; +epartment of +efense /+o+0 commissioned a tasC force to in9estigate =hy its (T !udget al=ays =ent out of controlH !ut =ithout much to sho= for. The findings are5 1. 47L of the !udget =ent to the soft=are /=hile the remaining 7L to the hard=are0. . More than 47L of the soft=are !udget =ent to maintenance /only the remaining 7L for ne= soft=are de9elopment0. $. Hard=are components could !e applied to 9arious productsF and their integrity normally did not affect other products. /Hard=are can share and reuseK Hard=are faults are isolatedK0 -. ;oft=are procedures =ere often non-shara!le and not reusa!le. ;oft=are faults could affect other programs running in computers. The tasC force proposed to maCe soft=are !eha9e liCe hard=are O%IE&T. ;u!seMuentlyF +o+ replaces o9er -.7 computer languagesF =hich =ere then used to !uild +o+ systemsF =ith an o!"ect-oriented language called )da. "#* Object Oriente! Programming Language)

O!"ect-oriented programming /OOP0 languages are designed to o9ercome these pro!lems. 1. The !asic unit of OOP is a classF =hich encapsulates !oth the static attributes and dynamic behaviors =ithin a 8!o*8F and specifies the pu!lic interface for using these !o*es. ;ince the class is =ell-encapsulated /compared =ith the function0F it is easier to reuse these classes. (n other =ordsF OOP com!ines the data structures and algorithms of a soft=are entity inside the same !o*. . OOP languages permit higher level of abstraction for sol9ing real-life pro!lems. The traditional procedural language /such as & and Pascal0 forces you to thinC in terms of the structure of the computer /e.g. memory !its and !ytesF arrayF decisionF loop0 rather than thinCing in terms of the pro!lem you are trying to sol9e. The OOP languages /such as Ia9aF &NNF &O0 let you thinC in the pro!lem spaceF and use soft=are o!"ects to represent and a!stract entities of the pro!lem space to sol9e the pro!lem.

)s an e*ampleF suppose you =ish to =rite a computer soccer games /=hich ( consider as a comple* application0. (t is Muite difficult to model the game in procedural-oriented languages. %ut using OOP languagesF you can easily model the program accordingly to the 8real things8 appear in the soccer games.

Player5 attri!utes include nameF num!erF location in the fieldF and etcH operations include runF "umpF CicC-the-!allF and etc. %all5 Eeference5 ,ield5 )udience5 Weather5

Most importantlyF some of these classes /such as Ball and Audience0 can !e reused in another applicationF e.g.F computer !asCet!all gameF =ith little or no modification. "#+ Bene,it) o, OOP The procedural-oriented languages focus on proceduresF =ith function as the !asic unit. Gou need to first figure out all the functions and then thinC a!out ho= to represent data. The o!"ect-oriented languages focus on components that the user percei9esF =ith o!"ects as the !asic unit. Gou figure out all the o!"ects !y putting all the data and operations that descri!e the user?s interaction =ith the data. O!"ect-Oriented technology has many !enefits5

Ease in software design as you could thinC in the pro!lem space rather than the machine?s !its and !ytes. Gou are dealing =ith high-le9el concepts and a!stractions. Ease in design leads to more producti9e soft=are de9elopment. Ease in software maintenance5 o!"ect-oriented soft=are are easier to understandF therefore easier to testF de!ugF and maintain. Reusable software5 you don?t need to Ceep re-in9enting the =heels and re-=rite the same functions for different situations. The fastest and safest =ay of de9eloping a ne= application is to reuse e*isting codes - fully tested and pro9en codes.

*# OOP Ba)ic)
*#" C(a))e) - In)tance) &lass5 ) class is a definition of objects of the same kind. (n other =ordsF a class is a !lueprintF templateF or prototype that defines and descri!es the static attributes and dynamic behaviors common to all o!"ects of the same Cind. (nstance5 )n instance is a realization of a particular item of a class. (n other =ordsF an instance is an instantiation of a class. )ll the instances of a class ha9e similar propertiesF as

descri!ed in the class definition. ,or e*ampleF you can define a class called 8Student8 and create three instances of the class 8Student8 for 8Peter8F 8Paul8 and 8Pauline8. The term 8object8 usually refers to instance. %ut it is often used Muite looselyF =hich may refer to a class or an instance. *#* A C(a)) i) a + Com.artment Bo/ enca.)u(ating Data an! Function)

) class can !e 9isuali@ed as a three-compartment !o*F as illustrated5 1. Classname /or identifier05 identifies the class. . Data Members or Variables /or attributesF statesF fields05 contains the static attributes of the class. $. Member Functions /or methodsF behaviorsF operations05 contains the dynamic operations of the class. (n other =ordsF a class encapsulates the static attri!utes /data0 and dynamic !eha9iors /operations that operate on the data0 in a !o*. &lass Mem!ers5 The data members and member functions are collecti9ely called class members. The follo=ings figure sho=s a fe= e*amples of classes5

The follo=ing figure sho=s t=o instances of the class StudentF identified as 8paul8 and 8perter8.

Dnified Modeling #anguage /DM#0 &lass and (nstance +iagrams5 The a!o9e class diagrams are dra=n according to the DM# notations. ) class is represented as a $-compartment !o*F containing nameF data mem!ers /9aria!les0F and mem!er functionsF respecti9ely. classname is sho=n in !old and centrali@ed. )n instance /o!"ect0 is also represented as a $-compartment !o*F =ith instance name sho=n as instanceName:Classname and underlined.
Brie, Summar&

1. ) class is a programmer-definedF a!stractF self-containedF reusa!le soft=are entity that mimics a real-=orld thing. . ) class is a $-compartment !o* containing the nameF data mem!ers /9aria!les0 and the mem!er functions.

$. ) class encapsulates the data structures /in data mem!ers0 and algorithms /mem!er functions0. The 9alues of the data mem!ers constitute its state. The mem!er functions constitute its behaviors. -. )n instance is an instantiation /or reali@ation0 of a particular item of a class. *#+ C(a)) De,inition (n &NNF =e use the Cey=ord class to define a class. There are t=o sections in the class declaration5 private and publicF =hich =ill !e e*plained later. ,or e*amplesF
class Circle { private: double radius; string color; public: double get adius(); double getArea(); # class SoccerPlayer { private: int number; string name; int $% &; public: void run(); void 'ic'Ball(); # // classname // Data members (variables) // !ember "unctions // classname // Data members (variables)

// !ember "unctions

&lass Jaming &on9ention5 ) classname shall !e a noun or a noun phrase made up of se9eral =ords. )ll the =ords shall !e initial-capitali@ed /camel-case0. Dse a singular noun for classname. &hoose a meaningful and self-descripti9e classname. ,or e*amplesF SoccerPla&erF (ttpPro$&ServerF )ile*nputStreamF PrintStream and Soc'et)actor&. *#0 Creating In)tance) o, a C(a)) To create an instance of a classF you ha9e to5 1. +eclare an instance identifier /name0 of a particular class. . (n9oCe a constructor to construct the instance /i.e.F allocate storage for the instance and initiali@e the 9aria!les0. ,or e*amplesF suppose that =e ha9e a class called CircleF =e can create instances of Circle as follo=s5
// Construct + instances o" t,e class Circle: c-% c.% and c+ Circle c-(-/.% 0red0); // radius% color Circle c.(+/1); // radius% de"ault color Circle c+; // de"ault radius and color

)lternati9elyF you can in9oCe the constructor e*plicitly using the follo=ing synta*5
Circle c- 2 Circle(-/.% 0red0); Circle c. 2 Circle(+/1); // radius% color // radius% de"ault color

Circle c+ 2 Circle();

// de"ault radius and color

*#1 Dot (#) O.erator To reference a member of a object /data mem!er or mem!er function0F you must5 1. ,irst identify the instance you are interested inF and then 2. Dse the dot operator //0 to reference the mem!erF in the form of instanceName.memberName. ,or e*ampleF suppose that =e ha9e a class called CircleF =ith t=o data mem!ers /radius and color0 and t=o functions /get adius() and getArea()0. We ha9e created three instances of the class CircleF namelyF c-F c. and c+. To in9oCe the function getArea()F you must first identity the instance of interestF says c.F then use the dot operatorF in the form of c./getArea()F to in9oCe the getArea() function of instance c.. ,or e*ampleF
// Declare and construct instances c- and c. o" t,e class Circle Circle c-(-/.% 0blue0); Circle c.(+/1% 0green0); // *nvo'e member "unction via dot operator cout 33 c-/getArea() 33 endl; cout 33 c./getArea() 33 endl; // e"erence data members via dot operator c-/radius 2 4/4; c./radius 2 5/5;

&alling getArea() =ithout identifying the instance is meaninglessF as the radius is unCno=n /there could !e many instances of Circle - each maintaining its o=n radius0. (n generalF suppose there is a class called AClass =ith a data mem!er called aData and a mem!er function called aFunction(). )n instance called anInstance is constructed for AClass. Gou use anInstance.aData and anInstance.aFunction(). *#2 Data 3ember) (4ariab(e)) ) data member /variable0 has a name /or identifier0 and a typeH and holds a value of that particular type /as descried in the earlier chapter0. ) data mem!er can also !e an instance of a certain class /to !e discussed later0. +ata Mem!er Jaming &on9ention5 ) data mem!er name shall !e a noun or a noun phrase made up of se9eral =ords. The first =ord is in lo=ercase and the rest of the =ords are initialcapitali@ed /camel-case0F e.g.F "ontSi6eF roomNumberF $!a$F &!in and $7op8e"t. TaCe note that 9aria!le name !egins =ith an lo=ercaseF =hile classname !egins =ith an uppercase. *#5 3ember Function) ) mem!er function /as descri!ed in the earlier chapter05 1. recei9es parameters from the callerF

. performs the operations defined in the function !odyF and $. returns a piece of result /or 9oid0 to the caller. Mem!er ,unction Jaming &on9ention5 ) function name shall !e a 9er!F or a 9er! phrase made up of se9eral =ords. The first =ord is in lo=ercase and the rest of the =ords are initialcapitali@ed /camel-case0. ,or e*ampleF get adius()F getParameter9alues(). TaCe note that data mem!er name is a noun /denoting a static attri!ute0F =hile function name is a 9er! /denoting an action0. They ha9e the same naming con9ention. Je9erthelessF you can easily distinguish them from the conte*t. ,unctions taCe arguments in parentheses /possi!ly @ero argument =ith empty parentheses0F !ut 9aria!les do not. (n this =ritingF functions are denoted =ith a pair of parenthesesF e.g.F println()F getArea() for clarity. *#6 Putting t%em Toget%er7 An OOP E/am.(e

) class called Circle is to !e defined as illustrated in the class diagram. (t contains t=o data mem!ers5 radius /of type double0 and color /of type String0H and three mem!er functions5 get adius()F getColor()F and getArea(). Three instances of Circles called c-F c.F and c+ shall then !e constructed =ith their respecti9e data mem!ersF as sho=n in the instance diagrams. (n this e*ampleF =e shall Ceep all the codes in a single source file called CircleA*:/cpp.
Circ(eAIO#c.. - /; 7,e Circle class (All source codes in one "ile) (CircleA*:/cpp) ;/ . <include 3iostream= // using *: "unctions

+ 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 .5 .> .? .@ +A ++. ++ +1 +4 +5 +> +? +@ 1A 11. 1+ 11 14 15 1> 1?

<include 3string= using namespace std; class Circle { private: double radius; string color;

// using string

// Data member (9ariable) // Data member (9ariable)

public: // Constructor Bit, de"ault values "or data members Circle(double r 2 -/A% string c 2 0red0) { radius 2 r; color 2 c; # double get adius() { return radius; # string getColor() { return color; # // !ember "unction (Cetter)

// !ember "unction (Cetter)

double getArea() { // !ember "unction return radius;radius;+/-1-5; # #; // need to end t,e class declaration Bit, a semiDcolon // 7est driver "unction int main() { // Construct a Circle instance Circle c-(-/.% 0blue0); cout 33 0 adius20 33 c-/get adius() 33 0 Area20 33 c-/getArea() 33 0 Color20 33 c-/getColor() 33 endl; // Construct anot,er Circle instance Circle c.(+/1); // de"ault color cout 33 0 adius20 33 c./get adius() 33 0 Area20 33 c./getArea() 33 0 Color20 33 c./getColor() 33 endl; // Construct a Circle instance using de"ault noDarg constructor Circle c+; // de"ault radius and color cout 33 0 adius20 33 c+/get adius() 33 0 Area20 33 c+/getArea() 33 0 Color20 33 c+/getColor() 33 endl; return A; #

To compile and run the program /=ith :JD :&& under Windo=s05
= g++ -o CircleAIO.exe CircleAIO.cpp // Do speci"ies t,e output "ile name = CircleAIO adius2-/. Area21/4.+@ Color2blue adius2+/1 Area2+5/+-5@ Color2red adius2- Area2+/-1-5 Color2red

*#8 Con)tructor)

) constructor is a special function that has the function name same as the classname. (n the a!o9e Circle classF =e define a constructor as follo=s5
// Constructor ,as t,e same name as t,e class Circle(double r 2 -/A% string c 2 0red0) { radius 2 r; color 2 c; #

) constructor is used to construct and initialize all the data members. To create a ne= instance of a classF you need to declare the name of the instance and in9oCe the constructor. ,or e*ampleF
Circle c-(-/.% 0blue0); Circle c.(+/1); // de"ault color Circle c+; // de"ault radius and color // 7a'e note t,at t,ere is no empt& brac'et ()

) constructor function is different from an ordinary function in the follo=ing aspects5


The name of the constructor is the same as the classname. &onstructor has no return type /or implicitly returns void0. HenceF no return statement is allo=ed inside the constructor?s !ody. &onstructor can only !e in9oCed once to initiali@e the instance constructed. Gou cannot call the constructor after=ards in your program. &onstructors are not inherited /to !e e*plained later0.

*#"9 De,au(t Argument) ,or Function) (n &NNF you can specify the default 9alue for the trailing arguments of a function /including constructor0 in the function header. ,or e*ampleF
. + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ./; 7est "unction de"ault arguments (7est)nDe"ault/cpp) ;/ <include 3iostream= using namespace std; // )unction protot&pe int sum(int n-% int n.% int n+ 2 A% int n1 2 A% int n4 2 A); int main() cout 33 cout 33 cout 33 cout 33 // cout 33 # { sum(-% sum(-% sum(-% sum(-% sum(-) -% -% -% -) 33 -% -% -) 33 endl; // -% -) 33 endl; // -) 33 endl; // 33 endl; // endl; // error: too 4 1 + . "eB arguments

// )unction de"inition // 7,e de"ault values s,all be speci"ied in "unction protot&pe% // not t,e "unction implementation int sum(int n-% int n.% int n+% int n1% int n4) { return n- E n. E n+ E n1 E n4; #

*#"" :.ub(ic: ;)# :.ri;ate: Acce)) Contro( 3o!i,ier) )n access control modifier can !e used to control the 9isi!ility of a data mem!er or a mem!er function =ithin a class. We !egin =ith the follo=ing t=o access control modifiers5
1. public5 The mem!er /data or function0 is accessi!le and a9aila!le to all in the

system.
2. private5 The mem!er /data or function0 is accessi!le and a9aila!le within this class

only. ,or e*ampleF in the a!o9e Circle definitionF the data mem!er radius is declared private. )s the resultF radius is accessi!le inside the Circle classF !ut JOT outside the class. (n other =ordsF you cannot use 8c-/radius8 to refer to c-?s radius in main(). Try inserting the statement 8cout 33 c-/radius;8 in main() and o!ser9e the error message5
CircleA*:/cpp:?:--: error: Fdouble Circle::radiusF is private

Try mo9ing radius to the public sectionF and re-run the statement. On the other handF the function get adius() is declared public in the Circle class. HenceF it can !e in9oCed in the main(). DM# Jotation5 (n DM# notationF public mem!ers are denoted =ith a 8E8F =hile private mem!ers =ith a 8D8 in the class diagram. *#"* In,ormation Hi!ing an! Enca.)u(ation ) class encapsulates the static attri!utes and the dynamic !eha9iors into a 8$-compartment !o*8. Once a class is definedF you can seal up the 8!o*8 and put the 8!o*8 on the shel9e for others to use and reuse. )nyone can picC up the 8!o*8 and use it in their application. This cannot !e done in the traditional procedural-oriented language liCe &F as the static attri!utes /or 9aria!les0 are scattered o9er the entire program and header files. Gou cannot 8cut8 out a portion of & programF plug into another program and e*pect the program to run =ithout e*tensi9e changes. +ata mem!er of a class are typically hidden from the outside =ordF =ith private access control modifier. )ccess to the pri9ate data mem!ers are pro9ided 9ia public assessor functionsF e.g.F get adius() and getColor(). This follo=s the principle of information hiding. That isF o!"ects communicate =ith each others using =ell-defined interfaces /pu!lic functions0. O!"ects are not allo=ed to Cno= the implementation details of others. The implementation details are hidden or encapsulated =ithin the class. (nformation hiding facilitates reuse of the class. Eule of Thum!5 +o not maCe any data mem!er publicF unless you ha9e a good reason. *#"+ <etter) an! Setter) To allo= other to read the 9alue of a private data mem!er says $$$F you shall pro9ide a get function /or getter or accessor function0 called getG$$(). ) getter need not e*pose the data

in ra= format. (t can process the data and limit the 9ie= of the data others =ill see. :etters shall not modify the data mem!er. To allo= other classes to modify the 9alue of a private data mem!er says $$$F you shall pro9ide a set function /or setter or mutator function0 called setG$$(). ) setter could pro9ide data 9alidation /such as range checCing0F and transform the ra= data into the internal representation. ,or e*ampleF in our Circle classF the data mem!ers radius and color are declared private. That is to sayF they are only a9aila!le =ithin the Circle class and not 9isi!le outside the Circle class - including main(). Gou cannot access the private data mem!ers radius and color from the main() directly - 9ia says c-/radius or c-/color. The Circle class pro9ides t=o pu!lic accessor functionsF namelyF get adius() and getColor(). These functions are declared public. The main() can in9oCe these pu!lic accessor functions to retrie9e the radius and color of a Circle o!"ectF 9ia says c-/get adius() and c-/getColor(). There is no =ay you can change the radius or color of a Circle o!"ectF after it is constructed in main(). Gou cannot issue statements such as c-/radius 2 4/A to change the radius of instance c-F as radius is declared as private in the Circle class and is not 9isi!le to other including main(). (f the designer of the Circle class permits the change the radius and color after a Circle o!"ect is constructedF he has to pro9ide the appropriate setterF e.g.F
// Setter "or color void setColor(string c) { color 2 c; # // Setter "or radius void set adius(double r) { radius 2 r; #

With proper implementation of information hidingF the designer of a class has full control of =hat the user of the class can and cannot do. *#"0 =e&>or! :t%i): Gou can use Cey=ord 8t,is8 to refer to this instance inside a class definition. One of the main usage of Cey=ord t,is is to resol9e am!iguity !et=een the names of data mem!er and function parameter. ,or e*ampleF
class Circle { private: double radius; // !ember variable called 0radius0 ////// public: void set adius(double radius) { // )unctionFs argument also called 0radius0

# //////

t,isD=radius 2 radius; // 0t,is/radius0 re"ers to t,is instanceFs member variable // 0radius0 resolved to t,e "unctionFs argument/

(n the a!o9e codesF there are t=o identifiers called radius - a data mem!er and the function parameter. This causes naming conflict. To resol9e the naming conflictF you could name the function parameter r instead of radius. Ho=e9erF radius is more appro*imate and meaningful in this conte*t. Gou can use Cey=ord t,is to resol9e this naming conflict. 8t,isD=radius8 refers to the data mem!erH =hile 8radius8 resol9es to the function parameter. 8t,is8 is actually a pointer to this o!"ect. ( =ill e*plain pointer and the meaning of 8D=8 operator later. )lternati9elyF you could use a prefi* /such as mH0 or suffi* /such as H0 to name the data mem!ers to a9oid name crashes. ,or e*ampleF
class Circle { private: double mHradius; // or radiusH ////// public: void set adius(double radius) { mHradius 2 radius; // or radiusH 2 radius # ////// #

&NN &ompiler internally names their data mem!ers !eginning =ith a leading underscore /e/g/% H$$$0 and local 9aria!les =ith leading underscores /e.g.F HH$$$0. HenceF a9oid name !eginning =ith underscore in your program. *#"1 :con)t: 3ember Function) ) const mem!er functionF identified !y a const Cey=ord at the end of the mem!er function?s headerF cannot modifies any data mem!er of this o!"ect. ,or e*ampleF
double get adius() const { // const member "unction radius 2 A; // error: assignment o" dataDmember FCircle::radiusF in readDonl& structure return radius; #

*#"2 Con;ention ,or <etter)?Setter) an! Con)tructor) The constructorF getter and setter functions for a private data mem!er called $$$ of type 7 in a class Aaa ha9e the follo=ing con9entions5
class Aaa { private:

// A private variable named $$$ o" t&pe 7 7 $$$; public: // Constructor Aaa(7 $) { $$$ 2 $; # // : Aaa(7 $$$) { t,isD=$$$ 2 $$$; # // : using member initiali6er list (to be e$plained later) Aaa(7 $$$) : $$$($$$) { # // A getter "or variable $$$ o" t&pe 7 receives no argument and return a value o" t&pe 7 7 getG$$() const { return $$$; # // A setter "or variable $$$ o" t&pe 7 receives a parameter o" t&pe 7 and return void void setG$$(7 $) { $$$ 2 $; # // : void setG$$(7 $$$) { t,isD=$$$ 2 $$$; # #

,or a bool 9aria!le $$$F the getter shall !e named isG$$()F instead of getG$$()F as follo=s5
private: // Private boolean variable bool $$$; public: // Cetter bool isG$$() const { return $$$; # // Setter void setG$$(bool $) { $$$ 2 $; # // : void setG$$(bool $$$) { t,isD=$$$ 2 $$$; #

*#"5 De,au(t Con)tructor ) default constructor is a constructor =ith no parametersF or ha9ing default 9alues for all the parameters. ,or e*ampleF the a!o9e Circle?s constructor can !e ser9ed as default constructor =ith all the parameters default.
Circle c-; // Declare c- as an instance o" Circle% and invo'e t,e de"ault constructor Circle c-(); // IrrorJ // (7,is declares c- as a "unction t,at ta'es no parameter and returns a Circle instance)

(f &NNF if you did not pro9ide )JG constructorF the compiler automatically pro9ides a default constructor that does nothing. That isF
ClassName::ClassName() { # // 7a'e no argument and do not,ing

&ompiler =ill not pro9ide a default constructor if you define any constructor/s0. (f all the constructors you defined reMuire argumentsF in9oCing no-argument default constructor results in error. This is to allo= class designer to maCe it impossi!le to create an uninitialized instanceF !y JOT pro9iding an e*plicit default constructor.

*#"6 Con)tructor@) 3ember Initia(iAer Li)t (nstead of initiali@ing the pri9ate data mem!ers inside the !ody of the constructorF as follo=s5
Circle(double r 2 -/A% string c 2 0red0) { radius 2 r; color 2 c; #

We can use an alternate synta* called member initializer list as follo=s5


Circle(double r 2 -/A% string c 2 0red0) : radius(r)% color(c) { #

Mem!er initiali@er list is placed after the constructor?s headerF separated !y a colon /:0. Each initaili@er is in the form of data_member_name(parameter_name). ,or fundamental typeF it is eMui9alent to data_member_name 2 parameter_name. ,or o!"ectF the constructor =ill !e in9oCed to construct the o!"ect. The constructor?s !ody /empty in this case0 =ill !e run after the completion of mem!er initiali@er list. (t is recommended to use mem!er initiali@er list to initiali@e all the data mem!ersF as it is often more efficient than doing assignment inside the constructor?s !ody. *#"8 BDe)tructor ) destructorF similar to constructorF is a special function that has the same name as the classnameF =ith a prefi* KF e.g.F KCircle(). +estructor is called implicitly =hen an o!"ect is destroyed. (f you do not define a destructorF the compiler pro9ides a defaultF =hich does nothing.
class !&Class { public: // 7,e de"ault destructor t,at does not,ing K!&Class() { # ////// # A!;ance! Note)

(f your class contains data mem!er =hich is dynamically allocated /9ia neB or neBLM operator0F you need to free the storage 9ia delete or deleteLM.

*#*9 BCo.& Con)tructor ) copy constructor constructs a ne= o!"ect !y copying an e*isting o!"ect of the same type. (n other =ordsF a copy constructor taCes an argumentF =hich is an o!"ect of the same class. (f you do not define a copy constructorF the compiler pro9ides a default =hich copies all the data mem!ers of the gi9en o!"ect. ,or e*ampleF
Circle c1(>/?% 0blue0); cout 33 0 adius20 33 c1/get adius() 33 0 Area20 33 c1/getArea()

33 0 Color20 33 c1/getColor() 33 endl; // adius2>/? Area2-@-/-+4 Color2blue // Construct a neB obNect b& cop&ing an e$isting obNect // via t,e soDcalled de"ault cop& constructor Circle c4(c1); cout 33 0 adius20 33 c4/get adius() 33 0 Area20 33 c4/getArea() 33 0 Color20 33 c4/getColor() 33 endl; // adius2>/? Area2-@-/-+4 Color2blue

&opy constructor is particularly important. (t is !ecause =hen an o!"ect is passed into a function by valueF the copy constructor =ould !e used to maCe a clone copy of the argument.
A!;ance! Note)

Pass-!y-9alue for o!"ect means calling the copy constructor. To a9oid the o9erhead of creating a clone copyF it is usually !etter to pass-!y-reference-to-constF =hich =ill not ha9e side effect on modifying the caller?s o!"ect. The copy constructor has the follo=ing signature5
class !&Class { private: 7- member-; 7. member.; public: // 7,e de"ault cop& constructor B,ic, constructs an obNect via memberBise cop& !&Class(const !&Class O r,s) { member- 2 r,s/member-; member. 2 r,s/member.; # ////// #

The default copy constructor performs shadow copy. (t does not copy the dynamically allocated data mem!ers created 9ia neB or neBLM operator.

*#*" BCo.& A))ignment O.erator (C) The compiler also pro9ides a default assignment operator /20F =hich can !e used to assign one o!"ect to another o!"ect of the same class 9ia mem!er=ise copy. ,or e*ampleF using the Circle class defined earlierF
Circle c5(4/5% 0orange0)% c>; cout 33 0 adius20 33 c5/get adius() 33 0 Area20 33 c5/getArea() 33 0 Color20 33 c5/getColor() 33 endl; // adius24/5 Area2@?/4.A5 Color2orange cout 33 0 adius20 33 c>/get adius() 33 0 Area20 33 c>/getArea() 33 0 Color20 33 c>/getColor() 33 endl; // adius2- Area2+/-1-5 Color2red (de"ault constructor) c> 2 c5; // memberBise cop& assignment cout 33 0 adius20 33 c>/get adius() 33 0 Area20 33 c>/getArea() 33 0 Color20 33 c>/getColor() 33 endl; // adius24/5 Area2@?/4.A5 Color2orange

A!;ance! Note)

Gou could o9erload the assignment opeator to o9erride the default. The copy constructorF instead of copy assignment operatorF is used in declaration5
Circle c? 2 c5; operator // *nvo'e t,e cop& constructor% N:7 cop& assignment // Same as Circle c?(c5)

The default copy assignment operator performs shadow copy. (t does not copy the dynamically allocated data mem!ers created 9ia neB or neBLM operator. The copy assignment operator has the follo=ing signature5
class !&Class { private: 7- member-; 7. member.; public: // 7,e de"ault cop& assignment operator B,ic, assigns an obNect via memberBise cop& !&Class O operator2(const !&Class O r,s) { member- 2 r,s/member-; member. 2 r,s/member.; return ;t,is; # ////// #

The copy assignment operator differs from the copy constructor in that it must release the dynamically allocated contents of the target and pre9ent self assignment. The assignment operator shall return a reference of this o!"ect to allo= chaining operation /such as $ 2 & 2 60. The default constructorF default destructorF default copy constructorF default copy assignment operators are Cno=n as special member functionsF in =hich the compiler =ill automatically generate a copy if they are used in the program and not e*plicitly defined.

+# Se.arating Hea!er an! Im.(ementation


,or !etter soft=are engineeringF it is recommended that the class declaration and implementation !e Cept in separate files5 declaration is a header file 8/,8H =hile implementation in a 8/cpp8. This is Cno=n as separating the pu!lic interface /header declaration0 and the implementation. (nterface is defined !y the designerF implementation can !e supplied !y others. While the interface is fi*edF different 9enders can pro9ide different implementations. ,urthermoreF only the header files are e*posed to the usersF the implementation can !e pro9ided in an o!"ect file 8/o8 /or in a li!rary0. The source code needs not gi9en to the users. ( shall illustrate =ith the follo=ing e*amples.

0# E/am.(e7 T%e Circ(e C(a))

(nstead of putting all the codes in a single file. We shall 8separate the interface and implementation8 !y placing the codes in $ files.
1. Circle/,5 defines the pu!lic interface of the Circle class. 2. Circle/cpp5 pro9ides the implementation of the Circle class. 3. 7estCircle/cpp5 ) test dri9er program for the Circle class.
Circ(e#% Hea!er . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 /; 7,e Circle class (eader (Circle/,) ;/ <include 3string= // using string using namespace std; // Circle class declaration class Circle { private: // Accessible b& members o" t,is class onl& // private data members (variables) double radius; string color; public: // Accessible b& A88 // Declare protot&pe o" member "unctions // Constructor Bit, de"ault values Circle(double radius 2 -/A% string color 2 0red0); // Public getters O setters "or private data members double get adius() const; void set adius(double radius); string getColor() const; void setColor(string color); // Public member )unction double getArea() const; #;

Program Jotes5

The header file contains declaration statementsF that tell the compiler a!out the names and typesF and function prototypes =ithout the implementation details.

&NN64>7$ does JOT allo= you to assign an initial 9alue to a data mem!er /e*cept const static mem!ers0. +ate mem!ers are to !e initiali@ed 9ia the constructor. ,or e*ampleF
double radius 2 -/A; // error: *S: CEE "orbids inDclass initiali6ation o" nonDconst static member FradiusF

&NN11 allo=s in-class initiali@ation of data mem!ers.

Gou can pro9ide default 9alue to function?s arguments in the header. ,or e*ampleF
Circle(double radius 2 -/A% string color 2 0red0);

Header contains function prototypeF the parameter names are ignored !y the compilerF !ut good to ser9e as documentation. ,or e*ampleF you can lea9e out the parameter names in the prototype as follo=s5
Circle(double 2 -/A% string 2 0red0); // Bit,out identi"iers // *denti"iers not needed in protot&pe but good to serve as documentation

Header files shall contains constantsF function prototypesF class>struct declarations.


Circ(e#c.. Im.(ementation . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 .5 .> .? .@ +A ++. ++ /; 7,e Circle class *mplementation (Circle/cpp) ;/ <include 0Circle/,0 // userDde"ined ,eader in t,e same director& // Constructor // de"ault values s,all onl& be speci"ied in t,e declaration% // cannot be repeated in de"inition Circle::Circle(double r% string c) { radius 2 r; color 2 c; # // Public getter "or private data member radius double Circle::get adius() const { return radius; # // Public setter "or private data member radius void Circle::set adius(double r) { radius 2 r; # // Public getter "or private data member color string Circle::getColor() const { return color; # // Public setter "or private data member color void Circle::setColor(string c) { color 2 c; # // A public member "unction double Circle::getArea() const {

+1 +4 #

return radius;radius;+/-1-4@.54;

Program Jotes5

The implementation file proi9ides the definition of the functionsF =hich are omitted from the declaration in the header file. Oinclude 8&ircle.h8 The compiler searches the headers in dou!le Muotes /such as 0Circle/,00 in the current directory firstF then the system?s include directories. ,or header in angle !racCet /such as 3iostream=0F the compiler doe JOT searches the current directoryF !ut only the system?s include directories. HenceF use dou!le Muotes for user-defined headers. &ircle55&ircle/dou!le rF string c0 P Gou need to include the className:: /called class scope resolution operator0 in front of all the mem!ers namesF so as to inform the compiler this mem!er !elong to a particular class. /&lass ;cope5 James defined inside a class ha9e so-called class scope. They are 9isi!le =ithin the class only. HenceF you can use the same name in t=o different classes. To use these names outside the classF the class scope resolution operator className:: is needed.0 Gou &)JJOT place the default arguments in the implementation /they shall !e placed in the header0. ,or e*ampleF
Circle::Circle(double r 2 -/A% string c 2 0red0) { // errorJ

Com.i(ing t%e Circ(e C(a))

Gou can compile the Circle/cpp to an o!"ect file called Circle/oF 9ia option Dc /compileonly0 in :JD :&&5
= g++ -c Circle.cpp // option Pc "or compileDonl&% output is Circle/o

To use the Circle classF the user needs Circle/, and Circle/o. He does not need Circle/cpp. (n other =ordsF you do not need to gi9e a=ay your source codesF !ut merely the pu!lic declarations and the o!"ect codes.
Te)tCirc(e#c.. Te)t Dri;er

#et?s =rite a test program to use the Circle class created.


. + 1 4 5 > ? @ /; A test driver "or t,e Circle class (7estCircle/cpp) ;/ <include 3iostream= <include 0Circle/,0 // using Circle class using namespace std; int main() { // Construct an instance o" Circle cCircle c-(-/.% 0red0); cout 33 0 adius20 33 c-/get adius() 33 0 Area20 33 c-/getArea()

-A --. -+ -1 -4 -5 -> -? -@ .A ... #

33 0 Color20 33 c-/getColor() 33 endl; c-/set adius(./-); // C,ange radius and color o" cc-/setColor(0blue0); cout 33 0 adius20 33 c-/get adius() 33 0 Area20 33 c-/getArea() 33 0 Color20 33 c-/getColor() 33 endl; // Construct anot,er instance using t,e de"ault constructor Circle c.; cout 33 0 adius20 33 c./get adius() 33 0 Area20 33 c./getArea() 33 0 Color20 33 c./getColor() 33 endl; return A;

Com.i(ing t%e Te)t Program

To compile 7estCircle/cpp =ith the o!"ect code Circle/o /and Circle/,05


= g++ -o TestCircle.exe TestCircle.cpp Circle.o // option Do speci"ies t,e output "ilename

Gou can also compile 7estCircle/cpp =ith the source code Circle/cpp /and Circle/,0
= g++ -o TestCircle.exe TestCircle.cpp Circle.cpp

1# E/am.(e7 T%e Time C(a))

#et?s =rite a class called 7imeF =hich models a specific instance of time =ith hourF minute and second 9aluesF as sho=n in the class diagram. The class 7ime contains the follo=ing mem!ers5

Three private data mem!ers5 ,our /7- $0F minute /7-.60 and second /7-.60F =ith default 9alues of 7. ) public constructor 7ime()F =hich initiali@es the data mem!ers ,ourF minute and second =ith the 9alues pro9ided !y the caller.
public getters and setters for pri9ate data mem!ers5 get(our()F get!inute()F getSecond()F set(our()F set!inute()F and setSecond().

) public mem!er function set7ime() to set the 9alues of ,ourF minute and second gi9en !y the caller. ) public mem!er function print() to print this 7ime instance in the format 8,,:mm:ss8F @ero-filledF e.g.F A-:+A:A1. ) public mem!er function ne$tSecond()F =hich increase this instance !y one second. ne$tSecond() of .+:4@:4@ shall !e AA:AA:AA.

#et?s =rite the code for the 7ime classF =ith the header and implementation separated in t=o files5 7ime/, and 7ime/cpp.
Hea!er Time#% /; (eader "or t,e 7ime class (7ime/,) ;/ <i"nde" 7*!IH( // *nclude t,is 0bloc'0 onl& i" 7*!IH( is N:7 de"ined <de"ine 7*!IH( // Qpon t,e "irst inclusion% de"ine 7*!IH( so t,at // t,is ,eader Bill not get included more t,an once class 7ime { private: // private section // private data members int ,our; // A D .+ int minute; // A D 4@ int second; // A D 4@ public: // public section // public member "unction protot&pes 7ime(int , 2 A% int m 2 A% int s 2 A); // Constructor Bit, de"ault values int get(our() const; // public getter "or private data member ,our void set(our(int ,); // public setter "or private data member ,our int get!inute() const; // public getter "or private data member minute void set!inute(int m); // public setter "or private data member minute int getSecond() const; // public getter "or private data member second void setSecond(int s); // public setter "or private data member second void set7ime(int ,% int m% int s); // set ,our% minute and second void print() const; // Print a description o" t,is instance in 0,,:mm:ss0 void ne$tSecond(); // *ncrease t,is instance b& one second #; // need to terminate t,e class declaration Bit, a semicolon <endi" // end o" 0<i"nde"0 bloc'

. + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 .5

Di))ecting Time#%

Oifndef T(MEQH Odefine T(MEQH ......

Oendif To pre9ent an header file from included more than once into a source file /=hich could result in compilation error if an entity is declared t=iceF e.g.F int i0F =e =rap the header codes =ithin a pair of preprocessor directives <i"nde" /if not define0 and <endi". The codes =ithin the if-!locC =ill only !e included if the identifier 7*!IH( has not !een defined. This is true for the first inclusionF =hich also defines the identifier 7*!IH( /the first directi9e in !ody of the if-!locC0. Jo su!seMuent inclusion is possi!leF since 7*!IH( has !een defined during the first inclusion. %y con9entionF use the identifier GGGH( /or GGGH(H*NC8QDID0 for header G$$/,. class Time P pri9ate5 ...... pu!lic5 ...... RH The header 7ime/, contains the class declaration for the class 7ime. (t is di9ided into t=o sections5 private and public. The private mem!ers /data or functions0 are accessi!le !y mem!ers of this class onlyF =hile public mem!ers are 9isi!le !y all /such as the main() function =hich is outside the class0. The class declaration must !e terminated !y a semicolon. pri9ate5 int hourH int minuteH int secondH pu!lic5 ...... We declare $ pri9ate data mem!ers called ,ourF minute and second. (n &NN64>&NN7$F you are JOT allo= to initiali@e a data mem!er in the class declaration /e*cept const static int data mem!ers0. ,or e*ampleF setting ,our 2 A causes a compilation error. (nsteadF the data mem!ers are to !e initiali@ed in the constructor /to !e sho=n later0. The ne=er &NN11 allo=s initiali@ation of data mem!ers. Only member function prototypes are listed in the class declaration. ) function prototype consists of the return-typeF function name and parameter types. Time/int h B 7F int m B 7F int s B 70H declares the so-called constructor. ) constructor is a special function that has the same name as the class. ) constructor has no return typeF or implicitly return void. Jo return statement is allo=ed inside the constructor?s !ody. ) constructor can only !e used during the instance declaration to initiali@e the data mem!ers of the instance. (t cannot !e in9oCed thereafter. (n the function prototypes of the headerF =e can set the default 9alues of the function?s parameters for any function mem!er using 82 default-value8. (n this caseF this constructor can !e in9oCed =ith 7 to $ argumentsF the omitted trailing arguments =ill !e set to their default 9aluesF e.g.F
7ime t-(-% .% +); // no de"ault used 7ime t.(-% .); // s 2 A (de"ault) 7ime t+(-); // m 2 A% s 2 A (de"aults)

7ime t1; parent,eses ()

// , 2 A% m 2 A% s 2 A (all de"aults) D no empt&

The identifiers ,F m and s are not needed in the function prototype - you only need to specify the parameters? types. %ut they ser9e as proper documentationF and are strongly recommended. int getHour/0 constH 9oid setHour/int h0H int getHour/0 constH 9oid setHour/int h0H int getHour/0 constH 9oid setHour/int h0H declare the so-called getter and setter for the pri9ate data mem!er ,ourF minute and second. ;ince the data mem!ers are private and are not accessi!le outside the classF public getters and setters are often pro9ided to read and modify the private data mem!ers. %y con9entionF a getter recei9es nothing /void0 from the caller and returns a 9alue of the type of the data mem!erH a setter recei9es a 9alue of the type of the data mem!er and returns void. ;etters may 9alidate the input !efore setting the 9alue of the data mem!er. We declare the getter function constantF !y placing the Cey=ord const after the function parameter list. ) const mem!er function cannot modify any data mem!er of this o!"ect. :etter does not need to modify any data mem!er. 9oid setTime/int hF int mF int s0H declares a pu!lic mem!er function to set the ,ourF minute and second of this instance in one call. 9oid print/0 constH declares a pu!lic mem!er function to print this instance in the format ((:!!:SSF @ero-filledF e.g.F A-:45:A@. The function print() returns void. 9oid ne*t;econd/0H declares a pu!lic mem!er function to increase this instance !y one second. ,or e*ampleF .+:4@:4@ !ecomes AA:AA:AA. The function ne$tSecond() returns void.
Im.(ementation Time#c.. . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 /; *mplementation "or t,e 7ime Class (7ime/cpp) ;/ <include 3iostream= <include 3iomanip= <include 07ime/,0 // include ,eader o" 7ime class using namespace std; // Constructor Bit, de"ault values/ No input validation 7ime::7ime(int ,% int m% int s) { ,our 2 ,; minute 2 m; second 2 s; # // public getter "or private data member ,our int 7ime::get(our() const { return ,our;

-> -? -@ .A ... .+ .1 .4 .5 .> .? .@ +A ++. ++ +1 +4 +5 +> +? +@ 1A 11. 1+ 11 14 15 1> 1? 1@ 4A 44. 4+ 41 44 45 4> 4? 4@ 5A 55. 5+ 51 54 55 5> 5? 5@ >A >>. >+

# // public setter "or private data member ,our/ No input validation void 7ime::set(our(int ,) { ,our 2 ,; # // public getter "or private data member minute int 7ime::get!inute() const { return minute; # // public setter "or private data member minute/ No input validation void 7ime::set!inute(int m) { minute 2 m; # // public getter "or private data member second int 7ime::getSecond() const { return second; # // public setter "or private data member second/ No input validation void 7ime::setSecond(int s) { second 2 s; # // Set ,our% minute and second/ No input validation void 7ime::set7ime(int ,% int m% int s) { ,our 2 ,; minute 2 m; second 2 s; # // Print t,is 7ime instance in t,e "ormat o" 0,,:mm:ss0% 6ero "illed void 7ime::print() const { cout 33 set"ill(FAF); // 6eroD"illed% need 3iomanip=% stic'& cout 33 setB(.) 33 ,our // set Bidt, to . spaces% need 3iomanip=% nonDstic'& 33 0:0 33 setB(.) 33 minute 33 0:0 33 setB(.) 33 second 33 endl; # // *ncrease t,is instance b& one second void 7ime::ne$tSecond() { EEsecond; i" (second =2 5A) { second 2 A; EEminute; # i" (minute =2 5A) { minute 2 A; EE,our; # i" (,our =2 .1) { ,our 2 A; # #

Di))ecting Time#c..

The implementation file 7ime/cpp contains mem!er?s definitions /=hereas the header file contains the declarations0F in particularF mem!er functions. )ll mem!er?s identifiers in the implementation are preceded !y the classname and the scope resolution operator /::0F e.g.F 7ime::7ime and 7ime::get(ourF so that the compiler can tell that these identifiers !elong to a particular classF in this caseF 7ime. Time55Time/int hF int mF int s0 P hour B hH minute B mH second B sH R (n the constructorF =e initiali@e the private data mem!ers ,ourF minute and second !ased on the inputs pro9ided !y the caller. &NN does JOT initiali@e fundamental-type /e.g.F intF double0 data mem!ers. (t also does JOT issue an error message if you use an data mem!er !efore it is initiali@ed. HenceF (t is strongly recommended to initiali@e all the data mem!ers in the constructorF so that the constructed instance is completeF instead of relying on the user to set the 9alues of the data mem!ers after construction. The default 9alues of the parameters are specified in the class declaration /in the header0F JOT in the function definition. Placing a default 9alue in function definition /e.g.F , 2 A0 causes a compilation error. TaCe note that =e ha9e not included input 9alidation /e.g.F hour shall !e !et=een 7 and $0 in the constructor /and setters0. We shall do that in the later e*ample. int Time55getHour/0 const P return hourH R the pu!lic getter for pri9ate data mem!er ,our simply returns the 9alue of the data mem!er ,our. 9oid Time55setHour/int h0 P hour B hH R the pu!lic setter for pri9ate data mem!er ,our sets the data mem!er ,our to the gi9en 9alue ,. )gainF there is no input 9alidation for h /shall !e !et=een 7 to $0. The rest of the function definitions are self-e*planatory.
:t%i): Pointer

(nstead of naming the function parameters ,F m and sF =e =ould liCe to name the parameters ,ourF minute and secondF =hich are semantically more meaningful. Ho=e9erF these names crashes =ith the names of pri9ate data mem!ers. &NN pro9ides a Cey=ord t,is /=hich is a pointer to this instance - to !e discussed later0 to differentiate !et=een the data mem!ers and function parameters. t,isD=,ourF t,isD=minute and t,isD=second refer to the data mem!ersH =hile ,ourF minuteF and second refer to the function parameters. We can re=rite the constructor and setter as follo=s5

7ime::7ime(int ,our% int minute% int second) { t,isD=,our 2 ,our; t,isD=minute 2 minute; t,isD=second 2 second; # 7ime::set(our(int ,our) { t,isD=,our 2 ,our; # 7ime::get(our() const { return t,isD=,our; # 3ember Initia(iAer Li)t // Setter "or ,our

// Constructor

// Cetter "or ,our // t,isD= is t,e de"ault% and ,ence optional

&NN pro9ide an alternative syntax to initiali@e data mem!ers in the constructor called member initializer list. ,or e*ampleF
7ime::7ime(int ,% int m% int s) : ,our(,)% minute(m)% second(s) { // 7,e bod& runs a"ter t,e member initiali6er list // empt& in t,is case #

The mem!er initiali@er list is placed after the function parameter listF separated !y a colonF in the form of dataMemberName(parameters). ,or fundamental-type data mem!ers /e.g.F intF double0F ,our(,) is the same as ,our 2 ,. ,or o!"ect data mem!ers /to !e discussed later0F the copy constructor =ill !e in9oCed. The function !ody =ill !e e*ecuted after the mem!er initiali@er listF =hich is empty in this case. The data mem!ers in the initiali@er list are initiali@ed in the order of their declarations in the class declarationF not the order in the initiali@er list.
Te)t Dri;er Te)tTime#c.. . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... /; 7est Driver "or t,e 7ime class (7est7ime/cpp) ;/ <include 3iostream= <include 07ime/,0 // include ,eader o" 7ime class using namespace std; int main() { 7ime t-(.+% 4@% 4@); // 7est constructor

// 7est all public member "unctions t-/print(); // .+:4@:4@ t-/set(our(-.); t-/set!inute(+A); t-/setSecond(-4); t-/print(); // -.:+A:-4 cout 33 0(our is 0 33 t-/get(our() 33 endl; cout 33 0!inute is 0 33 t-/get!inute() 33 endl; cout 33 0Second is 0 33 t-/getSecond() 33 endl; 7ime t.; // 7est constructor Bit, de"ault values "or ,our% minute and second t./print(); // AA:AA:AA t./set7ime(-% .% +);

.+ .1 .4 .5 .> .? .@ +A ++. ++ +1 +4 +5 +> +?

t./print();

// A-:A.:A+

7ime t+(-.); // Qse de"ault values "or minute and second t+/print(); // -.:AA:AA // 7est ne$tSecond() 7ime t1(.+% 4@% 4?); t1/print(); t1/ne$tSecond(); t1/print(); t1/ne$tSecond(); t1/print(); // No input validation 7ime t4(.4% 5-% @@); // values out o" range t4/print(); // .4:5-:@@

Di))ecting Te)tTime#c..

The test dri9er tests the constructor /=ith and =ithout the default 9alues0 and all the pu!lic mem!er functions. &learlyF no input 9alidation is carried outF as reflected in instance t4.
E/erci)e

)dd mem!er functions previousSecond()F ne$t!inute()F previous!inute()F ne$t(our()F previous(our() to the 7ime class.
Com.i(ing t%e Program

Gou can compile all the source file together to get the e*ecuta!le file as follo=s5
// Qsing CCC on RindoBs // Compile all source "iles% Do speci"ies t,e output = gEE Do 7est7ime/e$e 7ime/cpp 7est7ime/cpp // I$ecute t,e program = 7est7ime

)lternati9elyF you can compile 7ime/cpp into an o!"ect file 7ime/oF and then the test dri9er =ith the o!"ect file. (n this =ayF you only distri!ute the o!"ect file and header fileF not the source file.
// Compile 7ime/cpp into obNect "ile 7ime/o% Bit, Dc option = gEE Dc 7ime/cpp // Compile test driver Bit, obNect "ile = gEE Do 7est7ime/e$e 7est7ime/cpp 7ime/o // I$ecute t,e test driver = 7est7ime

2# E/am.(e7 T%e Point C(a))

The Point classF as sho=n in the class diagramF models + points =ith * and y co-ordinates. (n the class diagramF 8D8 denotes private mem!erH 8E8 denotes public mem!er. 82 $$$8 specifies the default 9alue of a data mem!er. The Point class contains the follo=ings5

Pri9ate data mem!ers $ and & /of type int0F =ith default 9alues of 7. ) constructorF getters and setters for pri9ate data mem!er $ and &. ) function setSG/0 to set !oth $ and & coordinates of a Point. ) function get!agnitude() =hich returns S($.E&.). Gou can use the !uilt-in sTrt() function in 3cmat,= to compute the sMuare root. ) function getArgument() =hich returns tanD-(&/$). Gou can use the !uilt-in atan.(&% $) function in 3cmat,= to compute the gradient in radians. ) function print() =hich prints 8($%&)8 of this instance.

Point#% Hea!er . + 1 4 5 > ? @ -A --. -+ -1 /; 7,e Point class (eader (Point/,) ;/ <i"nde" P:*N7H( <de"ine P:*N7H( // Point class declaration class Point { private: // private data members (variables) int $; int &; public: // Declare member "unction protot&pes Point(int $ 2 A% int & 2 A); // Constructor Bit, de"ault values

-4 int getG() const; -5 void setG(int $); -> int getU() const; -? void setU(int &); -@ void setGU(int $% int &); .A double get!agnitude() const; .double getArgument() const; .. void print() const; .+ #; .1 .4 <endi" Point#c.. Im.(ementation . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 .5 .> .? .@ +A ++. ++ +1 +4 +5 +> +? +@ 1A 11. 1+ 11 14 15 /; 7,e Point class *mplementation (Point/cpp) ;/ <include 0Point/,0 // userDde"ined ,eader in t,e same director& <include 3iostream= <include 3cmat,= using namespace std; // Constructor (de"ault values can onl& be speci"ied in t,e declaration) Point::Point(int $% int &) : $($)% &(&) { # // Qse member initiali6er list // Public getter "or private data member $ int Point::getG() const { return $; # // Public setter "or private data member $ void Point::setG(int $) { t,isD=$ 2 $; # // Public getter "or private data member & int Point::getU() const { return &; # // Public setter "or private data member & void Point::setU(int &) { t,isD=& 2 &; # // Public member "unction to set bot, $ and & void Point::setGU(int $% int &) { t,isD=$ 2 $; t,isD=& 2 &; # // Public member "unction to return t,e magitude double Point::get!agnitude() const { return sTrt($;$ E &;&); // sTrt in 3cmat,= # // Public member "unction to return t,e argument double Point::getArgument() const { return atan.(&% $); // atan. in 3cmat,= #

// Public member "unction to print description about t,is point 1> void Point::print() const { 1? cout 33 0(0 33 $ 33 0%0 33 & 33 0)0 33 endl; 1@ # Te)tPoint#c.. Te)t Dri;er . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 /; A test driver "or t,e Point class (7estPoint/cpp) ;/ <include 3iostream= <include 3iomanip= <include 0Point/,0 // using Point class using namespace std; int main() { // Construct an instance o" Point pPoint p-(+% 1); p-/print(); cout 33 0$ 2 0 33 p-/getG() 33 endl; cout 33 0& 2 0 33 p-/getU() 33 endl; cout 33 "i$ed 33 setprecision(.); cout 33 0mag 2 0 33 p-/get!agnitude() 33 endl; cout 33 0arg 2 0 33 p-/getArgument() 33 endl; p-/setG(5); p-/setU(?); p-/print(); p-/setGU(-% .); p-/print(); // Construct an instance o" Point using de"ault constructor Point p.; p./print(); #

5# E/am.(e7 T%e Account C(a))

) class called AccountF =hich models a !anC accountF is designed as sho=n in the class diagram. (t contains5

T=o pri9ate data mem!ers5 accountNumber /int0 and balance /double0F =hich maintains the current account !alance. Pu!lic functions credit() and debit()F =hich adds or su!tracts the gi9en amount from the !alanceF respecti9ely. The debit() function shall print 8amount =ithdra=n e*ceeds the current !alanceK8 if amount is more than balance. ) pu!lic function print()F =hich shall print 8)>& no5 *** %alanceB***8 /e.g.F )>& no5 661 $- %alanceBT44.440F =ith balance rounded to t=o decimal places.

Hea!er ,i(e Account#% . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A /; (eader "or Account class (Account/,) ;/ <i"nde" ACC:QN7H( <de"ine ACC:QN7H( class Account { private: int accountNumber; double balance; public: Account(int accountNumber% double balance 2 A/A); int getAccountNumber() const; double getBalance() const; void setBalance(double balance); void credit(double amount); void debit(double amount); void print() const; #; <endi"

Im.(ementation ,i(e Account#c.. . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A /; *mplementation "or t,e Account class (Account/cpp) ;/ <include 3iostream= <include 3iomanip= <include 0Account/,0 using namespace std; // Constructor Account::Account(int no% double b) : accountNumber(no)% balance(b) { # // Public getter "or private data member accountNumber int Account::getAccountNumber() const { return accountNumber; # // Public getter "or private data member balance double Account::getBalance() const { return balance; # // Public setter "or private data member balance

... .+ .1 .4 .5 .> .? .@ +A ++. ++ +1 +4 +5 +> +? +@ 1A 11. 1+

void Account::setBalance(double b) { balance 2 b; # // Adds t,e given amount to t,e balance void Account::credit(double amount) { balance E2 amount; # // Subtract t,e given amount "rom t,e balance void Account::debit(double amount) { i" (amount 32 balance) { balance D2 amount; # else { cout 33 0Amount Bit,draBn e$ceeds t,e current balanceJ0 33 endl; # # // Print description "or t,is Account instance void Account::print() const { cout 33 "i$ed 33 setprecision(.); cout 33 0A/C no: 0 33 accountNumber 33 0 Balance2V0 33 balance 33 endl; #

Te)t Dri;er Te)tAccount#c.. . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ./; 7est Driver "or Account class (7estAccount/cpp) ;/ <include 3iostream= <include 0Account/,0 using namespace std; int main() { Account a-(?---% @@/@@); a-/print(); // A/C no: ?--- Balance2V@@/@@ a-/credit(.A); a-/debit(-A); a-/print(); // A/C no: ?--- Balance2V-A@/@@ Account a.(?...); // de"ault balance a./print(); // A/C no: ?... Balance2VA/AA a./setBalance(-AA); a./credit(.A); a./debit(.AA); // Amount Bit,draBn e$ceeds t,e current balanceJ a./print(); // A/C no: ?... Balance2V-.A/AA return A; #

6# E/am.(e7 T%e Ba(( c(a))

) Ball class models a mo9ing !allF designed as sho=n in the class diagramF contains the follo=ing mem!ers5

,our private data mem!ers $F &F $Speed and &Speed to maintain the position and speed of the !all. ) constructorF and pu!lic getters and setters for the pri9ate data mem!ers. ) function setGU()F =hich sets the position of the !all and setGUSpeed() to set the speed of the !all. ) function move()F =hich increases $ and & !y $Speed and &SpeedF respecti9ely. ) function print()F =hich prints 8Ball W ($%&) Bit, speed ($Speed%&Speed)8F to decimal places.

Hea!er Fi(e Ba((#% . + 1 4 5 > ? @ -A /; (eader "or t,e Ball class (Ball/,) ;/ <i"nde" BA88H( <de"ine BA88H( class Ball { private: double $% &; // Position o" t,e ball double $Speed% &Speed; // Speed o" t,e ball public:

Ball(double $ 2 A/A% double & 2 A/A% // Constructor Bit, de"ault -values -. double $Speed 2 A/A% double &Speed 2 A/A); -+ double getG() const; -1 void setG(double $); -4 double getU() const; -5 void setU(double &); -> double getGSpeed() const; -? void setGSpeed(double $Speed); -@ double getUSpeed() const; .A void setUSpeed(double &Speed); .void setGU(double $% double &); .. void setGUSpeed(double $Speed% double &Speed); .+ void move(); .1 void print() const; .4 #; .5 .> <endi" Im.(ementation Fi(e Ba((#c.. . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 .5 .> .? .@ +A ++. ++ +1 +4 +5 +> +? +@ /; *mplementation "or t,e Ball Class (Ball/cpp) ;/ <include 3iostream= <include 3iomanip= <include 0Ball/,0 // include ,eader o" Ball class using namespace std; // Constructor Bit, de"ault values/ No input validation Ball::Ball(double $% double &% double $Speed% double &Speed) : $($)% &($)% $Speed($Speed)% &Speed(&Speed) { # // use member initiali6er list // public getters/setters "or private data members double Ball::getG() const { return $; # double Ball::getU() const { return &; # void Ball::setG(double $) { t,isD=$ 2 $; # void Ball::setU(double &) { t,isD=& 2 &; # double Ball::getGSpeed() const { return $Speed; # double Ball::getUSpeed() const { return &Speed; # void Ball::setGSpeed(double $Speed) { t,isD=$Speed 2 $Speed; # void Ball::setUSpeed(double &Speed) { t,isD=&Speed 2 &Speed; # // Set position ($%&) void Ball::setGU(double $% double &) {

1A 11. 1+ 11 14 15 1> 1? 1@ 4A 44. 4+ 41 44 45 4> 4? 4@ 5A

t,isD=$ 2 $; t,isD=& 2 &;

// Set speed ($Speed%&Speed) void Ball::setGUSpeed(double $Speed% double &Speed) { t,isD=$Speed 2 $Speed; t,isD=&Speed 2 &Speed; # // !ove t,e ball b& increases $ and & b& $Speed and &Speed void Ball::move() { $ E2 $Speed; // increment $ b& $Speed & E2 &Speed; // increment & b& &Speed # // Print a description about t,is Ball instance void Ball::print() const { cout 33 "i$ed 33 setprecision(.); cout 33 0Ball W (0 33 $ 33 F%F 33 & 33 0) Bit, speed (0 33 $Speed 33 F%F 33 &Speed 33 F)F 33 endl; #

Te)t Dri;er Te)tBa((#c.. . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? /; 7est Driver "or t,e Ball class (7estBall/cpp) ;/ <include 3iostream= <include 0Ball/,0 // include ,eader o" Ball class using namespace std; int main() { Ball ball; ball/print(); // Ball W (A/AA%A/AA) Bit, speed (A/AA%A/AA) ball/setGU(-/-% ./.); ball/setGUSpeed(+/+% 1/1); ball/print(); // Ball W (-/-A%./.A) Bit, speed (+/+A%1/1A) ball/setG(4/4); ball/setU(5/5); cout 33 0$ is 0 33 ball/getG() 33 endl; // $ is 4/4A cout 33 0& is 0 33 ball/getU() 33 endl; // & is 5/5A ball/move(); ball/print(); // Ball W (?/?A%--/AA) Bit, speed (+/+A%1/1A) #

8# E/am.(e7 T%e Aut%or an! BooD C(a))e) (,or a BooD)tore)


8#" Let@) )tart >it% t%e Aut%or c(a))

#et?s !egin =ith a class called Aut,orF designed as sho=n in the class diagram. (t contains5

Three private data mem!ers5 name /string0F email /string0F and gender /c,ar of FmFF F"F or FuF for unCno=n0. ) constructor to initiali@e the nameF email and gender =ith the gi9en 9alues. There are no default 9alues for data mem!ers. :etters for nameF email and genderF and setter for email. There is no setter for name and gender as =e assume that these attri!utes cannot !e changed. ) print() mem!er function that prints 8name /gender0 at email8F e.g.F 8Peter Iones /m0 at peterUsome=here.com8.

Hea!er Fi(e Aut%or#% . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ /; (eader "or t,e Aut,or class (Aut,or/,) ;/ <i"nde" AQ7(: H( <de"ine AQ7(: H( <include 3string= using namespace std; class Aut,or { private: string name; string email; c,ar gender;

// FmF% F"F% or FuF "or un'noBn

public: Aut,or(string name% string email% c,ar gender); string getName() const; string getImail() const; void setImail(string email); c,ar getCender() const; void print() const; #; <endi"

Im.(ementation Fi(e Aut%or#c.. . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 .5 .> .? .@ +A ++. ++ +1 +4 +5 +> +? +@ 1A 11. 1+ 11 14 /; *mplementation "or t,e Aut,or class (Aut,or/cpp) ;/ <include 3iostream= <include 0Aut,or/,0 using namespace std; // Constructor% Bit, input validation Aut,or::Aut,or(string name% string email% c,ar gender) { t,isD=name 2 name; setImail(email); // Call setter to c,ec' "or valid email i" (gender 22 FmF XX gender 22 F"F) { t,isD=gender 2 gender; # else { cout 33 0*nvalid genderJ Set to FuF (un'noBn)/0 33 endl; t,isD=gender 2 FuF; # # string Aut,or::getName() const { return name; # string Aut,or::getImail() const { return email; # void Aut,or::setImail(string email) { // C,ec' "or valid email/ Assume t,at a valid email contains // a FWF t,at is not t,e "irst nor last c,aracter/ si6eHt at*nde$ 2 email/"ind(FWF); i" (at*nde$ J2 string::npos OO at*nde$ J2 A OO at*nde$ J2 email/lengt,()D-) { t,isD=email 2 email; # else { cout 33 0*nvalid emailJ Set to empt& string/0 33 endl; t,isD=email 2 00; # # c,ar Aut,or::getCender() const { return gender; # // print in t,e "ormat 0name (gender) at email0 void Aut,or::print() const { cout 33 name 33 0 (0 33 gender 33 0) at 0 33 email 33 endl; #

Di))ecting t%e Aut%or#c..

)uthor55)uthor/string nameF string emailF char gender0 P this-Vname B nameH setEmail/email0H (n this e*ampleF =e use identifier name in the function?s parameterF =hich crashes =ith the data mem!er?s identifier name. To differentiate !et=een the t=o identifiersF =e use the Cey=ord t,isF =hich is a pointer to this instance. t,isD=name refers to the data mem!erH =hile name refers to the function?s parameter.

Jo input 9alidation is done on the parameter name. On the other handF for emailF =e in9oCe setter setImail() =hich performs input 9alidation. if /gender BB ?m? || gender BB ?f?0 P this-Vgender B genderH R else P cout WW 8(n9alid genderK ;et to ?u? /unCno=n0.8 WW endlH this-Vgender B ?u?H R R We 9alidate the input for gender /FmFF F"FF or FuF for unCno=n0. We assign FuF for any other inputs. 9oid )uthor55setEmail/string email0 P si@eQt found B email.find/?U?0H if /found KB string55npos '' found KB 7 '' found KB email.length/0-10 P this-Vemail B emailH R else P cout WW 8(n9alid emailK ;et to empty string.8 WW endlH this-Vemail B 88H R R To 9alidate emailF =e assume that there is an FWF =hich is not the first or last character /there are other stricter email 9alidation criteria0. We use the string class function "ind() to find the position of the character FWFF =hich returns a 9alue of type si6eHt /typically same as unsigned int0. The function "ind() returns a special constant string::npos /=hich is typically set to -10 to indicate 8not found8H 7 for the first character and lengt,()D- for the last character /=here string?s function lengt,() returns the length of the string0.
Te)tAut%or#c.. . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A /; 7est Driver "or t,e Aut,or class (7estAut,or/cpp) ;/ <include 0Aut,or/,0 int main() { // Declare and construct an instance o" Aut,or Aut,or peter(0Peter Yones0% 0peterWsomeB,ere/com0% FmF); peter/print(); // Peter Yones (m) at peterWsomeB,ere/com peter/setImail(0peterW$&6/com0); peter/print(); // Peter Yones (m) at peterW$&6/com Aut,or paul(0Paul Yones0% 0WsomeB,ere/com0% FnF); // *nvalid emailJ Set to empt& string/ // *nvalid genderJ Set to FuF (un'noBn)/ paul/setImail(0paulW0); // *nvalid emailJ Set to empt& string/ paul/print(); // Paul Yones (u) at

8#* A BooD i) >ritten b& an Aut%or E)ing an :Object: Data 3ember

#et?s design a Boo' class. )ssume that a !ooC is =ritten !y one and only one author. The Boo' class /as sho=n in the class diagram0 contains the follo=ing mem!ers5

,our private data mem!ers5 name /string0F aut,or /an instance of the class Aut,or that =e ha9e created earlier0F price /double0F and Tt&*nStoc' /intF =ith default 9alue of 70. The price shall !e positi9e and the Tt&*nStoc' shall !e @ero or positi9e. TaCe note that data mem!er aut,or is an instance /o!"ect0 of the class Aut,orF instead of a fundamental types /such as intF double0. (n factF name is an o!"ect of the class string too. The public getters and setters for the private data mem!ers. TaCe note that getAut,or() returns an o!"ect /an instance of class Aut,or0. ) public mem!er function print()F =hich prints 8?book-name? !y author-name /gender0 U email8. ) public mem!er function getAut,orName()F =hich returns the name of the author of this Boo' instance.

The hallow diamond shape in the class diagram denotes aggregation /or has-a0 association relationship. That isF a Boo' instance has one /and only one0 Aut,or instance as its component.
Hea!er Fi(e BooD#% . + 1 4 5 > ? /; (eader "or t,e class Boo' (Boo'/,) ;/ <i"nde" B::ZH( <de"ine B::ZH( <include 3string= <include 0Aut,or/,0 using namespace std; // Qse t,e Aut,or class

@ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 .5 .> .? .@

class Boo' { private: string name; Aut,or aut,or; // data member aut,or is an instance o" class Aut,or double price; int Tt&*nStoc'; public: Boo'(string name% Aut,or aut,or% double price% int Tt&*nStoc' 2 A); // 7o recieve an instance o" class Aut,or as argument string getName() const; Aut,or getAut,or() const; // eturns an instance o" t,e class Aut,or double getPrice() const; void setPrice(double price); int get[t&*nStoc'() const; void set[t&*nStoc'(int Tt&*nStoc'); void print() const; string getAut,orName() const; #; <endi"

Oinclude 8)uthor.h8 We need to include the 8Aut,or/,8 headerF as =e use the Aut,or class in this class Boo'. pri9ate5 )uthor authorH We declare a private data mem!er aut,or as an instance of class Aut,orF defined earlier.
Im.(ementation Fi(e BooD#c.. . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 .5 .> .? /; *mplementation "or t,e class Boo' (Boo'/cpp) ;/ <include 3iostream= <include 0Boo'/,0 using namespace std; // Constructor% Bit, member initiali6er list to initiali6e t,e // component Aut,or instance Boo'::Boo'(string name% Aut,or aut,or% double price% int Tt&*nStoc') : name(name)% aut,or(aut,or) { // !ust use member initiali6er list to construct obNect // Call setters to validate price and Tt&*nStoc' setPrice(price); set[t&*nStoc'(Tt&*nStoc'); # string Boo'::getName() const { return name; # Aut,or Boo'::getAut,or() const { return aut,or; # double Boo'::getPrice() const { return price; # // 9alidate price% B,ic, s,all be positive

.@ +A ++. ++ +1 +4 +5 +> +? +@ 1A 11. 1+ 11 14 15 1> 1? 1@ 4A 44. 4+ 41 44 45 4> 4? 4@ 5A

void Boo'::setPrice(double price) { i" (price = A) { t,isD=price 2 price; # else { cout 33 0price s,ould be positiveJ Set to A0 33 endl; t,isD=price 2 A; # # int Boo'::get[t&*nStoc'() const { return Tt&*nStoc'; # // 9alidate Tt&*nStoc'% B,ic, cannot be negative void Boo'::set[t&*nStoc'(int Tt&*nStoc') { i" (Tt&*nStoc' =2 A) { t,isD=Tt&*nStoc' 2 Tt&*nStoc'; # else { cout 33 0Tt&*nStoc' cannnot be negativeJ Set to A0 33 endl; t,isD=Tt&*nStoc' 2 A; # # // print in t,e "ormat 00Boo'Dname0 b& aut,orDname (gender) at email0 void Boo'::print() const { cout 33 0F0 33 name 33 0F b& 0; aut,or/print(); # // eturn t,e aut,orF name "or t,is Boo' string Boo'::getAut,orName() const { return aut,or/getName(); // invo'e t,e getName() on instance aut,or #

%ooC55%ooC/string nameF Aut%or aut%orF dou!le priceF int Mty(n;tocC0 5 name/name0F aut%or(aut%or) P setPrice/price0H setXty(n;tocC/Mty(n;tocC0H R (n the constructorF the caller is supposed to create an instance of Aut,orF and pass the instance into the constructor. We use member initializer list to initiali@e data mem!ers name and aut,or. We call setters in the !odyF =hich perform input 9alidation to set the price and Tt&*nStoc'. The !ody is run after the mem!er initiali@er list. The aut,or(aut,or) in9oCes the default copy constructor of the Aut,or classF =hich performs mem!er=ise copy for all the data mem!ers. O!"ect data mem!er shall !e constructed 9ia the mem!er initiali@er listF not in the !ody. Other=iseF the default constructor =ill !e in9oCed to construct the o!"ect. 9oid %ooC55setPrice/dou!le price0 P if /price V 70 P this-Vprice B priceH R else P cout WW 8price should !e positi9eK ;et to 78 WW endlH this-Vprice B 7H R R The setter for price 9alidates the gi9en input.

string %ooC55get)uthorJame/0 const P return author.getJame/0H R (n9oCe the getName() of the data mem!er aut,orF =hich returns the author?s name of this Boo' instance.
Te)tBooD#c.. . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 .5 /; 7est Driver "or t,e Boo' class (7estBoo'/cpp) ;/ <include 3iostream= <include 0Boo'/,0 using namespace std; int main() { // Declare and construct an instance o" Aut,or Aut,or peter(0Peter Yones0% 0peterWsomeB,ere/com0% FmF); peter/print(); // Peter Yones (m) at peterWsomeB,ere/com // Declare and construct an instance o" Boo' Boo' cppDumm&(0CEE "or Dummies0% peter% -@/@@); cppDumm&/set[t&*nStoc'(??); cppDumm&/print(); // FCEE "or DummiesF b& Peter Yones (m) at peterWsomeB,ere/com cout 33 cppDumm&/get[t&*nStoc'() 33 endl; // ?? cout 33 cppDumm&/getPrice() 33 endl; // -@/@@ cout 33 cppDumm&/getAut,or()/getName() 33 endl; // 0Peter Yones0 cout 33 cppDumm&/getAut,or()/getImail() 33 endl; // 0peterWsomeB,ere/com0 cout 33 cppDumm&/getAut,orName() 33 endl; // 0Peter Yones0 Boo' moreCpp(0!ore CEE "or Dummies0% peter% D-@/@@); // price s,ould be positiveJ Set to A cout 33 moreCpp/getPrice() 33 endl; // A #

T%e De,au(t Co.& Con)tructor

The initiali@er aut,or(aut,or) in the constructor in9oCes the so-called copy constructor. ) copy constructor creates a ne= instance !y copying the gi9en instance of the same class. (f you do not pro9ide a copy constructor in your classF &NN pro9ides a default copy constructorF =hich construct a ne= o!"ect 9ia mem!er=ise copy. ,or e*ampleF for Aut,or classF the default copy constructor pro9ided !y the compiler is as follo=s5
// De"ault cop& constructor o" Aut,or class provided b& CEE Aut,or::Aut,or(const Aut,orO ot,er) : name(ot,er/name)% email(ot,er/email)% gender(ot,er/gender) { # memberBise cop&

//

8#+ Pa)) b& Fe,erence ,or Object) Function Parameter) Aut%or an! )tring %y defaultF o!"ects are pass-!y-9alue into functions. That isF a clone copy is created and pass into the functionF instead of the original copy. Pass-!y-9alue for huge o!"ects depicts performance due to the o9erhead of creating a clone copy.

(nsteadF =e could pass an o!"ect into function by referenceF 9ia the reference /O0 declaration in the parameter list. (f =e do not intend to modify the o!"ect inside the function /=ith side effect to the original copy0F =e set it as const. (n the Boo' classF data mem!ers of string and Aut,or are o!"ects. Aut,or class =as defined earlierH string is a class pro9ided in &NN header 3string=F !elonging to the namespace std. (nstead of including 8using namespace std;8 in the header /=hich is a poor practice as this statement =ill !e included in all the files using this header0F =e shall use the scope resolution operator and refer to it as std::string. #et?s modify our Boo' class to illustrate pass-!y-reference /for performance0.
Aut%or#% . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ /; (eader "or Aut,or class (Aut,or/,) ;/ <i"nde" AQ7(: H( <de"ine AQ7(: H( <include 3string= class Aut,or { private: std::string name; std::string email; c,ar gender; // FmF% F"F% or FuF "or un'noBn public: Aut,or(const std::string O name% const std::string O email% c,ar gender); // O speci"ies pass b& re"erence% const "or nonDmutable std::string getName() const; std::string getImail() const; void setImail(const std::string O email); c,ar getCender() const; void print() const; #; <endi"

Program Jotes5

(n &NNF string is a class in the standard li!rary /in header WstringVF !elonging to namespace std0F "ust liCe PointF Circle classes that =e ha9e defined. (nstead of including 8using namespace std;8F =hich is a poor practice as this statement =ill !e included in all the files using this headerF =e use the fully-Mualified name std::string. (nstead of passing string o!"ects !y 9alue into functionF =hich affects performance as a clone copy needs to !e made. We pass the string o!"ects !y reference /indicated !y O0. Ho=e9erF in pass-!y-referenceF changes inside the function =ill affect the caller?s copy outside the function.

(f =e do not intend to change the o!"ect inside the functionF =e could use Cey=ord const to indicate immuta!ility. (f the o!"ect is inad9ertently changed inside the functionF compiler =ould issue an error.

Aut%or#c.. /; *mplementation "or t,e Aut,or class (Aut,or/cpp) ;/ <include 3iostream= <include 0Aut,or/,0 using namespace std; // Constructor% Bit, input validation Aut,or::Aut,or(const string O name% const string O email% c,ar gender) : name(name) { setImail(email); // Call setter to c,ec' "or valid email i" (gender 22 FmF XX gender 22 F"F) { t,isD=gender 2 gender; # else { cout 33 0*nvalid genderJ Set to FuF (un'noBn)/0 33 endl; t,isD=gender 2 FuF; # # string Aut,or::getName() const { return name; # string Aut,or::getImail() const { return email; # void Aut,or::setImail(const string O email) { // C,ec' "or valid email/ Assume t,at a valid email contains // a FWF t,at is not t,e "irst nor last c,aracter/ si6eHt at*nde$ 2 email/"ind(FWF); i" (at*nde$ J2 string::npos OO at*nde$ J2 A OO at*nde$ J2 email/lengt,()D-) { t,isD=email 2 email; # else { cout 33 0*nvalid emailJ Set to empt& string/0 33 endl; t,isD=email 2 00; # # c,ar Aut,or::getCender() const { return gender; # // print in t,e "ormat 0name (gender) at email0 void Aut,or::print() const { cout 33 name 33 0 (0 33 gender 33 0) at 0 33 email 33 endl; #

. + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 .5 .> .? .@ +A ++. ++ +1 +4 +5 +> +? +@ 1A 11. 1+ 11

Program Jotes5

)uthor55)uthor/con)t )tring - nameF con)t )tring - emai(F char gender0 P ...... R (n the constructorF the string o!"ects are passed !y reference. This impro9es the performance as it eliminates the need of creating a temporary /clone0 o!"ect. The

constructor then in9oCes the copy constructor of the string class to mem!er=ise copy the arguments into its data mem!ers name and email. We maCe the parameters const to pre9ent them from modifying inside the function /=ith side effect to the original copies0.
BooD#% . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 .5 .> .? /; (eader "or t,e class Boo' (Boo'/,) ;/ <i"nde" B::ZH( <de"ine B::ZH( <include 3string= <include 0Aut,or/,0 using namespace std; class Boo' { private: string name; Aut,or aut,or; double price; int Tt&*nStoc'; public: Boo'(const string O name% const Aut,or O aut,or% double price% int Tt&*nStoc' 2 A); string getName() const; Aut,or getAut,or() const; double getPrice() const; void setPrice(double price); int get[t&*nStoc'() const; void set[t&*nStoc'(int Tt&*nStoc'); void print() const; string getAut,orName() const; #; <endi" // Qse t,e Aut,or class

Program Jotes5

%ooC/con)t )tring - nameF con)t Aut%or - aut%orF dou!le priceF int Mty(n;tocC B 70H string and Aut,or o!"ects are passed into the constructor 9ia reference. This impro9es performance as it eliminates the creation of a temporary clone copy in pass!y-9alue. The parameters are marCed const as =e do not intend to modify them inside the function /=ith side effect to the original copies0. Aut%or get)uthor/0 constH The getter returns a copy of the data mem!er aut,or.

BooD#c.. . + 1 4 5 /; *mplementation "or t,e class Boo' (Boo'/cpp) ;/ <include 3iostream= <include 0Boo'/,0 using namespace std; // Constructor% Bit, member initiali6er list to initiali6e t,e

> ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 .4 .5 .> .? .@ +A ++. ++ +1 +4 +5 +> +? +@ 1A 11. 1+ 11 14 15 1> 1? 1@ 4A 44. 4+ 41 44 45 4> 4? 4@ 5A

// component Aut,or instance Boo'::Boo'(const string O name% const Aut,or O aut,or% double price% int Tt&*nStoc') : name(name)% aut,or(aut,or) { // *nit obNect re"erence in member initiali6er list // Call setters to validate price and Tt&*nStoc' setPrice(price); set[t&*nStoc'(Tt&*nStoc'); # string Boo'::getName() const { return name; # Aut,or Boo'::getAut,or() { return aut,or; # double Boo'::getPrice() const { return price; # // 9alidate price% B,ic, s,all be positive void Boo'::setPrice(double price) { i" (price = A) { t,isD=price 2 price; # else { cout 33 0price s,ould be positiveJ Set to A0 33 endl; t,isD=price 2 A; # # int Boo'::get[t&*nStoc'() const { return Tt&*nStoc'; # // 9alidate Tt&*nStoc'% B,ic, cannot be negative void Boo'::set[t&*nStoc'(int Tt&*nStoc') { i" (Tt&*nStoc' =2 A) { t,isD=Tt&*nStoc' 2 Tt&*nStoc'; # else { cout 33 0Tt&*nStoc' cannnot be negativeJ Set to A0 33 endl; t,isD=Tt&*nStoc' 2 A; # # // print in t,e "ormat 00Boo'Dname0 b& aut,orDname (gender) at email0 void Boo'::print() const { cout 33 0F0 33 name 33 0F b& 0; aut,or/print(); # // eturn t,e aut,orF name "or t,is Boo' string Boo'::getAut,orName() const { return aut,or/getName(); // invo'e t,e getName() on instance aut,or # %ooC55%ooC/con)t )tring - nameF Aut%or - aut%orF dou!le priceF int Mty(n;tocC0

5 name(name)F aut%or(aut%or) P ...... R name(name) and aut,or(aut,or) in9oCe the default copy constructors to construct ne= instances of string and Aut,or !y mem!er=ise copy the parameters.

Aut%or %ooC55get)uthor/0 P return aut%orH R ) copy of the data mem!er aut,or is returned to the caller. Gou should a9oid returning a reference of a pri9ate data mem!er to the caller /e.g.F Aut,or O Boo'::getAut,ro() { return aut,or; #0F as the caller can change the pri9ate data mem!er 9ia the referenceF =hich !reaCs the concept of 8information hiding and encapsulation8.

Te)t Dri;er Te)tBooD#c.. . + 1 4 5 > ? @ -A --. -+ -1 -4 -5 -> -? -@ .A ... .+ .1 /; 7est Driver "or t,e Boo' class (7estBoo'/cpp) ;/ <include 3iostream= <include 0Boo'/,0 using namespace std; int main() { // Declare and construct an instance o" Aut,or Aut,or peter(0Peter Yones0% 0peterWsomeB,ere/com0% FmF); peter/print(); // Peter Yones (m) at peterWsomeB,ere/com // Declare and construct an instance o" Boo' Boo' cppDumm&(0CEE "or Dummies0% peter% -@/@@); cppDumm&/print(); // FCEE "or DummiesF b& Peter Yones (m) at peterWsomeB,ere/com peter/setImail(0peterW$&6/com0); peter/print(); // Peter Yones (m) at peterW$&6/com cppDumm&/print(); // FCEE "or DummiesF b& Peter Yones (m) at peterWsomeB,ere/com cppDumm&/getAut,or()/setImail(0peterWabc/com0); cppDumm&/print(); // FCEE "or DummiesF b& Peter Yones (m) at peterWsomeB,ere/com #

(n the a!o9e test programF an instance of Aut,or called peter is constructed /in #ine 40. This instance is passed !y reference into Boo'?s constructor /#ine 1 0 to create the Boo'?s instance cppDumm&.
Summar&

)ll the codes in this 9ersion of e*ample /using references0 is e*actly the same as the pre9ious 9ersion /=ithout using references0F e*cept that the o!"ect function parameters are marCed =ith 8const classname O8 /e.g.F const string OF const Aut,or O0. This eliminates the creation of temporary clone o!"ect as in the pass-!y-9alueF =hich impro9es the performance. TaCe note that the constructor actually in9oCes the copy constructor to maCe a copy for its data mem!erF instead of referencing the copy pro9ided !y the caller. #inC to 8&NN Eeferences ' Eesources8 #atest 9ersion tested5 :&& /:NN0 -.1. #ast modified5 MayF 71$ ,eed!acCF commentsF correctionsF and errata can !e sent to &hua HocC-&huan /ehchuaUntu.edu.sg0 | HOME

Vous aimerez peut-être aussi