You are on page 1of 15

OOPSUsingC++

Unit1

Unit1
Structure 1.1 Introduction

IntroductiontoOOPandC++

1.2 EvolutionofProgrammingmethodologies SelfAssessmentQuestions 1.3 IntroductiontoOOPanditsbasicfeatures SelfAssessmentQuestions 1.4 BasiccomponentsofaC++Programandprogramstructure SelfAssessmentQuestions 1.5 CompilingandExecutingC++Program SelfAssessmentQuestions Summary TerminalQuestions

1.1Introduction
Thisunithasthefollowingobjectives Tounderstandtheimportanceofobjectorientedprogrammingapproach overprocedurallanguages TolearnthebasicfeaturessupportedbyOOPlanguages TolearnthebasicconstructofaC++programandlearntocompileand executeit

1.2EvolutionofProgrammingmethodologies
The programming languages have evolved from machine languages, assembly languages to high level languages to the current age of programmingtools.While machine level language and assembly language wasdifficulttolearnforalayman,highlevellanguageslikeC,Basic,Fortran
SikkimManipalUniversity PageNo.1

OOPSUsingC++

Unit1

and the like was easy to learn with more English like keywords. These languages were also known as procedural languages as each and every statementintheprogramhadtobespecifiedtoinstructthecomputertodo a specific job. The procedural languages focused on organizing program statements into procedures or functions. Larger programs were either broken intofunctions or modules whichhaddefined purpose and interface tootherfunctions. Proceduralapproachforprogramminghadseveralproblemsasthesizeof the softwares grew larger and larger. One of the main problems was data being completely forgotten. The emphasis was on the action and the data was only used in the entire process. Data in the program was created by variables and if more than one functions had to access data, global variableswereused.Theconceptofglobalvariablesitselfisaproblemasit may be accidentally modified by an undesired function. This also leads to difficulty in debugging and modifying the program when several functions accessaparticulardata. Theobjectorientedapproachovercomesthisproblembymodelingdataand functions together there by allowing only certain functions to access the requireddata. The procedural languages had limitations of extensibility as there was limited supportfor creating user defined datatypes anddefininghowthese datatypeswillbehandled.Forexampleiftheprogrammerhadtodefinehis ownversionofstringanddefinehowthisnewdatatypewillbemanipulated, itwouldbedifficult.Theobjectorientedprogrammingprovidesthisflexibility throughtheconceptofclass. Anotherlimitationoftheprocedurallanguagesisthattheprogrammodelis not closer to real world objects . For example, if you want to develop a gamingapplicationofcarrace,whatdatawouldyouuseandwhatfunctions
SikkimManipalUniversity PageNo.2

OOPSUsingC++

Unit1

youwouldrequireisdifficultquestionstoanswerinaproceduralapproach. The object oriented approach solves this further by conceptualizing the problem as group of objects which have their own specific data and functionality. In the car game example, we would create several objects suchasplayer,car,trafficsignalandsoon. Someofthelanguagesthatuseobjectorientedprogrammingapproachare C++, Java, Csharp, Smalltalk etc. We will be learning C++ in this text to understand object oriented programming. C++ is a superset of C. Several featuresaresimilarinCandC++. SelfAssessmentQuestions 1. Listthelimitationsofprocedurallanguages 2. _______isanOOPLanguage 3. In OOP approach programmers can create their own data types. True/False 4. In procedural languages, the programs are written by dividing the programsintosmallerunitsknownas__________

1.3IntroductiontoOOPanditsbasicfeatures
As discussed earlier, one of the basic concept in Object Oriented Programming approach is bundling both data and functions into one unit known as object. The functions of a particular object can only access the dataintheobjectprovidinghighlevelofsecurityforthedata.Thefunctions intheobjectareknownasmemberfunctionsorsometimesasmethods. ThekeyfeaturesofOOPprogramminglanguagesare: ObjectsandClasses An Object is a program representation of some realworld thing (i.e person,placeor an event). Objects can have both attributes(data) and behaviours (functions or methods). Attributes describe the object with
SikkimManipalUniversity PageNo.3

