C___ an Introductory Guide for - Francis John Thottungal

61

description

An introduction to c++, variables, reserved words

Transcript of C___ an Introductory Guide for - Francis John Thottungal

C++

AnIntroductoryGuide

ForBeginners

FrancisJohnThottungal

C++

AllRightsReserved

Copyright©2015FrancisJohnThottungal

Thisbookmaynotbereproduced,transmitted,orstoredinwholeorinpartbyanymeans,includinggraphic,electronic,ormechanicalwithout theexpresswrittenconsentof thepublisherexcept in thecaseofbriefquotationsembodied incriticalarticlesandreviews.

Booktango

1663LibertyDrive

Bloomington,IN47403

www.booktango.com

877-445-8822

ISBN:978-1-4689-6322-9(ebook)

ContentsOverview

1–Thefirstprogram

1.0Thefirstprogram

1.1Comments

1.2Usingnamespace:std

1.3Variables

1.4FundamentalDataTypes

1.5DeclarationofVariables

1.5.1IntroductiontoStrings

1.5.2Operators

1.5.3Precedenceofoperators

1.5.4Scopeofavariable

2–I/O

2.0InputandOutput

2.1cout

2.2cin

3–Theflowcontrol

3.0Statements

3.1Ifandelse

3.2Loops

3.3Jumpstatements

3.4Switch

4–Functions

4.0Definitionofafunction

4.1Functionsthatdonotreturnavalue

5–Arrays

5.0WhatareArrays

5.1SimpleArrays

5.2Accessinganelementofanarray

5.3Multi-dimensionalArrays

6–Pointers

6.0WhatarePointers

6.1Pointerconcepts

7–Strings

7.0CharacterString

7.1StringFunctions

8–References

8.0WhatareReferences

9–File

9.0Inputandoutputwithfiles

9.1Openingafile

9.2Closingafile

9.3TextFiles

10–StorageClasses

10.0Typesofstorageclasses

11–Classes

11.0Buildingclasses

11.1Classconcepts

12–Inheritance

12.0TheconceptofInheritance

12.1SomeOOP’sterms

13–Exceptions

13.0Errorhandling

14–Conclusion

OverviewC++isgenerallyalanguagetaughttotechnicalstudentsincollegearoundtheworld.ThemainreasonC++,aderivativeofC,hasbecomeimportantisthatitisusedinprettymuchanything of a serious kind in programming such as developing drivers, graphical userinterfaces,operatingsystemsetc.

It is a technical language apt for technologists. However, anyone who is interested inprogrammingcanmasteritwithsomeeffort.Thislanguagehastwopartstoit-standaloneandobjectoriented.

Theapproach:Inthisguide, theapproachis toemphasizethebasicbuildingblocksofaC++program.Theemphasis is tohelpone tomakesimplestandaloneprograms.Theexamples in thisguidearerelativelysmallandperhapsacademic.

Onecandownloadthezipfileofallexamplecodeusedinthisguideatthelocationgivenattheendofthebook.

SoftwareUsed:TherearemanyC++editorsinthemarket.IusedtheMicrosoftVisualExpress2010.

To use this software or its latest version, just install the express version or full versionafterdownloadfromhttp://www.microsoft.com.

Youmaywanttodoasearchforeditorsespeciallyifusenon-windowsbasedcomputerssuchasLinuxorMac.

Asthis isnotatextbook, thegoalof thisguideis justforaquickstart tounderstandinghow towrite basicC++ code. It is intended for those completely new to the subject orprogramming in general. Itmight also serve thosewhoprefer less technical jargon andsimpleexamplestogetagraspofthelanguage.

Youmayviewordownload the instructionsandscreenshotsforusingMicrosoftVisualStudioorExpressversionsatthewebsitestatedattheendofthebook.

1Thefirstprogram

“Comeforthintothelightofthings,letnaturebeyourteacher.”—WilliamWordsworth

1.0ThefirstprogramThefirstprogramusuallywritteninanyprogramminglanguageclassisonethatdisplaystheword“HelloWorld”.Thisisakindofanunwrittentradition.Letuswritethecodeforthatnow:

#include<iostream>

intmain()

{

std::cout<<“HelloWorld!”;

}

Intheabovecode:

Ahashsign(#)indicatesdirectivesreadandinterpretedbythepre-processor.

Theintmain()isthedeclarationofafunction.AllC++programshaveamainfunction.

Theopenbrace({)indicatesthebeginningofmain’sfunctiondefinition,andtheclosingbrace(}),indicatesitsend.

Thestd::cout<<“HelloWorld!”isaC++statementtobeexecuted.

Here<<meansinsertionandcoutisthekeywordthatisneededtooutputthetext

Allstatementendswithasemicolon(;).Onecanenterblanklinesbetweenlinestomakethecodereadable.

InC++,onecanwriteseveralstatementsinasingleline,oreachstatementcanbeinitsownline.

Now, let us add an additional statement to our first program.Theoutput of the code isHelloWorld!MyC++program.Inotherwords,thetwostatementsareonthesameline.

Toavoidthisuseendlattheendofeachstatement.

#include<iostream>

intmain()

{

std::cout<<“HelloWorld!”;

std::cout<<“MyC++program”;

}

#include<iostream>

intmain()

{

std::cout<<“HelloWorld!”;<<endl;

std::cout<<“MyC++program”;<<endl;

}

1.1CommentsC++supportstwowaysofcommentingcode:

//linecomment

/*blockcomment*/

One canwrite short comments using the line comment. The block comments are usedwhenlargeramountoftextisrequiredinthecomments.

Letusaddcommentstoour“HelloWorld”program:

Wewilluseblockcommentsatthebeginningoftheprogramandlinecommentsforthestatements.

/*Thisisablockcomment.Thisprogramiswrittentoshowtheusageofcomments-blockandline*/

#include<iostream>

intmain()

{

std::cout<<“HelloWorld!”;//printsHelloWorld!

}

1.2Usingnamespace:stdByusingthenamespacestdwecanavoidwritingstd::couteverytimewewantsomethingwrittentothescreen.Forexample:

/*AprogramtowriteHelloWorld.Thisdemonstratestheuseofblockcomments*/

#include<iostream>

usingnamespacestd;

intmain()

{

cout<<“HelloWorld!”;//printsHelloWorld!

}

1.3VariablesVariablescanbefoundinmathematics.Youmusthaveseenstatementssuchas:

A=1;ora=5;ora+b=cetc.

Variablesholdvaluesordataforaperiodandreferenceaparticularareaofmemory.Likemany other programming languages, C++ uses variables. Each variable should have adistinctnameoridentifier.Insteadofcallingavariablebythelettersofthealphabet,wecouldgivethevariableusefulnamessuchasresultaslongasthenameisnotreservedasanexclusiveC++identifier.

A valid identifier or variable name is a sequence of one or more letters, digits, orunderscorescharacters(_).Spaces,punctuationmarks,andsymbolscannotbepartofanidentifier.Inaddition,identifiersshallalwaysbeginwithaletter.Theycanalsobeginwithanunderlinecharacter.Innocasecanitbeginwithadigit.

C++languageiscasesensitivesoacapitalvariableidentifierisdifferentfromlowercasevariableidentifier.

SomeexamplesofreservedidentifiersinC++are:

Thelistisonlyapartialone.

asm else new

auto enum operator

bool explicit private

break export protected

case extern public

catch FALSE register

char float reinterpret_cast

class for return

const friend short

const_cast goto signed

continue if sizeof

default inline static

delete int static_cast

do long struct

double mutable switch

Specificcompilersmayhaveadditionalreservedwords.

1.4FundamentalDataTypes• Charactertypes:Theycanrepresentasinglecharacter,suchas‘A’or‘$’.Themost

basictypeischar,whichisaone-bytecharacter.(ex:Char)

• Numericalintegertypes:Theycanstoreawholenumbervalue,suchas7or1024.Theyexistinavarietyofsizes,andcanbeeithersignedorunsigned,dependingonwhethertheysupportnegativevaluesornot.(ex:int)

• Floating-point types: They can represent real values, such as 3.14 or 0.01, withdifferentlevelsofprecision,dependingonwhichofthethreefloating-pointtypesisused.(ex:float,double)

• Booleantype:TheBooleantype,knowninC++asbool,canonlyrepresentoneoftwostates,trueorfalse.(ex:bool)

1.5DeclarationofVariablesTodeclareavariableoftypeintegerwewriteasfollows:

inta;

intb;

floatfirstnumber:

doublew;

chara;

Wecanalsodeclaremorethanonevariableofthesametypeinasinglelineasfollows:

intx,y,z;

Onecaninitializevariables.

intx=0;

#include<iostream>

usingnamespacestd;

intmain()

{

intx=5;//initialvalue:5

inty=2;//initialvalue:2

intz;

z=x+y;

cout<<z;

return0;

}

Sometimesitisconvenienttogiveaconstantvaluetoavariable.Forexample:

constpi=3.1415926;

However if you declare pi without const also the program will work. Most first timeprogrammersfromobservationdonotusetheconstvariabledefinition.

1.5.1IntroductiontoStringsWhile a character represents a single symbol such as ‘A’ or a ‘$’ a string represents acompoundtypeinC++.

Touseastringweneed to includeanewdirective# include<string> inaddition to thedirectiveiostream.

Weusecouttooutputthevalueofxtothescreen.

//Anexampleofastring

#include<iostream>

#include<string>

usingnamespacestd;

intmain()

{

stringx;

x=“Thisisanexampleofastring”;

cout<<x;

return0;

}

Intheexampleabovetheoutputwouldbethestring:

Thisisanexampleofastring

1.5.2OperatorsOperatorsareusedonvariablesandconstants.Thereareseveraltypesofoperators.

ThemostcommonoftheoperatorsinC++are:

• Assignmentoperators(=):

x = 2; The assignment operation always takes place from right to left. So here, x isassignedthevalueof2.

y = z; The statement assigns the value contained in z to the variable y. The valuecurrentlyinyislostandreplacedwiththevalueinz.Ifzchangesatalatermoment,itwillnotaffectthenewvaluetakenbyy.

//assignmentoperator

#include<iostream>

usingnamespacestd;

intmain()

{

intx,y;

x=5;//x:5,y:

y=2;//x:5,y:2

x=y;//x:2,y:2

y=3;//x:2,y:3

cout<<“x:”;

cout<<x;

cout<<“y:”;

cout<<y;

}

• ArithmeticOperators(+,-,*,/,%):

The fivearithmeticaloperations supportedbyC++are common toalmost all languagesandsomethingoneisfamiliarwithfrommathematics.

Theyare:

Operator Description

+ Addition

- Substraction

* Multiplication

/ Division

% Modulo

Themodoluoperatorgivestheremainderofadivisionoftwovalues:Forexample:

x=10%4;willgivethevalueof2tox.

• CompoundAssignment(+=,-=,*=,/=,%=,>>=,<<=,&=,^=,|=)

Compoundassignmentoperatorsmodifythecurrentvalueofavariablebyperforminganoperationonit.Forexample:

a+=x;meansa=a+x;

x-=10;meansx=x-10;

y/=x;meansy=y/x;

z*=x;meansz=z*x

• IncrementandDecrement(++,—)

These operators increase or decrease by one (1) the value stored in a variable. This isequivalentto+=1and--1respectively.

Thus++y;

y+=1;

y=y+1;

areallequivalentinitsfunctionality.Theyallincreasebyonethevalueofy.

Sodoesitmakeadifferenceifthe++isbefore(prefix)orafterthevariable(suffix)?

Yesitdoes:

Example1 Example2

z=5 z=5;

y=++z; y=z++

Herezis6,yis6 Herezis6yis5

In other words in Example 1, the value assigned to y is the value of z after beingincreased.InExample2,thevalueassignedtoyisthevalueofzbeforebeingincreased.

• Relationalandcomparisonoperators(==,!=,>,<,>=,<=)

Twoexpressions canbe comparedusing relational and equalityoperators.The result ofsuchanoperationiseithertrueorfalse.TherelationaloperatorsinC++are:

Operator Description

== Equalto

!= Notequalto

< Lessthan

> Greaterthan

<= Lessthanorequalto

>= Greaterthanorequalto

Thus:

(7==8)isfalse

5>3istrue

1!=2istrue

7>=7istrue

9<=8isfalse

Theassignmentoperator(=)isnotthesameastherelationaloperator(==).Oneassignsthevalueontherighthandsidetothevariableontheleftandtheothercompareswhethervaluesonbothsidesoftheoperatorareequal.

• Logicaloperators(!,&&,||)

Theoperator!istheC++operatorfortheBooleanoperationNOT.Thus:

!(7==7)isfalse

!(7<=5)istrue

!(9>5)isfalse

!(10<=8)istrue

The logical operators && and!! are used when evaluating two expression to obtain asinglerelationalresult.The&&isequivalenttotheBooleanlogicaloperationANDwhichhasthefollowingtruthtable.

x y x&&y

True True True

True False False

False True False

False False False

The || logical operator is equivalent to theBoolean logical operationORwhich has thefollowingtruthtable.

x y x||y

True True True

True False True

False True True

False False False

• Conditionalternaryoperator(?)

The conditional operator returns one value if the expression evaluates to true and adifferentoneiftheexpressionevaluatestofalse.Itssyntaxis:

condition?result1:result2

ThisissimilartousingtheIFcondition.Wewilldiscussthisinthecontrolschapter.

Fornow:

9==7?5:3 willgivetheresult3because9and7arenotequal

7==6+1?5:3 willgivetheresult5

Letuslookatanexample:

//conditionaloperator

#include<iostream>

usingnamespacestd;

intmain()

{

intx,y,z;

x=1;

y=5;

z=(x<y)?5:x;

cout<<z<<‘\n’;

}

Inthecodeabovetheresultwouldbe5because1islessthan5.Haditbeengreaterthanythentheresultwouldgivethevalueofx.

• CommaOperator(,)

Thecommaoperatorseparatestwoormoreexpressions.Forexample:

x=(y=5,y+7);

Thiswouldassign thevalueof5 toyand thenassigny+7 tox.Theresultwouldx=9whiley=5.

• Bitwiseoperators(&,|,^,~,<<,>>)

Bitwiseoperatorsmodifyvariablesconsidering thebitpatterns that represent thevaluestheystore.

Operator Equivalent Description

& AND BitwiseAND

| OR BitwiseinclusiveOR

^ XOR BitwiseexclusiveOR

~ NOT Unarycomplement

<< SHL Shiftbitsleft

>> SHR Shiftbitsright

• Explicittypecastingoperator

Typecastingoperatorsallowconversionofavalueofagiven type toanother type.Forexample:

intx;

floaty=3.15;

x=(int)y;

Herethexwillbe3.Anotherwayofwritingthelaststatementwouldbe:

x=int(y);

BothwaysarevalidinC++.

• Sizeofoperator

Thisoperatoracceptsoneparameter,whichcanbeeitheratypeoravariableandreturnsthesizeinbytesofthattypeorobject.

y=sizeof(char);

Hereywillgetthevalue1becausecharisatypewithasizeof1byte.Thevaluereturnedbysizeofisacompiletimeconstantsoitisalwaysdeterminedbeforeprogramexecution.

1.5.3PrecedenceofoperatorsAsingleexpressionmayhavemultipleoperators.Forexample:

z=7+8/2;

Sowheredoonestart?

Hadthisbeenwrittenas:z=7+(8/2); itwouldhavebeeneasieras thebracket itemswillbeevaluatedfirstbecauseofprecedence.7+4=11.Thetablebelowsummarizestheprecedenceorder.

Level Precedencegroup Operator Description Grouping

1 Scope :: scopequalifier Left-to-right

2 Postfix(unary) ++,—,(),[] Increment,decrement,bracket. Left-to-right

3 Prefix(unary) ++,—,|! prefixincrement/decrement,not,logicalnot Right-to-left

4 Pointer-to-member .*->* accesspointer Left-to-right

5 Arithmetic:scaling */% multiply,divide,modulo Left-to-right

6 Arithmetic:addition +- addition,subtraction Left-to-right

7 Bitwiseshift <<>> shiftleft,shiftright Left-to-right

8 Relational <><=>= comparisonoperators Left-to-right

9 Equality ==!= equality/inequality Left-to-right

10 And & bitwiseAND Left-to-right

11 Exclusiveor ^ bitwiseXOR Left-to-right

12 Inclusiveor | bitwiseOR Left-to-right

13 Conjunction && logicalAND Left-to-right

14 Disjunction || logicalOR Left-to-right

15 Assignment-levelexpressions

=*=/=%=+=-=>>=<<=&=^=|=

assignment/compoundassignmentRight-to-left

?: conditionaloperator

16 Sequencing , commaseparator Left-to-right

1.5.4ScopeofavariableWehavelookedintovariabledeclaration.Variablescanbelocalorglobal.

Variablesdeclaredinsideafunctionorblockarelocalvariables.Onlystatementsthatareinside that function or block of code can use them. Local variables are not known tofunctionsoutsidetheirown.

Globalvariablesaredefinedoutsideofall the functions,usuallyon topof theprogram.Theglobalvariableswillholdtheirvaluethroughoutthelifetimeofyourprogram.

Aglobalvariablecanbeaccessedbyanyfunction.Thatis,aglobalvariableisavailableforusethroughouttheentireprogram.

Wewilllookattwoexamples:

#include<iostream>

usingnamespacestd;

intmain()

{

intx,y;

intz;

x=10;

y=20;

z=x+y;

cout<<z;

return0;

}

#include<iostream>

usingnamespacestd;

intt;

intmain()

{

x=10;

y=20;

t=x+y;

cout<<t;

return0;

}

Inthetableontheleft,thereareonlylocalvariables.Theoutputwillbe30.

Thesecondtablehasadeclarationfortoutsidemainfunction.Themainfunctionusesittoprintthevalueoft,whichremainsat30.

C++allowsforglobalvariablesandlocalvariablestobethesame-butitisbestnottousethemthatway.

2I/O

“Thegreatestsignofsuccessforateacher…istobeabletosay,‘ThestudentsarenowworkingasifIdidnotexist.’”—MariaMontessori

2.0InputandOutputWewilllookatcinandcouthere.

Stream Description

cin standardinput

cout standardoutput

cerr standarderror–output

clog standardlogging-ouput

2.1coutcoutisusedwith<<whichisusedforinsertion.

Eachcoutlineproducesalineofwordsonaseparatelineonlyiftheendline\norendlisused.

Otherwise,thelineswillbewrittenoneaftertheotheronthesameline.

cout<<“Sentence1”;//printsSentence1

cout<<100;//prints100

cout<<x;//printsthevalueofx

Text is enclosed in double quotes as shown in previous example. Multiple insertionoperations(<<)maybechainedinasinglestatement.

cout<<“Thisis”<<“a”<<“avalidstatement”;

Whatcoutwillnotdoautomaticallyisaddlinebreaksattheend,unlessinstructedtodoso.Soifonewritesthefollowinglinesofcode:

cout<<“Thisisline1.”;

cout<<“Thisisline2.”;

Then the output will be in a single line without any line breaks in between as shownbelow:

Thisisline1.Thisisline2.

Toinsertalinebreak,anewlinecharactershouldbeincludedasfollows:

cout<<“Thisisline1.\n”;

cout<<“Thisisline2.\n”;

Nowtheoutputwillbe:

Thisisline1.

Thisisline2.

Anotherwayistouseendl.Forexample:

cout<<“Thisisline1.”<<endl;

cout<<“Thisisline2.”<<endl;

2.2cinThestandardinputbydefaultisthekeyboardandwewillnowlookatcinasthestreamobjecttoaccesswhatistobeinput.

intx;

cin>>x;

Thevalueofxcanbeentered.

Wewillusebothcinandcoutinthisexample.

//exampleofcinandcout

#include<iostream>

usingnamespacestd;

intmain()

{

floatx;

cout<<“Pleaseenteranumber:”;

cin>>x;

cout<<“Thevalueyouenteredis”<<x;

cout<<“anditsdoubleis”<<x*2<<“.\n”;

return0;

}

Here the program asks for a number of type float (ex: 3.14) and gives its double.Therefore, if we entered 5.0 then the output would be 10.0. If you are running thisprogramasastandalone,youmayseethecommandwindowclosingveryfast.Inthiscaseentercin.get();aftersecondandthirdcoutstatements.

Likecout,onecanchaincintorequestmorethanonedatainasinglelinestatement.Forexample:

cin>>x>>y;

isequivalentto:

cin>>x;

cin>>y;

Letusnowlookatanexamplewherecin,coutisusedtogetastringfromthekeyboard.When writing a console-based program in C++, cin might not effectively capture thestring.Therefore,wehavetointroduceafunctioncalledgetlineintheexamplebelow:

//cin,cout,getline

#include<iostream>

#include<string>

usingnamespacestd;

intmain()

{

stringx;

cout<<“What’syourname?”;

getline(cin,x);

cout<<“Hello”<<x<<“.\n”;

return0;

}

getlinewill call cin alongwith the stringvariablex. x stores thevaluesof thequestionbeingaskedintheprogram.

Ifyouareusingthis isaconsoleprogramyoumayhavetowritecin.get();after thelastcoutstatementtokeepthecommandwindowfromclosing.

3Theflowcontrol

“Theimportantthinginlifeisnotthetriumphbutthestruggle.”—PierredeCoubertin

3.0StatementsBynow,youare familiarwith thegeneral layoutofaC++program.Statementsare theindividualinstructionsofaprogramforexample-variabledeclarationandexpressions.

In a C++ program, a statement can be a simple one line statement terminated by asemicolon(;)oracompoundstatement.

Compound statement is a group of statements each terminated by a semicolon (;) andgroupedtogetherinablockenclosedincurlybrackets{}asfollows:

{

floatx;

cout<<“Pleaseenteranumber:”;

cin>>x;

cout<<“Thevalueyouenteredis”<<x;

cout<<“anditsdoubleis”<<x*2<<“.\n”;

return0;

}

3.1IfandelseThe if keyword is found in several programming languages. It is used to execute astatementorblockifandonlyifaconditionisfulfilled.

if(condition)statement

if(x<100)

cout<<“xislessthan100”;

If thecondition isnotmet,nothing isprintedout. If therearemultiple statements tobeexecuted when the condition is fulfilled, then these statements should be enclosed inbracketsformingablock.

Forexample:

if(x<100)

{

cout<<“xislessthan100”;

cout<<x;

}

Thecodeabovecanbemadeonasinglelineasfollows:

if(x<100)

{cout<<“xislessthan100”;cout<<x;}

Generally,beginnersaremorecomfortablewithwritinga statementon itsown lineandthis can increase the readability of the code. The elsekeyword is used to introduce analternativestatement.Thesyntaxis:

If(condition)statement1elsestatement2

Forexample:

if(y==10)

cout<<“yisequalto10”;

else

cout<<“yisnot10”;

Soherethestatementyisequalto10willprintif(y==10)otherwisethestatementyisnot10willprint.

3.2LoopsLoops are known as iteration statements. That is because one uses loops to repeat astatement a certain number of times while a condition is fulfilled. The loop uses thekeywords-while,doandfor.

Awhileloophasthefollowingsyntax:

while(condition)statement

//exampleofwhileloop

#include<iostream>

usingnamespacestd;

intmain()

{

inty=3;

while(x>0){

cout<<y<<“,”;

—y;

}

cout<<“Endofloop\n”;

}

Theoutputofthiscodewouldbe3,2,1,EndofLoop.Tocontrolthecommandwindowuse cin.get(); after the last cout if necessary. If after any executionof the statement theconditionbecomefalsethentheloopendsandtheprogramcontinuesrightaftertheloop.

Inthiscase,theconditionwasxhadtobegreaterthanzero.Sowhenitcountsfromfivedownwardsoneata timedueto(—x)itwillstoptheloopafteronewhenxwillnotbegreater than zero. Then it jumps the loop and goes to the next available line in theprogram,whichinthiscaseisthecoutstatement.Thus,itwillprint“Endofloop”.

Inallloops,theremustbeanexitpoint.Otherwise,itwillgoonforever.

do-whileloop

Thesyntaxforthistypeofloopis:

dostatementwhile(condition);

The condition is evaluated after the statement has been executed. Thus, at least oneexecutionofthestatementisdoneeveniftheconditionisnotfulfilled.Forexample:

//do-whileloop

#include<iostream>

#include<string>

usingnamespacestd;

intmain()

{

stringx;

do{

cout<<“Enteryourusername:”;

getline(cin,x);

cout<<“Youentered:”<<x<<‘\n’;

}while(x!=“student”);

}

Hereletuslookattheoutputbasedontheinput:

Enteryourusername:hello

Youentered:hello

Enteryourusername:student

Youentered:student

Soatleastonetimetheloophastobeexecutedevenifoneentersstudenttoexitthelooplikeinthiscase.Thisfeatureofdoisthereasonwhyonemayselectitoverwhile.

TheforloopThesyntaxforthistypeofloopisasfollows:

for(initialization;condition;increase/decrease)statement;

Likethewhileloopthistypeoflooprepeatsstatementswhileconditionistrue.Inadditiontheforloopprovidesaninitializationandincrease/decrease(change)expressionexecutedbeforetheloopbeginsforthefirsttimeandaftereachiteration.

for(intx=5;x>0;x—)

xstartsatfiveandisdecrementedbyoneeachtimeaslongasthevalueofxdoesnotgobelowone.

The three fields in a for loop are optional. They can be left empty, but the semicoloncannotbeomitted.Forexample:

for (;x<5;) is a loopwith an initializationor an increase and is equivalent to awhileloop.

for (;x<5;++x) is a loopwith increase but no initialization. In this case the variablemighthavebeeninitializedalreadyelsewhereintheprogram.

for(x=5;;++x)isaloopwithnocondition.Thus,itisthesameasaloopwithtrueascondition.Thusresultinganinfinitelooporendlessloop.

#include<iostream>

usingnamespacestd;

intmain()

{

for(intn=5;n>0;n—){

cout<<n<<“,”;

}

cout<<“Endofline\n”;}}