OOPSUsingC++

Unit1

respect to certain parameters and Behaviour or functions describe the functionalityoftheobject. Table1.1ExampleofObjects
PolygonObject Attributes Position FillColor Bordercolor Behaviour Move Erase Changecolor Account number Balance BankAccount Attributes Behaviour DeductFunds Transferfunds DepositFunds Showbalance

AccordingtoPressman,Objectscanbeanyoneofthefollowing: a) Externalentities b) Things c) Occurrencesorevents d) Roles e) Organisationalunits f) Places g) DataStructures Forexample,objectscanbeanmenuorbuttoninangraphicuserinterface program or it may be an employee in an payroll application. Objects can alsorepresentadatastructuresuchasastackoralinkedlist.Itmaybea serveroraclientinannetworkingenvironment. Objectswiththesamedatastructureandbehavioraregroupedtogetheras class. In other words, Objects are instances of a class. Classes are templates that provide definition to the objects of similar type. Objects are like variables created whenever necessary in the program. For example, EmployeemaybeaclassandPawan,SujayandGaneshareobjectsofthe class employees. Just as you can create as many variables of a default datatypesuchasinteger,youcancreateasmanyobjectsofaclass.
SikkimManipalUniversity PageNo.4

OOPSUsingC++

Unit1

ClassesandObjectssupportdataencapsulationanddatahidingwhichare key terms describing object oriented programming languages. Data and functionsaresaidtobeencapsulatedinansingleentityasobject.Thedata issaidtobehiddenthusnotallowingaccidentalmodification. Inheritance Inheritance is one of the most powerful feature of Object Oriented Programming Languages that allows you to derive a class from an existing class and inherit all the characteristics and behaviour of the parentclass.Thisfeatureallowseasymodificationofexistingcodeand also reuse code. The ability to reuse components of a program is an importantfeatureforanyprogramminglanguage PolymorphismandOverloading Operatoroverloadingfeatureallowsuserstodefinehowbasicoperators work with objects. The operator + will be adding two numbers when usedwithintegervariables.Howeverwhenusedwithuserdefinedstring class,+operatormayconcatenatetwostrings.Similarlysamefunctions withsamefunctionnamecanperformdifferentactionsdependingupon which object calls the function. This feature of C++ where same operatorsorfunctionsbehavedifferentlydependinguponwhattheyare operatingoniscalledaspolymorphism(Samethingwithdifferentforms). Operatoroverloadingisakindofpolymorphism. OOPapproachoffersseveraladvantagestotheprogrammerssuchas Codecanbereusedinsituationsrequiringcustomization Program modelinganddevelopment closer to real world situations and objects Easytomodifycode Onlyrequireddatabindedtooperationsthushidingdatafromunrelated functions
SikkimManipalUniversity PageNo.5

OOPSUsingC++

Unit1

SelfAssessmentQuestions 1. _____________featureinOOPallowstoreusecode. 2. Theconceptofbundlingdataandfunctionsintosingleunitistermedas ___________ 3. Objectisan__________ofaclass 4. Giveanexampleofaclassandanobject 5. ______________isanadvantageofOOPapproach

1.4BasiccomponentsofaC++Programandprogramstructure
TheC++isasupersetofC.Atthebasiclevel,theprogramslooksimilarin bothCandC++.EverystatementinC++endswithasemicolon().Allthe reserved words have to be written in small case and the c++ compiler is casesensitive.Datainprogramminglanguagesarestoredinvariables.To create a variable, the variable should support an inbuilt datatype. The variableisanamegiventoaparticularlocationinthememoryandthevalue storedinavariablecanbealteredduringprogramexecution.Thedatatypes supportedinC++arelistedbelow Table1.2BasicDatatypesinc++
DataType Int Bool Char Long Float Double Longdouble Unsignedint Size(inbytes) Valuesthatcanbetaken 2 1 1 4 4 8 10 2 32768to32767 Falseandtrue/0and1 128to127 2,147,483,648to2,147,483,647
38 38 3.4X10 to3.4X10 (Precision7) 308 308 1.7X10 to1.7X10 (Precision15) 4932 4932 3.4X10 to1.1X10 (Precision19)