Itproducesthesameresult-5,4,3,2,1,Endofline.

3.3JumpstatementsJump statements allow altering the flow of a program by performing jumps to specificlocations.There are three typesof jump statements.Theyarebreak, continue andgoto.Letuslookatanexample:

Thecontinuestatement

The continue statement causes the program to skip the rest of the loop in the currentiterationisiftheendoftheblockhasbeenreachedcausingittojumptothestartofthefollowingiteration.Thenumber3isskipped.

for(intx=5;x>0;x—){

if(x==3)continue;

cout<<x<<“,”;

}

cout<<“Numberskipped\n”;}

ThegotostatementGotoallowsanabsolutejumptoanotherpointintheprogram.Itusesalabelwitha:

#include<iostream>

usingnamespacestd;

intmain()

{

inta=10;

LOOP:do

{

if(a==15)

{

a=a+1;

gotoLOOP;

}

cout<<“valueofa:”<<a<<endl;

a=a+1;

}while(a<20);

return0;

}

Heretheoutputwouldbealistofnumbersfrom10to19withoutthenumber15.Hereweseeadowhileloop.Thenumbercountsfrom10to19butskips15.

3.4Switch

switch(expression)

{

caseconstant1:

groupofstatements-1;

break;

caseconstant2:

groupofstatements-2;

break;

.

default:

defaultgroupofstatements

}

Switchevaluatesexpressionandchecksifitisequivalenttoconstant1.Ifitis,itexecutesthegroupofstatements-1untilitreachesthebreakstatement.Atthebreakstatement,theprogramjumpstotheendoftheentireswitchstatement–theclosingbrace.

If expression is not equal to constant1, it then checks against constant2 and if equalexecutesthegroupofstatements-2untilabreakisfoundandthenjumpstotheendoftheswitchstatement.

Finally, if the value of the expression did notmatch any of the constants the programexecutesthestatementsincludedafterthedefault:labelifitexists.

Letuslookatanexample:

#include<iostream>

usingnamespacestd;

intmain()

{

charx=‘C’;

switch(x)

{

case‘A’:

cout<<“Sedan”<<endl;

break;

case‘B’:

cout<<“MiniVan”<<endl;

break;

case‘C’:

cout<<“Truck”<<endl;

break;

default:

cout<<“Invalidentry”<<endl;

}

cout<<“Yourselectionis”<<x<<endl;

return0;

}

Theoutputwillbe:Truck

YourselectionisC

IfanythingotherthanA,B,Cisenteredthedefaultmessagewillbedisplayedwhichisinvalidentry.

4Functions

“Everytruthhasfourcorners:asateacherIgiveyouonecorner,anditisforyoutofindtheotherthree.”—Confucius

4.0DefinitionofafunctionAfunctionisasetofstatementsthattogetherperformatask.

Afunctionhasafunction’sname,returntype,andparameters.TherecanbemorethanonefunctiondeclarationinaC++program.

Thegeneralsyntaxofafunctionisasfollows:

return_typefunction_name(parameterlist)

{

body

}

• ReturnType:Thereturn_typeisthedatatypeofthevaluethefunctionreturns.Iffunctionsdonoreturn,avaluethereturn_typeissettovoid.

• FunctionName:Thisistheactualnameofthefunction.Thefunctionnameandtheparameterlisttogetherconstitutethefunctionsignature.

• Parameters:When a function is invoked, you pass a value to the parameter.Thisvalueisreferredtoasactualparameterorargument.Theparameterlistreferstothetype,order,andnumberoftheparametersofafunction.Afunctionmaycontainnoparameters.

• FunctionBody: The function body contains a collection of statements that definewhatthefunctiondoes.

Letuslookatanexample:

//functionexample

#include<iostream>

usingnamespacestd;

intmultiply(intx,inty)