0to65,535

SikkimManipalUniversity

PageNo.6

OOPSUsingC++

Unit1

Variablescanbenamedaccordingtofollowingrules Cancompriseof1to8alphabets,digitsorunderscore Firstcharactershouldbeanalphabet Namesarecasesensitive Reservewordsofc++cannotbeused

Variables have to be declared before using them in the program. The declarationisdoneinthefollowingway: datatypevariablename Eg:intdata The above declaration declares a integer variable named data. The value storedinintdatabydefaultisajunkvalue.Valuescanalsobeassignedto the variable during declarations or initialized separately using the assignmentoperator=. Eg:intdata=0 Or intdata data=0 Constants are those which do not change during execution of a program. The constants in C++ can be numeric, character or string constants. Examplesofeachareshownintable1.3 Table1.3ExampleofConstants
Constant Numeric Constant Character Constant Example 23000 450.6(Floatingpoint) A Constraints Can be negative or positive, cannot containblanksorcommas,or$ Any character enclosed within single quotes, represented by unique ASCII numberinthememory Set of characters enclosed in double quotes, last character in the string is nullcharacter\0 PageNo.7

StringConstant Hello

SikkimManipalUniversity

OOPSUsingC++

Unit1

OperatorssupportedinC++arelistedbelow.Unaryoperatorsareusedwith oneoperandandbinaryoperatorisusedwithtwooperands. Table1.4OperatorsinC++


ArithmeticOperators Type Unaryas wellas binary Binary Binary Binary Binary Unary Unary Type Binary Binary Binary Binary Binary Binary Type Binary Binary Unary Action Subtractionforbinaryandminusfor unary Addition Multiplication Division Modulus(remainderafterdividing) Decrementvaluebyone Incrementvaluebyone Action Greaterthan Greaterthanorequal Lessthan Lessthanequal Comparisionforequality Comparisionforinequality Action AND OR NOT

+ * / % ++ RelationalOperators > >= < <= == != LogicalOperators && || !

Letsbeginwithasimplec++program //sum.cpp #include<iostream.h> voidmain() { inta,b,sum cout<<Pleaseenteranytwonumbers<<endl cin>>a>>b


SikkimManipalUniversity PageNo.8

OOPSUsingC++

Unit1

sum=a+b cout<<Sumoftwonumbersis<<sum } The above program asks the user to enter two numbers and displays the sumofthetwonumbers.Iostream.hisaheaderfile.Thefirststatementof theaboveprogramisrequiredifyouwouldliketoincludethecinandcout statements which is used for standard input or input from keyboard and standard output or output to display screen. cin and cout are actually predefinedobjectsinC++.Iostream.hfilecontainsthedeclarationsforusing thecinandcoutstatements.Thereareseveralsuchheaderfileswhichhave to be included depending on the functions you are using. We will come acrossmanysuchheaderfilesasweprogress. EveryC++programshouldhaveamain()function.C++allowsyoutocreate yourownfunctionsintheprogram,likeC.Howevertheprogramexecution always begins with the master function main(). Paranthesis are used to group statements belonging to one function or program statement. Every openingparathesis({)shouldhaveamatchingclosingparathesis(}). The third statement declares three integer variables a, b and sum. The fourth statement displays Please enter any two numbers on the display screen using cout statement. Cout (pronounced as C out) uses << or insertionoperatortopushdatatotheoutputstream. Operatorsknownasmanipulatorscanbeusedalongwiththe<<operatorto modifythewaydataisdisplayed.Endlisanoperatorwhichissimilarto\n characterinCthatinsertsalinefeedintotheoutput.Thefirstcoutstatement in the program displays a statement where as the second cout statement displaysastatementandthevaluestoredinthevariablesum. Cin (pronounced asc in) statementuses >> orextraction operatortofeed thedatatotheinputstream.Theabovecinstatementwaitsforusertoenter
SikkimManipalUniversity PageNo.9