{

intz;

z=x*y;

returnz;

}

intmain()

{

intw;

w=multiply(5,2);

cout<<“Theresultis”<<w;

}

Here is a function,multiply that has been defined outside themain function. Inside themainfunctionwehavecalledthefunctionbyitsnamemultiplyandpassedtoittwovalues5and2.Thevalueswillbeassignedtox=5andy=2.Theresultwillbe10.

Remember the function is called frommain.At this point, activity is transferred to thefunction and once the function has been executed, control returns to the point inmainwherethefunctionwascalled.

Ifonelooksatthemultiplyfunctionitreturnsavaluezbacktomainwhichisofthesametypeasw.Thevalueofwwillbeprintedwith thevalueofz computed in the functionblock.

Afunctioncanbecalledseveraltimesinsideamainfunction.

4.1FunctionsthatdonotreturnavalueLetuslookatthefollowingexample:

//voidfunctionexample

#include<iostream>

usingnamespacestd;

voidpmessage()

{

cout<<“HelloIamfunction!”;

}

intmain()

{

pmessage();

}

Inthisexample,wearecallingafunctionfrommain.ItwillprintthemessageHelloIamafunction!

Unlikethepreviousexampleinsection,4.0novaluesaretransferredtothefunctionandnonearecomputedandreturned.

Whilemostfunctionsusethecallbyvaluemethodasinthepreviousexample,theuseof

voidtermindefiningfunctionpmessagetellsthatthefunctiondoesnotreturnavalue.

Furthernotetherearenoparametersinthebracketofthepmessagefunction.Theabsenceof theseparametersmeans that the function isnotgoing to receiveanyvalues from themainfunction.

Iftheexecutionofmainendsnormallywithoutencounteringareturn(return0;)statementthecompilerassumesthefunction,endswithanimplicitreturnstatement.

Allotherfunctionswithareturntypeshallendwithaproperreturnstatementthatincludesareturnvalue.

Therecanbemanyfunctions inaC++programbut themain()functionmustalwaysbethereirrespectiveofhowcomplicatedtheprogramis.

4.2Defaultvaluesforparameters

When you define a function, you can specify a default value for each of the lastparameters. This value is used if the corresponding argument is left blank when thefunctioniscalled.

Letuslookatthefollowingexample:

//defaultvaluesinfunctions

#include<iostream>

usingnamespacestd;

intdivide(intx,inty=5)

{

intz;

z=x/y;

return(z);

}

intmain()

{

cout<<divide(10)<<‘\n’;

cout<<divide(30,6)<<‘\n’;

return0;

}

Hereinthefirstcalldivide(10)thevaluestransferredtoxis10andsincethereisnothingelsetransferred10willbedividedbyy=5resultingintheanswer2.

In the secondcall divide (30, 6), functionparametersxwill take thevalueof30 andywhosevalueinthefunctionis5willgetthevalue6.Thus,theresultwillbe5.

5Arrays

“Readnottocontradictandconfute,nortobelieveandtakeforgranted…buttoweighandconsider.”—FrancisBacon

5.0WhatareArraysAnarray,storesafixed-sizesequentialcollectionofelementsofthesametype.Anarrayisused to store a collection of data, but it is oftenmore useful to think of an array as acollectionofvariablesofthesametype.

Allarraysconsistofcontiguousmemorylocations.Thelowestaddresscorrespondstothefirstelementandthehighestaddresstothelastelement.Theindexvalue0representthelowestaddress.

5.1SimpleArraysdoubleamount[5]={1000,800,900,700,600}

Thenumberoftheelementsofthecurlybracket{}mustnotbemorethanthenumberin[]brackets.Thisisasingleorone-dimensionalarray.

Ifthenumberin[]bracketsismissingthenanarrayofjustenoughsizetoaccommodatetheelementswillbecreated.

Ifwewriteamount[4]=600thiswouldmeanthatthe5thplaceor4th indexonthearraywillhavethevalueof600.

0 1 2 3 4

1000 800 900 700 600

AmountSoasshown5cellsnumbered0through4.

Thefifthpositionrepresentedbyindex4willholdthevalueof600inaone-dimensionalarray.

5.2AccessinganelementofanarrayStoringvalues isanarray isonlygoodifwecanaccess them.Toaccesselementsofanarraywecanusealoopsuchasa-forloop.

//arraysexample

#include<iostream>

usingnamespacestd;

intamount[]={16,2,77,40,12071};

intn;

intv=0;

intmain()

{

for(n=0;n<5;++n)

{

v=v+amount[n];

}

cout<<v;

return0;

}

Thiswillgivethesumofthefivenumbersinthearray,whichwillbe12206.

5.3Multi-dimensionalArraysTheformatforamultidimensionalarrayisasfollows:

typename[size1][size2]…[sizen];

Thesimplestformofthemultidimensionalarrayisthetwo-dimensionalarray.Todeclareatwo-dimensionalintegerarrayofsizex,y,youwouldwritesomethingasfollows:

typearrayname[x][y];

WheretypecanbeanyvalidC++datatypeandarraynamewillbeavalidC++identifier.

inta[2][3]isanarraywithtworowsandthreecolumns.Forexample:

inta[2][3]={

{0,1,2},

{3,4,5}

};

Sohere,therow1hastheindex0orinsimplewords,wecountrowsstartingwith0andnot1.Thustherownumberfortheabovearrayis0&1andcolumnnumbersare0…2.

Column0 Column1 Column2

Row0 0 1 2

Row1 3 4 5

Nowweaccesstheelementsofamulti-dimensionalarrayinthesamemanneraswedidforasinglearraybyusingaloop.Letusconsiderafourrowtwocolumnarraydefinedby

a[4][2].Letusassigntoitthefollowingvalues:

a[4][2]={{0,0},{1,2},{2,4},{3,6}}

Toprintoutthevaluesofthisandsimilararrayswewillusethe‘for’loop.Thekeyloopwouldbe:

for(inti=0;i<4;i++)

for(intj=0;j<2;j++)

{

cout<<“a[”<<i<<“][”<<j<<“]:”;

cout<<a[i][j]<<endl;

}

Herewehavei<4becauseweknowthecolumnsarenumbered0through3.

Hereisthefullcode:

#include<iostream>

usingnamespacestd;

intmain()

{

//anarraywith3rowsand2columns.

inta[3][2]={{0,0},{1,2},{2,4}};

//outputeacharrayelement’svalue

for(inti=0;i<3;i++)

for(intj=0;j<2;j++)

{

cout<<“a[”<<i<<“][”<<j<<“]:”;

cout<<a[i][j]<<endl;

}

return0;

}

Theoutputwouldbesimilartothis:

a[0][0]:0

a[0][1]:0

a[1][0]:1

a[1][1]:2

a[2][0]:2

a[2][1]:4

6Pointers

“Teachingstudentstocountisfine,butteachingthemwhatcountsisbest.”

—BobTalber

6.0WhatarePointersApointerisavariablewhosevalueistheaddressofanothervariable.Letuslookatthefollowingexample:

#include<iostream>

usingnamespacestd;

intmain()

{

intx;

cout<<“Addressofxvariable:”;

cout<<&x<<endl;

return0;

}

Theoutputofthiscodewillbesimilartothis:

Addressofxvariable:0031FDE0

Addressofyvariable:0031FDCC

Whatweseeaboveisthememorylocationforvariablesx.Noticethatthe‘&’isusedtogivethememorylocation.

Thisvaluewillvaryandmaybedifferentonyourcomputer.However,whatisimportanttounderstandtokeepinmindisthattheyarememoryaddresses.