OOPSUsingC++

Unit1

twointegers.Thevaluesenteredbytheuseristhenstoredinthevariables aandb.Eachvariableincinstatementshouldseparatedby>>operator. Comment statements can be included in the program by prefixing the statement with // for single line comments. Comments add clarity to the program.Multiplelinecommentscanbeaddedbyenclosingthestatements between/*and*/. SelfAssessmentQuestions 1. ______________ is a header file used in c++ that handles input and outputfunctions. 2. ____________statementisusedtoinputdatafromtheuserinc++. 3. ______________ statement is used to display data on the display screeninc++. 4. ______________ isa masterfunction required in all C++programand programexecutionbeginsfromthefirststatementofthisfunction.

1.5CompilingandExecutingC++Program
1. Therearethree steps inexecutinga c++ program: Compiling,Linking and Running the program. The c++ programs have to be typed in a compiler. All the programs discussed in the book will be compiled on turboc++compiler.Theturboc++compilercomeswithaneditortotype andeditc++program.Aftertypingtheprogramthefileissavedwithan extension.cpp.Thisisknownassourcecode.Thesourcecodehasto beconvertedtoanobjectcodewhichisunderstandablebythemachine. Thisprocessisknownascompilingtheprogram.Youcancompileyour programbyselectingcompilefromcompilemenuorpressAlt+f9.After compiling a file with the same name as source code file but with extension.obj.iscreated.

SikkimManipalUniversity

PageNo.10

OOPSUsingC++

Unit1

Secondstepislinkingtheprogramwhichcreatesanexecutablefile.exe (filename same as source code) after linking the object code and the libraryfiles(cs.lib)requiredfortheprogram.Inasimpleprogram,linking process may involve one object file and one library file. However in a project, there may be several smaller programs. The object codes of these programs and the library files are linked to create a single executable file. Third and the last step is running the executable file where the statements in the program will be executed one by one. Fig 1.1 shows the entire process. When you execute the program, the compiler displays the output of the program and comes back to the programeditor.Toviewtheoutputandwaitforusertopressanykeyto return to the editor, type getch() as the last statement in the program. Getch()isaninbuiltpredefinedlibraryfunctionwhichinputsacharacter from the user through standard input. However you should include anotherheaderfilenamedconio.htousethisfunction.Conio.hcontains thenecessarydeclarationsforusingthisfunction.Theincludestatement willbesimilartoiostream.h.

Fig.1.1:CompilingandLinking

SikkimManipalUniversity

PageNo.11

OOPSUsingC++

Unit1

Duringcompilation,ifthereareanyerrorsthatwillbelistingbythecompiler. Theerrorsmaybeanyoneofthefollowing 1. Syntaxerror Thiserroroccursduetomistakeinwritingthesyntaxofac++statement or wrong use of reserved words, improper variable names, using variableswithoutdeclarationetc.Examplesare:missingsemicolonor paranthesis,typeintegerforintdatatypeetc.Appropriateerrormessage andthestatementnumberwillbedisplayed.Youcanseethestatement andmakecorrectiontotheprogramfile,saveandrecompileit. 2. Logicalerror Thiserroroccursduetotheflawinthelogic.Thiswillnotbeidentifiedby thecompiler.Howeveritcanbetracedusingthedebugtoolintheeditor. First identify the variable which you suspect creating the error and add themtowatchlistbyselectingDebug>Watches>Addwatch.Writethe variable name in the watch expression. After adding all the variables required tothe watch list, goto the statementfrom where you want to observe. If you are not sure, you can go to the first statement of the program.ThenselectDebug>ToggleBreakpoint(orpressctrl+f8).A red line will appear on the statement. Then Run the program by selectingCtrl+f9orRunoptionfromrunmenu.Theexecutionwillhalt at the statement where you had added the breakpoint. The watch variables and their values at that point of time will be displayed in the bottominthewatchwindow.PressF8toexecutethenextstatementtill youreachtheendoftheprogram.Inthiswayyoucanwatchcloselythe values in the watch variables after execution of each and every statementintheprogram.Ifyouwanttoexitbeforeexecutionofthelast statementpressCtrl+Break.Toremovethebreakpointintheprogram go to the statement where you have added breakpoint select Debug >ToggleBreakpoint(orpressctrl+f8).SelectDebug>watch>remove
SikkimManipalUniversity PageNo.12

OOPSUsingC++

Unit1

watches to remove the variables in the watch list. This tool helps in knowing the values taken by the variable at each and every step. You can compare the expected value with the actual value to identify the error. 3. Linkererror Thiserroroccurwhenthefilesduringlinkingaremissingormispelt 4. Runtimeerror Thiserroroccursiftheprogramsencountersdivisionbyzero,accessing anullpointeretcduringexecutionoftheprogram SelfAssessmentQuestions 1. ___________, ______________ and _____________ are phases in executionofaC++program 2. Thelogicalerrorisidentifiedbythecompiler.True/False 3. ________________istheextensionofC++programsourcefiles 4. ________________istheextensionofC++objectcode Summary Object oriented Programming enables storing data and functions together which enables hiding data from unnecessary exposure. Procedural languages differs from the Object oriented programming in the approach used in solving the problem. While the former focuses on organizing programs around functions, the later focuses organizing programs around classes.Classesallowuserstodefinetheirowndatatypesandfunctionality. This allows extension of the basic datatypes supported by the language. Reusability of code through inheritance allows users to use the existing code without modifying it but also extend the functionality of the existing code. The C++ programs are similar to C except for the object oriented programmingfeatures.EveryC++programhasamainfunctionfromwhere theexecution starts. C++ programs goes through two phases ie compiling andlinkingbeforeexecution.
SikkimManipalUniversity PageNo.13

OOPSUsingC++

Unit1

TerminalQuestions 1. WhichofthefollowingisnotafeatureofObjectOrientedProgramming a. Dataencapsulation d.DataStructure 2. Whichoneofthefollowingisnotaninbuiltbasicdatatypeinc++ a.Int b.Bool c.String d.Float 3. Writeaprogramthatacceptstwonumbersfromtheuserandswapsthe twonumberswithoutusingatemporaryvariable. 4. Write aprogram thataccepts two numbersaandband divides abyb anddisplaysthequotientandtheremainder. 5. Objectconstitutesof____________and_____________ AnswerstoSAQsandTQs AnswerstoSAQsin1.2 1. Limitations of procedural languages are no importance to data and inabilitytodefineuserdefineddatatypesanddefinefunctionalityforthe same 2. C++,smalltalk,Javaareall OOPLanguages 3. True 4. Functionsorprocedures AnswerstoSAQsin1.3 1. Inheritance 3. DataAbstraction 4. Objectisaninstanceofaclass 5. Class carandobjectMaruti800 6. Reusabilityofcode AnswerstoSAQsin1.4 1. iostream.h 2. cin 3. cout 4. main()function
SikkimManipalUniversity PageNo.14

b.Inheritance

c.OperatorOverloading

OOPSUsingC++

Unit1

AnswerstoSAQsin1.5 1. Compiling,LinkingandRunning 2. False,itcanassistinidentifyingusingdebugtool 3. .cpp 4. .obj AnswersTQs 1. d 2. c 3. Programtoswaptwonumberswithoutusingatemporaryvariable #include<iostream.h> voidmain() {intnum1,num2 cout<<entertwonumbers cin>>num1>>num2 Num1=num1+num2 Num2=num1num2 Num1=num1num2 cout<<numbersafterswappingare<<num1<<num2 } 4. Programtodivideaandbanddisplayquotientandremainder #include<iostream.h> voidmain() {inta,b,q,rem cout<<entertwonumbers cin>>a>>b q=a/b r=a%b cout<<Quotient=<<q<<endl cout<<remainder=<<r } 5. DataandFunctions
SikkimManipalUniversity PageNo.15

You might also like