Wecandefinepointersbyfirstindicatingitstypeasfollows:

int*x;

float*y;

double*p;

char*w

Thesepointerswillpointtoaninteger,float,doubleandcharrespectively.

Wecanstorethevalueofvariableinapointerandtheaddressofthevariable.Letuslook

atthefollowingexample:

#include<iostream>

usingnamespacestd;

intmain()

{

intx=10;

int*ip;//pointervariable

ip=&x;//storeaddressofvarinpointervariable

cout<<“Valueofxvariable:”;

cout<<x<<endl;

cout<<“Addressstoredinipvariable:”;

cout<<ip<<endl;

cout<<“Valueof*ipvariable:”;

cout<<*ip<<endl;

return0;

}

Theoutputwillbesimilartothis:

Valueofxvariable:10

Addressstoredinipvariable:002BFC90

Valueof*ipvariable:10

6.1PointerconceptsLetuslookatsomepointerconcepts:

• Nullpointers

#include<iostream>

usingnamespacestd;

intmain()

{

int*p=NULL;

cout<<“Thevalueofpis”<<p;

return0;

}

ThisisanexampleofaNULLpointer.Theoutputofthiscodeis:

Thevalueofpis0

• PointerArithmetic

Apointerisanaddress,whichisanumericvalue;therefore,youcanperformarithmeticoperationsonapointerjustasyoucananumericvalue.Fourarithmeticoperatorsthatcanbeusedonpointers:++,—,+,and–.

For the following example, we will define an array y of three elements. It is a singledimensionarray.Wewilluseapointery topoint to thearrayy.Letusassumeboth thepointerandthearrayareoftypeinteger.

Wewill thena looptogothrougheachelementof thearrayyandprintout itsmemoryaddressandvalue.Wepreferusingapointer intheprograminsteadofanarraybecausethe variable pointer can be incremented, unlike the array name, which cannot beincrementedbecauseitisaconstantpointer.

Aforloopisusedinthisexampletogothrougheachelementofthearrayyaswasdoneinthechapteronarrays.

Letusthelookattheexample:

#include<iostream>

usingnamespacestd;

constintx=3;

intmain()

{

inty[x]={100,200,300};

int*p;

//letushavearrayaddressinpointer.

p=y;

for(inti=0;i<x;i++)

{

cout<<“Addressofy[”<<i<<“]=”;

cout<<p<<endl;

cout<<“Valueofy[”<<i<<“]=”;

cout<<*p<<endl;

p++;

}

return0;

}

Theexpectedoutputofthecodeissimilarto:

Addressofy[0]=0031FD88

Valueofy[0]=100

Addressofy[1]=0031FD8C

Valueofy[1]=200

Addressofy[2]=0031FD90

Valueofy[2]=300

• Pointerversusarrays

Pointersandarraysarestronglyrelated.Apointerthatpointstothebeginningofanarraycanaccessthatarraybyusingeitherpointerarithmeticorarray-styleindexing.Letuslookatthefollowing:

#include<iostream>

usingnamespacestd;

constintx=3;

intmain()

{

inty[x]={100,200,300};

int*p;

//letushavearrayaddressinpointer.

p=y;

for(inti=0;i<x;i++)

{

cout<<“Addressofy[”<<i<<“]=”;

cout<<p<<endl;

cout<<“Valueofy[”<<i<<“]=”;

cout<<*p<<endl;

//pointtothenextlocation

p++;

}

return0;

}

Theoutputoftheprogramwouldbesimilarto:

Addressofy[0]=004DF750

Valueofy[0]=100

Addressofy[1]=004DF754

Valueofy[1]=200

Addressofy[2]=004DF758

Valueofy[2]=300

Ifweusethearraynameyandwritethisy++thatissyntacticallywrong.

7Strings

“Educationisnottoreformstudentsoramusethemortomakethemexperttechnicians.Itistounsettletheirminds,widentheirhorizons,inflametheirintellects,teachthemtothinkstraight,ifpossible.”—RobertM.Hutchins

7.0CharacterStringWearefamiliarwiththechardatatype.Wealsohavegonethrougharraysandpointersinpreviouschapters.

LetusthereforelookatthefollowingcodewherewedefineacharacterarraytoprintthewordYes.

#include<iostream>

usingnamespacestd;

intmain()

{

charx[3]={‘Y’,‘e’,‘s’,‘\0’};

cout<<x<<endl;

return0;

}

Theexpectedoutputofthisprogramis:

Yes

Here thedeclarationcharx [3] isaone-dimensionalarrayofcharacters terminatedbyanullcharacter‘\0’.TheC++compilerautomaticallyplacesthe‘\0’attheendofthestringwhenitinitializesthearray.

7.1StringFunctionsSomeofthecommonstringfunctionsinC++are:

No FunctionName Description

1 strcpy(s1,s2) Copiesstrings2intostrings1

2 strcat(s1,s2) Concatenatesstrings2ontotheendofstring1

3 strlen(s1) Returnsthelengthofstrings1

4 strcmp(s1,s2) Returns0ifs1ands2arethesame;lessthan0ifs1<s2;greaterthan0ifs1>s2.

include<iostream>

#include<string>

usingnamespacestd;

intmain()

{

charx[10]=“Hello”;

chary[10]=“World”;

strcat(x,y);

cout<<“strcat(x,y):”<<x<<endl;

return0;}

TheoutputwillbeHelloWorld.Justkeepaneyeonthesizeofthearraysxandy.

8References

“Education…ispainful,continualanddifficultworktobedoneinkindness,bywatching,bywarning,…

bypraise,butaboveall—byexample.”—JohnRuskin

8.0WhatareReferencesA reference variable is an alias, that is, another name for an already existing variable.TherecannotbeNULLreferencesandreferencesmustbe tovalidvariables.Referencesinitializedtoanobjectcannotrefertoanotherobject.Referencesmustbeinitializedwhentheyarecreated.

include<iostream>

usingnamespacestd;

intmain()

{

intx;

//declarereferencevariable

int&y=x;

x=10;

cout<<“Valueofx:”<<x<<endl;

cout<<“Valueofyreference:”<<y<<endl;

return0;}

Expectedoutputofthisexampleis:

Valueofx:10

Valueofyreference:10

9File

“TellmeandIforget.TeachmeandIremember.InvolvemeandIlearn.”—BenjaminFranklin

9.0InputandoutputwithfilesSofar,wehaveusedcinandcoutasinputandoutputfortheprogramswehavewritten.Nowlookuslookathowtodealwithexternalfiles.C++providesthefollowingclassestoachievethis.Itrequirestheuseofanewadditionalheaderotherthaniostream.Theheaderisfstream.

Stream Description

ofstream Towritetofiles

ifstream Toreadfromfiles

fstream Toreadandwritefromandintofiles

Letuslookatanexample:

//basicfileoperations

#include<iostream>

#include<fstream>

usingnamespacestd;

intmain(){

ofstreammyfile;

myfile.open(“first.txt”);

myfile<<“Hello!Iamwritingtoafile.\n”;

myfile.close();

return0;}

Thiswritestoatextfileknownasfirst.txt.ThewordsHello!Iamwritingtoafile.Ifthefilefirst.txtdoesnotexist itwillcreatedaslongaspermissionsonyourcomputerallowforit.Otherwise,createthefilefirstnotingthedirectoryofC++compiler.

9.1OpeningafileInordertoopenafilewithastreamobjectweusethefollowingsyntax:

open(filename,mode);

Wherefilenameisastringrepresentingthenameofthefiletobeopened,andmodeisanoptionalparameterwithacombinationofthefollowingflags:

Flags Description

ios::in Openforinputoperations.

ios::out Openforoutputoperations.

ios::binary Openinbinarymode.

ios::ate Settheinitialpositionattheendofthefile.Ifthisflagisnotset,theinitialpositionisthebeginningofthefile.

ios::app Alloutputoperationsareperformedattheendofthefile,appendingthecontenttothecurrentcontentofthefile.

ios::trunc Ifthefileisopenedforoutputoperationsanditalreadyexisted,itspreviouscontentisdeletedandreplacedbythenewone.

All these flags can be combined using the bitwise operatorOR (|). For example, ifwewanttoopenthefilefirst.bininbinarymodetoadddatawecoulddoitbythefollowingcalltomemberfunctionopen:

ofstreammyfile;

myfile.open(“first.bin”,ios::out|ios::app|ios::binary);

Eachoftheopenmemberfunctionsofclassesofstream,ifstreamandfstreamhasadefaultmodethatisusedifthefileisopenedwithoutasecondargument:

Stream DefaultMode

ofstream ios::out

ifstream ios::in

Fstream ios::in|ios::out

Tocheckifafilestreamwassuccessfulinopeningafile,onecanusetheis_openmember.Thesyntaxwouldlooklikethis:

if(first.isopen()){statements}

9.2ClosingafileWhenwearefinishedwithwritingtoafileorreadingfromitwehavetoclosethefile.

Thesyntaxforthatisasfollows:

first.close();

9.3TextFilesTextfilesarethosewheretheios::binaryflagisnotincludedintheiropeningmode.Theyhavetheextentions.dat,.txt,.csvetc.

#include<iostream>

#include<fstream>

usingnamespacestd;

intmain(){

ofstreammyfile(“first.txt”);

if(myfile.is_open())

{

myfile<<“Thisisaline.\n”;

myfile<<“Thisisanotherline.\n”;

myfile.close();

}elsecout<<“Unabletoopenfile”;

return0;}}

//readingatextfile

#include<iostream>

#include<fstream>

#include<string>

usingnamespacestd;

intmain(){

stringline;

ifstreammyfile(“first.txt”);

if(myfile.is_open())

{

while(getline(myfile,line))

{

cout<<line<<‘\n’;

}

myfile.close();

}

elsecout<<“Unabletoopenfile”;

return0;}}}

Thisprogramallowsonetoreadfromatextfile.

10StorageClasses

“Alwaystoseethegeneralintheparticularistheveryfoundationofgenius.”—ArthurSchopenhauer

10.0TypesofstorageclassesLetuslookatfivestorageclasses:

• auto• register• static• extern• mutable

Theautostorageclassisthedefaultstorageclassforalllocalvariables.

{

inty;

autointx;

}

Theautostorageclasscanonlybeusedwithinfunctions.TheregisterstorageclassisusedtodefinelocalvariablesthatshouldbestoredintheregisterratherthanRAM.

{

registerintx;

}

Theregistershouldonlybeusedforvariablesthatrequirequickaccesssuchascounters.

Thestaticstorageclassinstructsthecompilertokeepalocalvariableinexistenceduringthe lifetimeof theprograminsteadofcreatinganddestroying iteach timeitcomes intoandgoesoutofscope.

Therefore, making local variables static allows them to maintain their values betweenfunctioncalls.Thestaticmodifiermaybeappliedtoglobalvariables

#include<iostream>

usingnamepacestd;

voidy(void);

staticintcount=5;/*Globalvariable*/

intmain()

{

while(count—)

{

y();

}

return0;

}

//Functiondefinition

voidy(void)

{

staticintx=0;//localstaticvariable

x++;

std::cout<<“xis”<<x;

std::cout<<“andcountis”<<count<<std::endl;

}

Theexpectedoutputfortheaboveexampleisasfollows:

xis1andcountis4

xis2andcountis3

xis3andcountis3

xis4andcountis1

xis5andcountis0

Theexternstorage class gives a reference of a global variable that is visible to all theprogramfiles.Whenthisclassisusedvariablescannotbeinitialized.

#include<iostream>

intcount;

externvoidw();

main()

{

count=5;

w();

}

Letusassumethecodeaboveisinafilecallfirst.cpp.Letalsoassumethereisasecondfilecalledsecond.cpp

#include<iostream>

Externintcount;

voidw(void)

{

std::cout<<“Countis”<<count<<std::endl;

}

Sincethefunctionwasdeclared,withexternitisavailabletothesecondfileanditisabletoprintthevalueofcountas5.Themutablemembercanbemodifiedbyaconstmemberfunction.

11Classes

“Therearetwokindsofteachers:thekindthatfillsyouwithsomuchquailshotthatyoucan’tmove,andthekindthatjustgivesyoualittleprodbehindandyou

jumptotheskies.”—RobertFrost

11.0BuildingclassesClasses form one of the fundamental features that enableC++ to be an object orientedlanguage.

Aclassdefinitionstartswiththekeywordclassfollowedbytheclassname;andtheclassbody,enclosedbyapairofcurlybraces.Eitherasemicolonoralistofdeclarationsmustfollowaclassdefinition.

Letuslookatanexampleofaclass.

classCar

{

public:

doublelength//Lengthofthecar

doublewidth;//Widthofthecar

doubleweight;//Weightofthecar

doubleengine;//Enginesize

};

We have defined a class known as car with a few features attributed to the car. Thekeywordpublicdeterminestheaccessattributesofthemembersoftheclassthatfollowit.Apublicmembercanbeaccessedfromoutsidetheclassanywherewithinthescopeoftheclassobject.

Nowletuslookatobjects.

Letusassumetherearetwocars–car1andcar2.Wewilldeclareitasfollows:

Carcar1

Carcar2

Bothobjectswillnowhaveacopyof thedatamembersof theclassknownasCar.Forexample:

#include<iostream>

usingnamespacestd;

classCar

{

public:

doublelength;//Lengthofthecar

doublewidth;//Widthofthecar

doubleweight;//Weightofthecar

doubleengine;//Enginesize

};

intmain()

{

Carcar1;//Declarecar1oftypeCar

Carcar2;//Declarecar2oftypeCar

car1.weight=1500;

car1.engine=1400;

car2.weight=2000;

car2.engine=1800;

cout<<“Weightofcar1:”<<car1.weight<<endl;

cout<<“Weightofcar2:”<<car2.weight<<endl;

return0;

}

Theoutputofthecodeabovewouldbe:

Weightofcar1:1500

Weightofcar2:2000

11.1Classconcepts• Classmemberfunction

Amemberfunctionofaclassisafunctionthathasitsdefinitionwithintheclassdefinitionlikeanyothervariable.Itoperatesonanyobjectoftheclassofwhichitisamember,andhasaccesstoallthemembersofaclassforthatobject.Letuslookatanexample:

classMarks

{

public:

doubleprelim;//narksinfirstexam

doublemidterm;//marksinsecondexam

doublefinal;//marksinfinalexam

doublegetfinal(void)

{

return(0.3*prelim)+(0.3*midterm)+(0.4*final);

}

};

Herethefunctiongetfinal()hasbeendefinedwithintheclass.Ifthefunctionisnotdefinedwithintheclassthenusescoperesolutionoperator,::,asfollows:

• Classmodifiers

DatahidingisoneoftheimportantfeaturesofObjectOrientedProgramming(OOP).Theaccess labels - public, private, and protected, specify the access restriction to the classmembers.

Apublicmemberisaccessiblefromanywhereoutsidetheclassbutwithinaprogram.Aprivatemembervariableorfunctioncannotbeaccessed,fromoutsidetheclass.Onlytheclassandfriendfunctionscanaccessprivatemembers.Letuslookatthis:

#include<iostream>

usingnamespacestd;

classCar

{

public:

doublelength;

voidsetw(doublew);

doublegetw(void);

private:

doubleweight;

};

//Memberfunctionsdefinitions

doubleCar::getw(void)

{

returnweight;

}

voidCar::setw(doublew)

{

weight=w;

}

intmain()

{

Carcar1;

car1.length=1100;//OK:becauselengthispublic

cout<<“Lengthofcar:”<<car1.length<<endl;

//car1.weight=1500;//Error:becauseweightisprivate

car1.setw(1500);//Usememberfunctiontosetit.

cout<<“Weightofcar:”<<car1.getw()<<endl;

return0;}

Herethedeclarationofweightasbeingprivateresultedincar1,whichisanobjectofCarfrombeingabletoaccesstheweightdirectly.Theoutputofthisprogramwouldbe:

Lengthofcar:1100

Weightofcar:1500

Aprotectedmembervariableorfunctionisverysimilartoaprivatemember.Theycanbeaccessedinchildclasses,whicharecalledderivedclasses.

#include<iostream>

usingnamespacestd;

classCar

{

protected:

doubleweight;

};

classSmallcar:Car//Smallcaristhederivedclass.

{

public:

voidsetSmallw(doublewid);

doublegetSmallw(void);

};

doubleSmallcar::getSmallw(void)

{

returnweight;

}

voidSmallcar::setSmallw(doublew)

{

weight=w;

}

intmain()

{

Smallcarcar1;

car1.setSmallw(1500);

cout<<“Weightofcar:“<<car1.getSmallw()<<endl;

return0;

}

Theoutputoftheprogramwouldbe:

Weightofcar:1500

• Constuctors

Aclassconstructorisaspecialmemberfunctionofaclassthatisexecutedwheneverwecreatenewobjectsofthatclass.

Aconstructorwillhaveexactsamenameastheclassanditdoesnothaveanyreturntypeatall,notevenvoid.Letuslookatthefollowing:

#include<iostream>

usingnamespacestd;

classCar

{

public:

voidsetw(doublew);

doublegetw(void);

Car();//Thisistheconstructor

private:

doubleweight;

};

//Memberfunctionsdefinitionsincludingconstructor

Car::Car(void)

{

cout<<“Pleasewait!Answerisontheway”<<endl;

}

doubleCar::getw(void)

{

returnweight;

}

voidCar::setw(doublew)

{

weight=w;

}

intmain()

{

Carcar1;

car1.setw(1500);

cout<<“Weightofcar:”<<car1.getw()<<endl;

return0;}

Heretheoutputwouldbetheweightofthecar.Thedifferenceis:

Pleasewait!Answerisontheway

Weightofcar:1500

• Destructors

#include<iostream>

usingnamespacestd;

classCar

{

public:

voidsetw(doublew);

doublegetw(void);

Car();//Thisistheconstructordeclaration

~Car();//Thisisthedestructor:declaration

private:

doubleweight;

};

//Memberfunctionsdefinitionsincludingconstructor

Car::Car(void)

{

cout<<“Objectisbeingcreated”<<endl;

}

Car::~Car(void)

{

cout<<“Objectisbeingdeleted”<<endl;

}

doubleCar::getw(void)

{

returnweight;

}

voidCar::setw(doublew)

{

weight=w;

}

intmain()

{

Carcar1;

car1.setw(1500);

cout<<“Weightofthevehicle:”<<car1.getw()<<endl;

return0;

}

Theexpectedoutputis:

Objectisbeingdeleted

Theweightofthevehicle:1500

12Inheritance

“Staycommittedtoyourdecisions;butstayflexibleinyourapproach.”—TonyRobbins

12.0TheconceptofInheritanceAclasscanbederivedfrommore thanoneclasses,whichmeans itcan inheritdataandfunctionsfrommultiplebaseclasses.Todefineaderivedclass,weuseaclassderivationlisttospecifythebaseclass(

Letus lookat anexampleby firstwritingabaseclass.Here thebaseclass thatwearegoingtodefineiscalledvehicle.Thevehiclehascertainpropertiessuchaslength,width,weight,engineetc.

Wewillthencreateaderivedclasscalledcar.Asacarisavehicleanditwillinheritthepropertiesofthebaseclassthatisvehicle.

Theexampleisasfollows:

#include<iostream>

usingnamespacestd;

//Baseclass

classvehicle

{

public:

voidsetengine(doublee)

{

engine=e;

}

public:doublegetengine()

{

return(engine);

}

protected:

doubleweight;

doubleengine;

};

//Derivedclass

classcar:publicvehicle

{

};

intmain(void)

{

vehiclecar;

car.setengine(1500);

cout<<“Engine:”<<car.getengine()<<endl;

return0;

}

The output is 1500. Inheritance is a key element as to why C++ is an object-orientedlanguage.

12.1SomeOOP’stermsPolymorphismisaterminC++.Thisfeaturemeansthatthereareahierarchyofclasses,whicharerelatedtoeachotherthroughinheritance.Polymorphismcanresultinacalltoafunction being replied to by another function depending on the object that called thefunction.

Placingavirtualfunctioninthebaseclasswilldealwithpolymorphism.

Dataabstractionmeansshowingonlynecessary informationandhidinganybackgrounddetails.Encapsulation isa feature thatkeepsdataand functions thatoperateon thedatasaferfromexternalmisuse.

Any C++ program, which has public and private members, is an example of dataencapsulationanddataabstraction.Forexample:

classCar

{

public:

doublegetw(void)

{

returnweight;

}

private:

doubleweight;

}

13Exceptions

“Alwaystoseethegeneralintheparticularistheveryfoundationofgenius.”—ArthurSchopenhauer

13.0ErrorhandlingAnexceptionisdefinedasaproblemthathappenswhenaprogramisrunning.Exceptionsprovideaway to transfercontrol fromonepartofaprogramtoanother.C++exceptionhandlingisbuiltuponthreekeywords:try,catch,andthrow.

try

{

//protectedcode

}catch(ExceptionNamea1)

{

//catchblock

}catch(ExceptionNamea2)

{

//catchblock

}catch(ExceptionNamean)

{

//catchblock

}

Exceptions can be introduced anywhere a bunch of statements are being executed. Forexample:

#include<iostream>

usingnamespacestd;

doubledivision(intv,intw)

{

if(w==0)

{

throw“Divisionbyzero”;

}

return(v/w);

}

intmain()

{

intx=10;

inty=0;

doublez=0;

try{

z=division(x,y);

cout<<z<<endl;

}catch(constchar*msg){

cerr<<msg<<endl;

}

return0;

}

14Conclusion

TheC++languageisaveryversatileprogrammingtool.

ThepreviouschaptersconcentratedoncreatingthebasicbuildingblocksofastandaloneC++ program. Chapters 11 and 12 introduced topics important to object orientedprogramming. As you go on tomore advanced programming youwill encounter otherOOP’sconceptssuchaspolymorphism,encapsulation,dataabstractionanddatahidingindetail.

Interestinglyintheexampleswehavedone,someoftheseconceptsarealreadypresent.

From thispoint, onecould takeamoreadvanced lookatC++programmingkeeping inmindthatwideusageofthislanguage.

Ifyouneed,thezipfileofalltheprogramsinthechaptersthatwehavedoneorupdatesonthissubjectandsubsequentandrelatedtopicsvisithttp://beam.to/fjtbooks