# K.L.E.

Society’s

K. L. E. INSTITUTE OF TECHNOLOGY HUBLI - 30

K.L.E.S.

OBJECT ORIENTED PROGRAMMING

LABORATORY MANUAL
FOURTH SEMESTER B.E.

Subject Code Hrs / Week "ota# Hrs

: : :

06CSL47 03 42

IA Marks E a! Hours E a! Marks

: : :

25 03 50

DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING

1

INTRODUCTION:-

Object-Orie te! C" ce#t\$

Implementation of Abstract Data Types
Consider the ADT Integer. Programming lang ages s ch as Pascal! C! "od la#\$ and others already offer an implementation for it. Sometimes it is called int or integer. %nce yo &'e created a 'ariable of this type yo can se its pro'ided operations. (or e)ample! yo can add t*o integers+
int i, j, k; i = 1; j = 2; k = i + j; /* Define three integers */ /* Assign 1 to integer i */ /* Assign 2 to integer j */ /* Assign the sum of i and j to k */

Let&s start *ith the abo'e code fragment and o tline the relationship to the ADT Integer. The first line defines three instances i! j and k of type Integer. Conse, ently! for each instance the special operation constructor sho ld be called. In o r e)ample! this is internally done by the compiler. The compiler reser'es memory to hold the 'al e of an integer and --binds&& the corresponding name to it. If yo refer to i yo act ally refer to this memory area *hich *as --constr cted&& by the definition of i. %ptionally! compilers might choose to initiali.e the memory! for e)ample! they might set it to / 0.ero1. The ne)t line
i = 1;

sets the 'al e of i to be 2. Therefore *e can describe this line *ith help of the ADT notation as follo*s+ Perform operation set with argument 1 on the Integer instance i. This is written as follows: i.set(1). 3e no* ha'e a representation at t*o le'els. The first le'el is the ADT le'el *here *e DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING %

e)press e'erything that is done to an instance of this ADT by the in'ocation of defined operations. At this le'el! pre# and post conditions are sed to describe *hat act ally happens. In the follo*ing e)ample! these conditions are enclosed in c rly brac4ets. 5 Precondition+ i 6 i.set021 5 Postcondition+ n i *here n 6 is any 2 Integer 7 7

The second le'el is the implementation le'el! *here an act al representation is chosen for the operation. In C the e, al sign --6&& implements the set() operation. 8o*e'er! in Pascal the follo*ing representation *as chosen+
i := 1;

In either case! the ADT operation set is implemented. Let&s stress these le'els a little bit f rther and ha'e a loo4 at the line
k = i + j;

%b'io sly! --9&& *as chosen to implement the add operation. 3e co ld read the part --i 9 :&& as --add the 'al e of j to the 'al e of i&&! th s at the ADT le'el this res lts in 5 Precondition+ Let i 6 n2 and j 6 n\$ *ith n2! n\$ partic lar Integers 7 i.add0:1 5 Postcondition+ i 6 n2 and j 6 n\$ 7 The postcondition ens res that i and j do not change their 'al es. Please recall the specification of add. It says that & e' Integer is created the 'al e of *hich is the s m. Conse, ently! *e m st pro'ide a mechanism to access this ne* instance. 3e do this *ith the set operation applied on instance k+ 5 Precondition+ Let k 6 n *here n is any Integer 7 4.set0i.add0:11 5 Postcondition+ k 6 i 9 j 7 As yo can see! some programming lang ages choose a representation *hich almost e, als the mathematical form lation sed in the pre# and postconditions. This ma4es it sometimes diffic lt to not mi) p both le'els.

Class
A class is an act al representation of an ADT. It therefore pro'ides implementation details for the data str ct re sed and operations. 3e play *ith the ADT Integer and design o r o*n class for it+
class Integer attri!utes:

DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING

3

In this notation class &&&% denotes the definition of a class.int i methods: set"alue#int n\$ Integer add"alue#Integer j\$ % In the e)ample abo'e as *ell as in e)amples *hich follo* *e se a notation *hich is not programming lang age specific. Please notice the se of --i&& and --:&& in the last sentence to name the t*o integers. %b:ects are ni. al to --\$&&. This is similar to --traditional&& programming lang ages *here yo co ld ha'e! say t*o integers i and j both of *hich e. Again *e disting ish the t*o le'els *ith different terms+ At the implementation le'el *e spea4 of --attrib tes&& *hich are elements of the data str ct re at the ADT le'el. %b:ect 3e ha'e tal4ed of instances of a stract emplo!ees. Therefore yo co ld ha'e t*o disting ishable ob:ects *ith the same set of 'al es. 3e refer to the set of 'al es at a partic lar time as the state of the ob:ect. The state of the ob:ect changes according to the methods *hich are applied to it. The corresponding attrib te is an ordinary integer of a programming lang age. 3e refer to these possible se. It defines attributes and methods which implement the data structure and operations of the A"T# respecti\$el!. Definition (Object) An object is an instance of a class. ence of digits. In o r e)ample! the data str ct re consists of only one element+ a signed se. Definition (Class) A class is the implementation of an a stract data t!pe (A"T). These instances are act al --e)amples&& of an abstract employee! hence! they contain act al 'al es to represent a partic lar employee. ely identifiable by a name. It can e uni%uel! identified ! its name and it defines a state which is represented ! the \$alues of its attri utes at a particular time. 3e call these instances o jects. 3e only define t*o methods setValue() and addValue() representing the t*o operations set and add. Instances of classes are called o jects. Conse. DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING ( . The same applies to --methods&& *hich are the implementation of the ADT operations. ently! classes define properties and beha'io r of sets of ob:ects. ence of state changes as the eha\$iour of the ob:ect+ Definition (Behaviour) The behaviour of an o ject is defined ! the set of methods which can e applied on it. Enclosed in the c rly brac4ets are t*o sections attri!utes: and methods: *hich define the implementation of the data str ct re and operations of the corresponding ADT.

#\$ set. At r ntime instances of these classes! the ob:ects! achie'e the goal of the program by changing their states. estion arises of ho* these ob:ects interact. A circle defines a center point and a radi s+ class -ircle attri!utes: int (.adius#ne+.adius#\$ % Comparing both class definitions *e can obser'e the follo*ing+ DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING ) . radius methods: set*#int ne+*\$ get*#\$ set.\$ get. ) methods: set*#int ne+*\$ get*#\$ set.3e no* ha'e t*o main concepts of ob:ect#orientation introd ced! class and ob:ect. ). %b:ect#oriented programming is therefore the implementation of abstract data types or! in more simple *ords! the *riting of classes. The . "ore %b:ect#%riented Concepts <elationships A-Kind-Of relationship Consider yo ha'e to *rite a dra*ing program. This program *o ld allo* dra*ing of 'ario s o jects s ch as points! circles! rectangles! triangles and many more.#int ne+.#\$ % =o contin e defining classes of yo r dra*ing program *ith a class to describe circles. 3e therefore introd ce the concept of a message in the ne)t section.adius\$ get. Conse.#int ne+. (or e)ample! the point class : st defines a point by its coordinates+ class 'oint attri!utes: int (.\$ get. (or each ob:ect yo pro'ide a class definition. ently! yo can thin4 of yo r r nning program as a collection of ob:ects.

1: Ill stration of --a#4ind#of&& relationship. Kno*ing the properties of class Point *e can describe a circle as a point pl s a radi s and methods to access it. In the class Point these elements describe the position of the point! in the case of class 'ircle they describe the circle&s center. Conse.2. The arro*ed line indicates the direction of the relation! hence! it is to be read as --Circle is a#4ind#of Point. In this and the follo*ing fig res! classes are dra*n sing rectangles. . Fi*+re ).• • • >oth classes ha'e t*o data elements & and !.%: Ill stration of --is#a&& relationship. 3e ill strate this graphically as sho*n in (ig re ?.\$ ill strates this relationship. Class 'ircle --adds&& a ne* data element radius and corresponding access methods. Similarly! yo mo'e circles in this direction by altering their & 'al e. 8o*e'er! a circle is some*hat more --speciali. Th s! a circle is --a#4ind#of&& point. If *e create ob:ects of t*o s ch classes *e refer to their relationship as an --is#a&& relationship. Their name only consists of lo*ercase letters. (or e)ample! yo can mo'e points in & direction by altering the 'al e of &. >oth classes offer the same set of methods to get and set the 'al e of the t*o data elements & and !. (ig re ?. DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING .&& Is-A relationship The pre'io s relationship is sed at the class le'el to describe relationships bet*een t*o similar classes. Th s! & and ! ha'e the same meaning in both classes+ They describe the position of their associated ob:ect by defining a point. ently! each circle beha'es li4e a point. Fi*+re ). Their name al*ays starts *ith an ppercase letter. In this and the follo*ing fig res! ob:ects are dra*n sing rectangles *ith ro nd corners. Since the class 'ircle is a 4ind of class Point! an instance of 'ircle! say circle! is a point.ed&&.

Fi*+re ).3: Ill stration of --part#of&& relationship.Part-Of relationship =o sometimes need to be able to b ild ob:ects by combining them o t of others. 0Let&s ass me! that yo already ha'e defined a class Triangle. Fi*+re ). Let&s come bac4 to o r dra*ing program. =o already ha'e created se'eral classes for the a'ailable fig res.A. =o already 4no* this from proced ral programming! *here yo ha'e the str ct re or record constr ct to p t data of 'ario s types together. DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING - .B1. Therefore *e can easily add this relationship to the part#of ill stration by adding arro*s in the other direction 0(ig re ?.(: Ill stration of --has#a&& relationship. Has-A relationship This relationship is : st the in'erse 'ersion of the part#of relationship. @o* yo decide that yo *ant to ha'e a special fig re *hich represents yo r o*n logo *hich consists of a circle and a triangle.1 Th s! yo r logo consists of t*o parts or the circle and triangle are part(of yo r logo+ class /ogo attri!utes: -ircle circle 0riangle triangle methods: set#'oint +here\$ % 3e ill strate this in (ig re ?.

%n the ob:ect le'el *e are no* able to se a circle : st as *e *o ld se a point! beca se a circle is#a point.Inheritance 3ith inheritance *e are able to ma4e se of the a#4ind#of and is#a relationship. 14\$ /* 5o2e circle !) mo2ing */ /* its center 3oint */ Let&s try to formali. (or e)ample! *e can define a circle ob:ect and set its center point coordinates+ -ircle acircle acircle&set*#1\$ acircle&set. There is no need to define them t*ice+ 3e : st se already e)isting and *ell#4no*n data and method definitions. (or e)ample! yo can *rite a f nction or method! say mo\$e()! *hich sho ld mo'e a point in & direction+ mo2e#'oint a3oint.adius\$ get. int delta(\$ a3oint&set*#a3oint&get*#\$ + delta(\$ % As a circle inherits from a point! yo can se this f nction *ith a circle arg ment to mo'e its center point and! hence! the *hole circle+ -ircle acircle &&& mo2e#acircle. As described there! classes *hich are a#4ind#of another class share properties of the latter. In o r point and circle e)ample! *e can define a circle *hich inherits from point+ class -ircle inherits from 'oint attri!utes: int radius methods: set.adius#int ne+.e the term --inheritance&&+ DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING . .adius#\$ % Class 'ircle inherits all data elements and methods from point.adius#1\$ /* Inherited from 'oint */ /* Added !) -ircle */ --Is#a&& also implies! that *e can se a circle e'ery*here *here a point is e)pected.#2\$ acircle&set.

. Any*ay! *ithin this t torial! the arro*ed line is al*ays directed to*ards the s perclass. %b:ects of a s bclass can be sed *here ob:ects of the corresponding s perclass are e)pected. DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING / . ently! the arro*ed line starts from the s bclass to*ards the s perclass as ill strated in (ig re ?. A common dra*ing scheme is to se arro*ed lines to indicate the inheritance relationship bet*een t*o classes or ob:ects.Definition (Inheritance) Inheritance is the mechanism which allows a class A to inherit properties of a class ). In o r e)amples *e ha'e sed --inherits#from&&. A is called subclass of ). *e sa! ++A inherits from ).jects of class A thus ha\$e access to attri utes and methods of class ) without the need to redefine them. S bclasses may also be called child classes or : st deri\$ed classes. This is d e to the fact that ob:ects of the s bclass share the same beha'io r as ob:ects of the s perclass. The follo*ing definition defines t*o terms *ith *hich *e are able to refer to participating classes *hen they se inheritance. Fi*+re ). Conse. In the literat re yo may also find other terms for --s perclass&& and --s bclass&&. .): A simple inheritance graph. If yo dra* this hierarchy yo get an inheritance graph. S perclasses are also called parent classes. %f co rse! yo can again inherit from a s bclass! ma4ing this class the s perclass of the ne* s bclass. In the follo*ing sections an nmar4ed arro*ed line indicates --inherit#from&&.?. The direction in *hich the arro*ed line is sed! depends on ho* the corresponding a thor has decided to nderstand it. In the literat re yo also find ill strations *here the arro*ed lines are sed : st the other *ay aro nd.. Definition (Superclass/Subclass) If class A inherits from class )# then ) is called superclass of A. This leads to a hierarchy of s perclassCs bclass relationships.

Conse. ently! it ma4es sense to let a dra*able te)t ha'e a point *hich defines its location *ithin the dra*ing area. " ltiple inheritance means that one s bclass can ha'e more than one s perclass. It *o ld be nice to also se already e)isting ro tines s ch as mo\$e() to mo'e the te)t aro nd. Fi*+re )." ltiple Inheritance %ne important ob:ect#oriented mechanism is m ltiple inheritance. It also does "t mean that a s bclass can inherit from a class *hich itself is a s bclass of another class.: Deri'e a dra*able string *hich inherits properties of Point and .tring *hich allo*s con'enient handling of te)t. In o r program *e *o ld li4e to se this class to add te)t to the possible dra*ing ob:ects. Therefore *e deri'e a ne* class "rawa le.tring *hich inherits properties from Point and .. In o r pse do lang age *e *rite this by simply separating the m ltiple s perclasses by comma+ class Dra+a!le6tring inherits from 'oint. " ltiple inheritance does "t mean that m ltiple s bclasses share the same s perclass. S ppose *e already ha'e a class . 6tring attri!utes: /* All inherited from su3erclasses */ methods: % /* All inherited from su3erclasses */ 3e can se ob:ects of class "rawa le. >eca se a drawa lestring is#a point *e can mo'e them aro nd DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 10 .tring as ill strated in (ig re ?. (or e)ample! it might ha'e a method to append other te)t.tring li4e both points and strings.tring. As an e)ample consider again o r dra*ing program. This enables the s bclass to inherit properties of more than one s perclass and to --merge&& their properties.D.

tring 'ersion or none of them. The s bclass m st resol'e the conflict by pro'iding a property *ith the name and by defining ho* to se the ones from its s perclasses. %thers *ill be --hidden&&. This ma! introduce naming conflicts in A if at least two of its superclasses define properties with the same name. estion arises! *hat sho ld be inherited by "rawa le.. This leads to an inheritance graph as sho*n in (ig re ?.# )n# we speak of multiple inheritance. The first sol tion is not 'ery con'enient as it introd ces implicit conse. 14\$ &&& Since it is a string! *e can append other te)t to them+ dstring&a33end#70he red !ro+n fo( &&&7\$ @o* it&s time for the definition of m ltiple inheritance+ Definition (Multiple Inheritance) If class A inherits from more than one class# ie. (or the second case! s bclasses m st e)plicitly redefine properties *hich are in'ol'ed in a naming conflict.F. The Point! . ences depending on the order in *hich classes inherit from each other.tring. (or an e)ample! let&s ass me! that class ..tring defines a method set0() *hich sets the string to a se. DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 11 . These conflicts can be sol'ed in at least t*o *ays+ • • The order in *hich the s perclasses are pro'ided define *hich property *ill be accessible by the conflict ca sing name. A special type of naming conflict is introd ced if a class " m ltiply inherits from s perclasses ) and ' *hich themsel'es are deri'ed from one s perclass A. The . The abo'e definition introd ce naming conflicts *hich occ r if more than one s perclass of a s bclass se the same name for either attrib tes or methods.Dra+a!le6tring dstring &&& mo2e#dstring. A inherits from )1# )/# . ence of --E&& characters.

8o*e'er! caref lly sed! nder some conditions m ltiple inheritance pro'ides an efficient and elegant *ay of form lating things. As the res lt of m ltiple inheritance can al*ays be achie'ed by sing 0simple1 inheritance some ob:ect# oriented lang ages e'en don&t allo* its se.Fi*+re ). Conse. ently! " cannot introd ce naming conflicts *ith names of class A. In this sol tion! " o*ns t'" copies of the properties of A+ one is inherited by ) and one by '. 8o*e'er! if ) and ' add properties *ith the same name! " r ns into a naming conflict. Some e)isting programming lang ages sol'e this special inheritance graph by deri'ing " *ith • • the properties of A pl s the properties of ) and ' 'it0"+t the properties they ha'e inherited from A. estion arises *hat properties class " act ally inherits from its s perclasses ) and '. Altho gh m ltiple inheritance is a po*erf l ob:ect#oriented mechanism the problems introd ced *ith naming conflicts ha'e lead se'eral a thors to --doom&& it.-: A name conflict introd ced by a shared s perclass of s perclasses sed *ith m ltiple inheritance. Abstract Classes DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 1% . Another possible sol tion is! that " inherits from both inheritance paths. The .

(or e)ample! the dra*ing ro tine of a circle is different from the dra*ing ro tine of a rectangle.ject! does not pro'ide any f nctionality for dra*ing itself.#\$ 3rint#\$ /* . ) methods: set*#int ne+*\$ get*#\$ set. @o*! e'ery class in o r dra*ing program e)ample inherits properties from the general dra*able ob:ect class. To force e'ery dra*able ob:ect to incl de s ch method! *e define a class "rawa le. Sometimes it ma4e sense to only describe the properties of a set of ob:ects *itho t 4no*ing the act al beha'io r beforehand. ently! ob:ects of a s bclass beha'e li4e ob:ects of their s perclasses. Therefore! class Point changes to+ class 'oint inherits from Dra+a!le8!ject attri!utes: int (. 8o*e'er! the necessary steps to dra* an ob:ects depends on its represented shape. 3e refer to this special type of classes as a stract classes+ DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 13 . Let&s call the dra*ing method print(). This class rather specifies properties *hich m st be defined by e'ery deri'ed class.#int ne+. It is sed to e)press the fact that deri'ed classes m st --redefine&& the properties to f lfill the desired f nctionality. It is not intended to create ob:ects from it. The f ll definition incl ding the semantics of the properties m st be pro'ided by deri'ed classes.\$ get. In o r dra*ing program e)ample! each ob:ect sho ld pro'ide a method to dra* itself on the dra*ing area.3ith inheritance *e are able to force a s bclass to offer the same properties li4e their s perclasses. The s perclass of all dra*able ob:ects! class "rawa le.edefine for 'oint */ % 3e are no* able to force e'ery dra*able ob:ect to ha'e a method called print *hich sho ld pro'ide f nctionality to dra* the ob:ect *ithin the dra*ing area.ject from *hich e'ery other class in o r e)ample inherits general properties of dra*able ob:ects+ a!stract class Dra+a!le8!ject attri!utes: methods: 3rint#\$ % 3e introd ce the ne* 4ey*ord &b\$tr&ct here. Th s from the abstract class& point of 'ie*! the properties are only specified b t not f lly defined. Conse.

Let&s ill strate this *ith the follo*ing e)ample. 8o*e'er! *e don&t 4no* *ith *hich types the class *ill be sed. Th s! it sho ld be possible to declare list ob:ects for apples! cars or any other type. The act al class definition is created once *e declare a partic lar ob:ect. 'lass A onl! specifies properties. anotherA33le a33le/ist&a33end#anotherA33le\$ a33le/ist&a33end#anA33le\$ The first line declares apple1ist to be a list for apples. Conse. (or e)ample! *e can declare a list ob:ect for apples if a definition fot the type Apple e)ists+ /ist for A33le a33le/ist A33le anA33le. At this time! the compiler ses the template definition! s bstit tes e'ery occ rrence of T *ith Apple and creates an act al class definition for it.Definition ( bstract Class) A class A is called abstract class if it is onl! used as a superclass for other classes. Generic Types At the time! *hen *e *rite do*n a class definition! *e m st be able to say that this class sho ld define a generic type. "eri\$ed classes must define the properties of A. 8o*e'er! *e act ally don&t *ant to create ob:ects from them+ *e only *ant to e)press common characteristics of a set of classes. tem3late class /ist for 0 attri!utes: &&& /* Data structure needed to im3lement */ /* the list */ methods: a33end#0 element\$ 0 get9irst#\$ 0 get:e(t#\$ !ool more#\$ % The abo'e template class 1ist loo4s li4e any other class definition. The type of this element *ill be the data type *ith *hich an act al list ob:ect is created. 8o*e'er! the first line declares 1ist to be a template for 'ario s types. ently! *e m st be able to define the class *ith help of a --placeholder&& to *hich *e refer as if it is the type on *hich the class operates. This leads to a class definition similar to the one that follo*s+ class /ist attri!utes: DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 1( . The identifier T is sed as a placeholder for an act al type. Abstract classes allo* s to str ct re o r inheritance graph. (or e)ample! append() ta4es one element as an arg ment. S ppose! yo *ant to define a list class *hich sho ld be a generic type. It is not used to create o jects. Th s! the class definition pro'ides s *ith a template of an act al class.

&&& /* Data structure needed to im3lement */ /* the list */ % methods: a33end#A33le element\$ A33le get9irst#\$ A33le get:e(t#\$ !ool more#\$ This is not e)actly! *hat the compiler generates. 3e are able to define template classes *ith more than one parameter. e names. This allows the definition of an actual class ased on the template specified for A and the actual data t!pe. %f co rse! a directory sho ld be able to store any type of ob:ect. ently! *e *o ld define a template class "irector! *hich is based on t*o type parameters! one for the 4ey and one for the stored ob:ects. (or e)ample! directories are collections of ob:ects *here each ob:ect can be referenced by a ke!. (or e)ample! in Pascal an e)pression li4e DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 1) . Th s! /ist for A33le a/ist /ist for A33le another/ist *ill create the act al class definition for a1ist and *ill re se it for another1ist.e this in the follo*ing definition+ Definition (!emplate Class) If a class A is parameteri2ed with a data t!pe )# A is called template class. The reason *hy both do not conflict by their name is that the compiler generates ni. > t there are also 'ario s possibilities for 4eys. (or e)ample! if *e need another list for! say pears! *e can *rite+ /ist for A33le a33le/ist /ist for 'ear 3ear/ist &&& In both cases the compiler generates an act al class definition. This also implies the 'ariable&s definition *here the compiler reser'es space for the 'ariable. Conse. The compiler m st ens re that *e can create m ltiple lists for different types at any time. Conse. In any case! if yo declare : st another list of apples! the compiler can fig re o t if there already is an act al class definition and se it or if it has to be created. 3e s mmari. 8o*e'er! since this is not 'ie*able to s! *e don&t go in more detail here. (or instance! they might be strings or n mbers. Static and Dynamic >inding In strongly typed programming lang ages yo typically ha'e to declare 'ariables prior to their se. -nce an o ject of A is created# ) is replaced ! an actual data t"pe. ently! both are of the same type.

Th s! beca se the content of i is a *hole n mber! the t!pe of i is integer. If it is T<HE! n is of type integer *hereas in the other case it is of type string. Definition (D"namic Binding) If the t!pe T of a \$aria le with name 3 is implicitl! associated ! its content# we sa!# that 3 is d"namicall" bound to T. The association process is called d"namic binding. The association process is called static binding.string. 3ith the declaration *e ind the name i to the type integer.. This enables the compiler to chec4 at compilation time for type consistency. (or e)ample! some lang ages allo* to introd ce 'ariables once they are needed+ &&& i := 121 /* :o a33earance of i */ /* -reation of i as an integer */ The type of i is 4no*n as soon as its 'al e is set. >oth bindings differ in the time *hen the type is bo nd to the 'ariable. 3e call this partic lar type of binding --static&& beca se it is fi)ed at compile time. endif The type of n after the if statement depends on the e'al ation of somecondition(). Additionally! it defines eno gh memory space to hold an integer 'al e. In this case! i is of type integer since *e ha'e assigned a *hole n mber to it.2ar i : integer. Definition (Static Binding) If the t!pe T of a \$aria le is e&plicitl! associated with its name 3 ! declaration# we sa!# that 3 is staticall" bound to T.<= then n := 121 else n := . declares 'ariable i to be of type integer. (or e)ample! the follo*ing assignment *ill res lt in a type mismatch error *hen yo try to compile it+ 2ar i : integer.a!c. . This binding is tr e *ithin the scope in *hich i is declared. There e)ist programming lang ages *hich are not sing e)plicitly typed 'ariables. Consider the follo*ing e)ample *hich is only possible *ith dynamic binding+ if somecondition#\$ == 0. &&& i := . DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 1.

ely identified by+ • • the name of the f nction 0or method1 and the t!pes of its parameter list.Polymorphism Polymorphism allo*s an entity 0for e)ample! 'ariable! f nction or ob:ect1 to ta4e a 'ariety of representations.ero1 and (ALSE other*ise. This a ilit! of a \$aria le is called pol"morphism. Th s! f nctions 0or methods1 are ni. In programming lang ages *itho t polymorphism for f nctions *e cannot declare these t*o f nctions beca se the name is3ull *o ld be do bly defined. 8ere! the type of a 'ariable depends on its content. DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 1- . 8o*e'er! if the lang age *o ld ta4e the parameters of the f nction into acco nt it *o ld *or4. Another type of polymorphism can be defined for f nctions.a!c. Therefore *e ha'e to disting ish different types of polymorphism *hich *ill be o tlined here. (or integer n mbers this is easy+ !oolean is:ull#int i\$ if #i == 4\$ then return 0. Th s! its type depends on the content at a specific time+ 2 := 121 &&& 2 := . The first type is similar to the concept of dynamic binding.<= else return 9A/6= endif % In both cases *e *ant the f nction to ha'e the name is3ull.<= else return 9A/6= endif % 8o*e'er! if *e *ant to chec4 this for real n mbers! *e sho ld se another comparison d e to the precision problem+ !oolean is:ull#real r\$ if #r > 4&41 and r ? @4&AA\$ then return 0. (or e)ample! s ppose yo *ant to define a f nction is3ull() *hich ret rns T<HE if its arg ment is / 0. &&& /* /* /* /* 2 is integer */ use 2 as integer */ 2 7s+itches7 to string */ use 2 as string */ Definition (#ol"morphism (\$)) The concept of d!namic inding allows a \$aria le to take different t!pes dependent on the content at a particular time. 3itho t polymorphism for f nctions! do bly defined names *o ld be ambig o s.

Since this is some*hat complicated! here is a more abstract e)ample+ class Base DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 1. The declaration of this f nction might loo4 li4e this+ dis3la)#Dra+a!le8!ject o\$ &&& o&3rint#\$ &&& % 3e *o ld li4e to se this f nction *ith ob:ects of classes deri'ed from "rawa le.ject+ -ircle acircle 'oint a3oint .Since the parameter list of both is3ull f nctions differ! the compiler is able to fig re o t the correct f nction call by sing the act al types of the arg ments+ 2ar i : integer 2ar r : real i = 4 r = 4&4 &&& if #is:ull#i\$\$ then &&& &&& if #is:ull#r\$\$ then &&& /* <se is:ull#int\$ */ /* <se is:ull#real\$ */ Definition (#ol"morphism (%)) If a function (or method) is defined ! the com ination of • • its name and the list of t!pes of its parameters we speak of pol"morphism. This type of polymorphism allo*s s to re se the same name for f nctions 0or methods1 as long as the parameter list differs. Sometimes this type of polymorphism is called o\$erloading. @o* consider a f nction displa!() *hich sho ld be sed to display dra*able ob:ects.ectangle arectangle dis3la)#a3oint\$ dis3la)#acircle\$ dis3la)#arectangle\$ /* 6hould in2oke a3oint&3rint#\$ */ /* 6hould in2oke acircle&3rint#\$ */ /* 6hould in2oke arectangle&3rint#\$ */ The act al method sho ld be defined by the content of the ob:ect o of f nction displa!(). Consider the f nction mo\$e() again! *hich ta4es an ob:ect of class Point as its arg ment. The last type of polymorphism allo*s an ob:ect to choose correct methods. . 3e ha'e sed this f nction *ith any ob:ect of deri'ed classes! beca se the is#a relation holds.

3e then define a f nction demo() *hich ta4es a )ase ob:ect as its arg ment. This time! it is a )ase ob:ect. Th s! the f nction&s arg ment is --filled&& *ith an ob:ect of class )ase. Each class defines t*o methods foo() and ar(). The first method is defined as 2irtual. 3hen it is time to in'o4e method foo() it&s act al f nctionality is chosen based on the c rrent content of the corresponding ob:ect o. ently! foo() as defined in class )ase is called. The call to ar() is not s b:ect to this content resol tion. This means that if this method is in'o4ed its definition sho ld be e'al ated by the content of the ob:ect. DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 1/ . 3e call this f nction *ith a )ase ob:ect and a "eri\$ed ob:ect! respecti'ely. Let&s see *hat happens. Conse. Then the o tp t is as follo*s+ foo#\$ !ar#\$ foo#\$ !ar#\$ of of of of Base called& Base called& Deri2ed called& Base called& 3hy is this so.attri!utes: methods: 2irtual foo#\$ !ar#\$ % class Deri2ed inherits from Base attri!utes: methods: 2irtual foo#\$ !ar#\$ % demo#Base o\$ o&foo#\$ o&!ar#\$ % Base a!ase Deri2ed aderi2ed demo#a!ase\$ demo#aderi2ed\$ In this e)ample *e define t*o classes )ase and "eri\$ed. ently! *e can se this f nction *ith ob:ects of class "eri\$ed as the is#a relation holds. It is not mar4ed as 2irtual. ently! ar() is called in the scope of class )ase. The first call to demo() ses a )ase ob:ect. Conse. Conse. S ppose! that foo() and ar() are defined to : st print o t their name and the class in *hich they are defined.

comment can include // and can s3an o2er se2eral lines& */ // /* 0his is the -++ st)le comment */ until end of line In C yo m st define 'ariables at the beginning of a bloc4. -perators and methods of su classes can e defined to e e\$aluated in two conte&tes: 1. Data Types C99 introd ces a ne* data type called reference. )ased on o ject t!pe# leading to an e\$aluation within the scope of the superclass. %n the other hand! ar() is still e'al ated *ithin the scope of )ase. (or e)ample+ DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING %0 . (rom C To C99 This section presents e)tensions to the C lang age *hich *ere introd ced by C99 IDJ. C99 allo*s yo to define 'ariables and ob:ects at any position in a bloc4. @o*! the call to foo() is e'al ated by e)amining the content of o! hence! it is called *ithin the scope of "eri\$ed. =o can se both comment styles! for e)ample to comment o t large bloc4s of code+ /* . As an alias cannot e)ist *itho t its corresponding real part! yo cannot define single references. >asic E)tensions C99 adds a ne* comment *hich is introd ced by t*o slashes 0CC1 and *hich lasts ntil the end of line. /. Definition (#ol"morphism (&)) . Th s! 'ariables and ob:ects sho ld be defined *here they are sed. Th s! the arg ment o is filled *ith a "eri\$ed ob:ect.ation. It also deals *ith ob:ect#oriented concepts and their reali. The ampersand 0K1 is sed to define a reference.The second call to demo() ta4es a "eri\$ed ob:ect as its arg ment. 8o*e'er! o itself : st represents the )ase part of the pro'ided ob:ect aderi\$ed. )ased on o ject content# leading to an e\$aluation within the scope of the contained su class.jects of superclasses can e filled with o jects of their su classes. =o can thin4 of them as if they *ere --aliases&& to --real&& 'ariables or ob:ects. The second t!pe is called pol"morphism.

2 is adopted from I2J and pro'ides yo *ith an o'er'ie* of possible declarations. T&b1e . This allo*s to pass parameters as reference or to ret rn a --handle&& to a calc lated 'ariable or ob:ect. 8o*e'er! these are the ones *hich yo *ill probably se 'ery often. The table L.. S bse.1: Declaration e)pressions.int i(. In C and C99 yo can se the modifier const to declare partic lar aspects of a 'ariable 0or ob:ect1 to be constant. r( = 2. ently! some e)amples are presented *hich demonstrate the se of const. T&b1e .. i( = 1. The ne)t table L. DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING %1 .\$ lists possible combinations and describe their meaning. /* i( is 7real7 2aria!le */ /* r( is 7alias7 for i( */ /* also r( == 1 */ /* also i( == 2 */ <eferences can be sed as f nction arg ments and ret rn 'al es. int Cr( = i(.%: Constant declaration e)presssions. It is not complete in that it sho*s not e'ery possible combination and some of them ha'e not been introd ced here! beca se *e are not going to se them.

// change 2alue of tem3orar) integer DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING %% . // // just an ordinar) integer uninitialiDed 3ointer to integer constant 3ointer to integer constant integer 3ointer to constant integer constant 3ointer to constant integer The follo*ing assignments are 2&1i!+ i = ci. int *i3. // int * const cic3 = Cci. // int ci = E. Consider the follo*ing declarations 0again from I2J1+ int i. // // // // // // // assign constant integer to integer assign constant integer to 2aria!le +hich is referenced !) constant 3ointer change 3ointer to constant integer set 3ointer to constant integer to reference 2aria!le of constant 3ointer to constant integer The follo*ing assignments are i 2&1i!+ ci = F. See the follo*ing e)ample program+ Ginclude >stdio&h? int main#\$ const int ci = 1. // create tem3orar) integer for reference // cr = E. ci3 = Cci. // cannot assign 2alue to constant reference r = 1. int * const const const // // // const c3 = Ci. int Cr = ci. const int Ccr = ci. *ci3 = E. // int *ci3. i3 = ci3. c3 = Cci. *c3 = ci. ci3 = cic3. // // // // // // cannot change constant integer 2alue cannot change constant integer referenced !) 3ointer cannot change 2alue of constant 3ointer this +ould allo+ to change 2alue of constant integer *ci3 +ith *i3 3hen sed *ith references some pec liarities m st be considered.@o* let&s in'estigate some e)amples of contant 'ariables and ho* to se them.

7def7\$\$.ed. ma(#1A. <eference cr is defined as read(onl! 0constant reference1. % The abo'e e)ample program defines these t*o f nctions *hich differ in their parameter list! hence! they define t*o different f nctions. def\$ = HsIn7. ently! *hen changing r the 'al e of the temporary integer is changed. JA\$ = HdIn7. The first printf() call in f nction main() iss es a call to the first 'ersion of ma&()! beca se it ta4es t*o integers as its arg ment. 3hen compiled *ith G@H g99! the compiler iss es the follo*ing *arning+ con\$ersion from +const int. Similarly! the second printf() call leads to a call of the second 'ersion of ma&(). This enables to change the 'al e of the f nction call arg ment as it is 4no*n from other lang ages *ith call#by#reference parameters+ DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING %3 . 3rintf#7ma(#a!c.% 3rint#7ci == Hd. return !. discards const 3hat act ally happens is! that the compiler a tomatically creates a temporay integer 'ariable *ith 'al e of ci to *hich reference r is initiali. JA\$\$. ma(#7a!c7. This disables its se on the left side of assignments. =o may *ant to remo'e the comment in front of the partic lar line to chec4 o t the res lting error message of yo r compiler. int !\$ if #a ? !\$ return a. (or e)ample! *e can define t*o different f nctions ma&()! one *hich ret rns the ma)im m of t*o integers and one *hich ret rns the ma)im m of t*o strings+ Ginclude >stdio&h? int ma(#int a.A. Functions C99 allo*s f nction o'erloading as defined in section D. return 4. This temporary 'ariable li'es as long as reference r. return !. return 4. Conse. !\$ ? 4\$ return a. % int main#\$ 3rintf#7ma(#1A. r == HdIn7. to +int 4. r\$. ci. % char *ma(#char *a. <eferences can be sed to pro'ide a f nction *ith an alias of an act al f nction call arg ment. char * !\$ if #strcm3#a.

/* i( == 1.#const int 2al\$. Conse. j( == K2 */ % (irst %b:ect#oriented E)tensions In this section *e present ho* the ob:ect#oriented concepts of section B are sed in C99. 'oint a3oint. int get*#\$ return L(. <ecall the dra*ing program e)ample of section ? again. Additionally! yo can specify the access rights in more detail. 3e can s*itch bac4 to pri'ate access rights by starting a pri'ate section *ith 3ri2ate:. int C!). // 3oint coordinates 3u!lic: // !egin interface section 2oid set*#const int 2al\$. !). In C99 this *o ld loo4 li4e this+ class 'oint int L(.#\$ return L). 2oid set. % %. This declares a class Point and defines an ob:ect apoint. j(\$. L). This is possible as often as needed+ class 9oo // 3ri2ate as default &&& 3u!lic: DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING %( . i( = j( = 1. (or e)ample! 5& and 5! are #ri2&te! beca se elements of classes are pri'ate as defa lt. j(. =o can thin4 of a class definition as a str ct re definition *ith f nctions 0or --methods&&1. ently! *e e)plicitly m st --s*itch&& the access rights to declare the follo*ing to be #+b1ic.eference = K2. Instances of classes are called o jects. % int get.eference\$ !)"alue = K2. foo#i(.2oid foo#int !)"alue. 3e do that by sing the 4ey*ord 3u!lic follo*ed by a colon+ E'ery element follo*ing this 4ey*ord are no* accessible from o tside of the class. There *e ha'e de'eloped a class Point. Classes and Objects C99 allo*s the declaration and definition of classes. % 2oid !ar#\$ int i(.

(or e)ample! another class might : st define a method set0() *hich is . T*o for each coordinate to set and get its 'al e. Let&s come bac4 to o r class Point. +here +e s+itch !ack to 3ri2ate &&& 3u!lic: // &&& and !ack to 3u!lic& %.// +hat follo+s is 3u!lic until &&& 3ri2ate: // &&& here. %n the contrary! calls to the set methods *o ld res lt in a --real&& f nction call. This type of method definition is sef l for small and simple bodies. 3e m st be able to define the scope of the definitionM *e therefore se the scope operator --++&&+ 2oid 'oint::set*#const int 2al\$ L( = 2al. % 8ere *e define method set0() 0set6()1 *ithin the scope of class Point.#const int 2al\$ L) = 2al. Their act al f nctionality is still to be defined. 8o*e'er! *e can also se 3ri2ate: to s*itch to a pri'ate section in str ct res. The set methods are only declared. ite different from that of Point. 3hereas elements of classes 0defined *ith class1 are pri'ate by defa lt! elements of str ct res 0defined *ith struct1 are p blic. Str ct res are handled li4e classes. 3e define these methods o tside of the class declaration. methods %. This is e)actly *hat C99 does *ith struct. % 2oid 'oint::set. The get methods ha'e a f nction body+ They are defined within the class or! in other *ords! they are inlined methods. 3e are no* able to e)press a str ct re *ith help of a class! *here all elements are declared to be p blic+ class 6truct 3u!lic: // 6tructure elements are 3u!lic !) default // elements. Its interface starts *ith the p blic section *here *e define fo r methods. The ob:ect apoint can se these methods to set and get information abo t itself+ DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING %) . It also impro'e performance! beca se bodies of inlined methods are --copied&& into the code *here'er a call to s ch a method ta4es place. <ecall that a str ct re struct is a combination of 'ario s data elements *hich are accessible from the o tside. This ma4es it necessary! to indicate to *hich class a method definition belongs to.

% 8ere *e e)plicitly se the pointer this to e)plicitly dereference the in'o4ing ob:ect. C rrently! *e need to call the set methods to initiali. 8o*e'er! it sometimes ma4e sense to 4no* that there is a pointer this a'ailable *hich indicates the in'o4ing ob:ect. The .#const int 2al\$.#1\$. // <se this to reference in2oking // o!ject % 2oid 'oint::set.e an ob:ect at its definition time. L). a3oint&set*#1\$. If in'o4ed by an ob:ect! these members are --a tomatically&& mapped to the correct ob:ect. . 3u!lic: 'oint#\$ L( = L) = 4. DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING %. 3e co ld se this to ill strate *hat act ally happens+ 2oid 'oint::set*#const int 2al\$ this@?L( = 2al. +e define it here and // initialiDe it to the (@coordinate of a3oint // int ( = a3oint&get*#\$. 2oid set.e a point ob:ect . 8o*e'er! *e *o ld li4e to initiali.'oint a3oint. % 2oid set*#const int 2al\$. // InitialiDation // // ( is needed from here. The definitions of methods set0() and set6() ma4e se of class members 5& and 5!! respecti'ely. (ort nately! the compiler a tomatically --inserts&& these dereferences for class members! hence! *e really can se the first definitions of set0() and set6().#const int 2al\$ this@?L) = 2al. a3oint&set. Constructors Constr ctors are methods *hich are sed to initiali. estion arises abo t ho* the methods --4no*&& from *hich ob:ect they are in'o4ed. 3e e)tend o r class Point s ch that it initiali. 3e therefore se special methods called constructors.e the point *hen *e define it. hence.es a point to coordinates 0/! /1+ class 'oint int L(. This is done by implicitly passing a pointer to the in'o4ing ob:ect to the method. 3e can access this pointer *ithin the methods as this.

3u!lic: 'oint#\$ L( = L) = 4.e a point to other coordinates than 0/! /1. % 'oint#const int (.#\$ return L(. % return L). L).e o r ob:ects at definition time as *e ha'e re. % DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING %- . As other methods! they can ta4e arg ments. 'oint !3oint#12. 2al\$. If *e *ant to create a point from another point! hence! copying the properties of one ob:ect to a ne*ly created one! *e sometimes ha'e to ta4e care of the copy process. If *e *ant to create a second list *hich is a copy of the first! *e m st allocate memory and copy the indi'id al elements. % L). 3u!lic: 'oint#\$ L( = L) = 4. In o r class Point *e therefore add a third constr ctor *hich ta4es care of correctly copying 'al es from one ob:ect to the ne*ly created one+ class 'oint int L(. 3e are no* able to define a class 1ist *here the constr ctors ta4e care of correctly initiali. const int\$ 3ith constr ctors *e are able to initiali. (or e)ample! *e may *ant to initiali. const int )\$ L( = (. 3e therefore define a second constr ctor ta4ing t*o integer arg ments *ithin the class+ class 'oint int L(. int get*#\$ int get. L(. // 'oint::'oint#\$ // 'oint::'oint#const int. % Constr ctors ha'e the same name of the class 0th s they are identified to be constr ctors1. Constr ctors are implicitly called *hen *e define ob:ects of their classes+ 'oint a3oint. ested it in section \$ for o r singly lin4ed list. (or e)ample! consider the class 1ist *hich allocates dynamically memory for its elements. 1K\$. L).%. % %. They ha'e no ret rn 'al e. L) = ).ing its ob:ects.#\$ return 2al\$. % 2oid set*#const int 2oid set.#const int int get*#\$ return int get.

ation at definition time. 3e still need a mechanism *hich a tomatically --destroys&& an ob:ect *hen it gets in'alid 0for e)ample! beca se of lea'ing its scope1. 2al\$. L) = ). % The third constr ctor ta4es a constant reference to an ob:ect of class Point as an arg ment and assigns 5& and 5! the corresponding 'al es of the pro'ided ob:ect. % L).#const int int get*#\$ return int get. &&& % // // // // /ist::/ist#\$ initialiDes to em3t) list& add/remo2e elements Destructor callM Destr ction of ob:ects ta4e place *hen the ob:ect lea'es its scope of definition or is e)plicitly destroyed. Destructors Consider a class 1ist. irements of implementation of abstract data types+ Initiali. It is highly recommended that yo pro'ide for each of yo r classes s ch a constr ctor! e'en if it is as simple as in o r e)ample. Elements of the list are dynamically appended and remo'ed. 8o*e'er! *hen *e lea'e the scope of the definition of a list ob:ect! *e m st ens re that the allocated memory is released. L(. 'oint c3oint = a3oint. The latter happens! *hen *e dynamically allocate an ob:ect and release it *hen it is no longer needed. L) = from&L). The constr ctor helps s in creating an initial empty list. Therefore! classes can define destructors.'oint#const int (. const int )\$ L( = (. The copy constr ctor is called in the follo*ing cases+ 'oint a3oint. % 'oint#const 'oint Cfrom\$ L( = from&L(. 'oint !3oint#a3oint\$. 3e therefore define a special method called destructor *hich is called once for each ob:ect at its destr ction time+ 2oid foo#\$ /ist alist. This type of constr ctor is so important that it has its o*n name+ cop! constructor. % 2oid set*#const int 2oid set. // 'oint::'oint#\$ // 'oint::'oint#const 'oint C\$ // 'oint::'oint#const 'oint C\$ 3ith help of constr ctors *e ha'e f lfilled one of o r re. Destr ctors are declared similar to constr ctors. 2al\$. . Th s! they also se the name prefi)ed by a tilde 0N 1 of the defining class+ DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING %.#\$ return %.

This is e)pressed by appending --6 /&& after the method signat res+ class Dra+a!le8!ject &&& 3u!lic: &&& 2irtual 2oid 3rint#\$ = 4. 3u!lic: 'oint#\$ L( = L) = 4. Classes *hich define p re methods are called a stract classes. It is e'en in'alid to define one! beca se destr ctors are implicitly called at destr ction time+ =o ha'e no chance to specify act al arg ments. DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING %/ . Abstract Classes Abstract classes are defined : st as ordinary classes. 2al\$. L(. L) = from&L). % %. const int )\$ L( = (2al. 2oid set*#const int 2oid set. % 'oint#const 'oint Cfrom\$ L( = from&L(. % 'oint#const int (. % L). L) = )2al. P re methods m st also be declared 2irtual! beca se *e only *ant to se ob:ects from deri'ed classes.class 'oint int L(. %. This class definition *o ld force e'ery deri'ed class from *hich ob:ects sho ld be created to define a method print(). 3e : st mention their signature incl ding their ret rn type! name and parameters b t not a definition.#\$ return Destr ctors ta4e no arg ments.#const int int get*#\$ return int get. L). 8o*e'er! some of their methods are designated to be necessarily defined by s bclasses. % N'oint#\$ /* :othing to doM */ % 2al\$. These method declarations are also called pure methods. %ne co ld say! *e omit the method body or! in other *ords! specify --nothing&&.

Altho gh absol tely correct! it does not pro'ide a con'enient *ay of e)pression. 2&4\$. 8ere *e assign c the s m of a and . imag = Limag + o3&Limag. % %. (or e)ample! *e co ld define a --9&& operator for o r class 'omple&+ class -om3le( &&& 3u!lic: &&& -om3le( o3erator +#const -om3le( Co3\$ dou!le real = Lreal + o3&Lreal.%perator %'erloading If *e recall the abstract data type for comple) n mbers! 'omple&! *e co ld create a C99 class as follo*s+ class -om3le( dou!le Lreal. Limag#4&4\$ % -om3le(#const dou!le real. const dou!le imag\$ : Lreal#real\$. 3u!lic: -om3le(#\$ : Lreal#4&4\$. c = a&add#!\$. return#-om3le(#real. 1&2\$. Limag#imag\$ % -om3le( add#const -om3le( o3\$. !#1&O. An e)pression of the form c = a + !. (ort nately! C99 allo*s s to o\$erload almost all of its operators for ne*ly created types. Limag. is translated into a method call DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 30 . 3e *o ld then be able to se comple) n mbers and to --calc late&& *ith them+ -om3le( a#1&4. &&& %. 3hat *e *o ld rather li4e to se is the *ell#4no*n --9&& to e)press addition of t*o comple) n mbers. imag\$\$. -om3le( mul#const -om3le( o3\$. c. &&& In this case! *e ha'e made operator + a member of class 'omple&.

return#-om3le(#real. % In this case *e m st define access methods for the real and imaginary parts beca se the operator is defined o tside of the class&s scope.c = a&o3erator +#!\$. Therefore *e declare operator + to be a friend of class 'omple&+ class -om3le( &&& 3u!lic: &&& friend -om3le( o3erator +# const -om3le( C. It is rather defined o tside as a normal o'erloaded f nction. % return Limag. return Lreal. The first arg ment is implicitly pro'ided by the in'o4ing ob:ect 0in this case a1. (riends 3e can define f nctions or classes to be friends of a class to allo* them direct access to its pri'ate data members. (or e)ample! *e co ld define operator + in this *ay+ class -om3le( &&& 3u!lic: &&& dou!le real#\$ dou!le imag#\$ %. imag\$\$. (or e)ample! in the pre'io s section *e *o ld li4e to ha'e the f nction for operator + to ha'e access to the pri'ate data members 5real and 5imag of class 'omple&. DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 31 . % // :o need to define o3erator hereM -om3le( o3erator +#-om3le( Co31. Th s! the binary operator + only needs one arg ment. !\$. In this case! the o'erloaded operator is "t a member of a class. imag = o31&imag#\$ + o32&imag#\$. This can be done by declaring it to be a friend of class 'omple&. 8o*e'er! the operator is so closely related to the class! that it *o ld ma4e sense to allo* the operator to access the pri'ate members. -om3le( Co32\$ dou!le real = o31&real#\$ + o32&real#\$. 8o*e'er! an operator call can also be interpreted as a s al f nction call! as in c = o3erator +#a.

T&b1e /. \$. return#-om3le(#real. E'en if *e are *riting --only&& C code! it ma4es sense to se &cc to force the compiler to treat it as C99. <o ghly spea4ing! mod les consist of t*o file types+ interface descriptions and implementation files. In this t torial *e *ill se &h for header files! &cc for C99 files and &t3l for template definition files. To disting ish these types! a set of s ffi)es are sed *hen compiling C and C99 programs. "od les are implemented in separate files and *e *ill no* briefly disc ss ho* mod lari. imag\$\$. % =o sho ld not se friends 'ery often beca se they brea4 the data hiding principle in its f ndamentals. Table O. This disc ssion is based on H@IE and the G@H C99 compiler. If yo are sing other constellations the follo*ing might 'ary on yo r side.const -om3le( C %. 8o*e'er! greater pro:ects! say! a calendar program! sho ld be split into manageable pieces! often called modules. 8o* to 3rite a Program Hntil no*! *e ha'e only presented parts of or 'ery small programs *hich co ld easily be handled in one file. This is especially important for those *ho are sing integrated de'elopment en'ironments 0IDEs1! for e)ample! >orland C 99.ation is done in C and C99. imag = o31&Limag + o32&Limag. -om3le( o3erator +#const -om3le( Co31.%: E)tensions and file types.\$ sho*s some of them. If yo ha'e to se friends 'ery often it is al*ays a sign that it is time to restr ct re yo r inheritance graph. const -om3le( Co32\$ dou!le real = o31&Lreal + o32&Lreal. This simplifies combination of both! since the internal mechanism of ho* the compiler arranges names in the program differs bet*een both lang ages. DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 3% .

2.Compilation teps The compilation process ta4es &cc files! preprocess them 0remo'ing comments! add header files1 and translates them into o ject files.1: Compilation steps.cc&& is : st an e)ample name! of co rse1+ LIST OF 3ROGR45S 3r"*r&6 N". Typical s ffi)es for that file type are &o or &o!j. DESCRI3TION Gi'en that an E"PL%=EE class contains the follo*ing members+ 33 1 DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING . 3ith modern compilers both steps can be combined.out if not other specified. After s ccessf l compilation the set of ob:ect files is processed by a linker. Hnder H @IE this file is called a. (or e)ample! o r small e)ample programs can be compiled and lin4ed *ith the G@H C99 compiler as follo*s 0--e)ample. This program combine the files! add necessary libraries and creates an e)ec table. Fi*+re /. These steps are ill strated in (ig re O.

0DA 6 ?\$Q of >asic and Income Ta) 6 A/Q of the gross salary1 Yincl de Uiostream. Gi'en that an E"PL%=EE class contains the follo*ing members+ Data "embers+ EmployeeP@ mber! EmployeeP@ame! >asic! DA! IT!@etPSal "ember ( nctions+ to read data! to calc late @etPSal and to print data members 3rite a C99 program to read data on @ employees and comp te the @etPSal of each Employee.hZ Yincl de Uconio. @ote+ In the e)amination each st dent pic4s one .1) 3rite a C99 program to create a class called EEP<ESSI%@. estion from a lot of all 2? . estions.hZ class E"PL%=EE CCimplments the E"PL%=EE class 5 pri'ate+ char employeePn mberI2/J!employeePnameI2/JM float basic!DA!IT!netPsalM p blic+ 'oid <eadPData01M CCreads the employeePn mber! CC emloyeePname and basic 'oid Calc lateP@etPSalary01M CCcalc lates the net salary 'oid DisplayPData01M CCDisplays the data 7M 'oid E"PL%=EE++<eadPData01 5 co t UU [Enter the Employee @ mber and @ame[ UU endlM cin ZZ employeePn mber ZZ employeePnameM co t UU [Enter the >asic Salary[ UU endlM cin ZZ basicM 7 'oid E"PL%=EE++Calc lateP@etPSalary01 5 float GrossPSalM DA 6 0?\$\basic1C2//M GrossPSal 6 basic9DAM IT 6 0A/\GrossPSal1C2//M netPsal 6 GrossPSal#ITM 7 DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 3. Hsing appropriate member f nctions con'ert a gi'en 'alid Infi) e)pression into postfi) form. Display the infi) and postfi) e)pressions. . 1.

Define a STHDE@T class *ith HS@! @ame! and "ar4s in A tests of a s b:ect.Calc lateP@etPSalary01M EmpIiJ.hZ Yincl de Uconio. Declare an array of 2/ STHDE@T ob:ects.<eadPData01M for0i6/MiUnMi991 5 EmpIiJ.'oid E"PL%=EE++DisplayPData01 5 co t UU [Emp @ame+[ UU employeePname UU []tEmp @ mber+[ UU employeePn mberM co t UU []t @et Salary+[ UU netPsal UU endlM 7 'oid main01 5 int n!iM clrscr01M co t UU [Enter the n mber of employees+ [ M cin ZZ nM co t UU endlM E"PL%=EE EmpI2/JM co t UU [Enter employee data[ UU endlM for0i6/M iUnM i991 EmpIiJ. Print the HS@! @ame and the a'erage mar4s of all the st dents.hZ Yincl de Ustdio.DisplayPData01M 7 7 %.hZ class STHDE@T 5 pri'ate+ char HS@I2/J! @ameI2/JM float mar4s2! mar4s\$! mar4sAM CCmar4s for the three s b:ects float a'eragePmar4sM CCA'erage mar4s for the best t*o p blic+ 'oid <eadPData01M 'oid Calc latePA'erageP"ar4s01M 'oid DisplayPData01M 7M 'oid STHDE@T++<eadPData01 5 co t UU [Enter the name and HS@ + [ M DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 3- . Hsing appropriate f nctions! find the a'erage of the t*o better mar4s for each st dent. Yincl de Uiostream.

\$f]n[!a'eragePmar4s1M 7 'oid main01 5 STHDE@T st dentI2/JM clrscr01M for0int i6/MiU2/Mi991 st dentIiJ. .<eadPData01M for0i6/MiU2/Mi991 5 st dentIiJ.hZ Yincl de Umath. Yincl de Uiostream.cin ZZ @ame ZZ HS@M co t UU endlM co t UU [Enter mar4s2! mar4s\$! mar4sA + [ M cin ZZ mar4s2 ZZ mar4s\$ ZZ mar4sAM co t UU endlM 7 'oid STHDE@T++Calc latePA'erageP"ar4s01 5 int smallestM if0 0mar4s2 U mar4s\$1 KK 0mar4s2 U mar4sA1 1 a'eragePmar4s 6 0mar4s\$ 9 mar4sA1C\$M else if 0mar4s\$ U mar4sA1 a'eragePmar4s 6 0mar4s2 9 mar4sA1C\$M else a'eragePmar4s 6 0mar4s2 9 mar4s\$1C\$M 7 'oid STHDE@T++DisplayPData01 5 co t UU [HS@+[ UU HS@ UU []t @ame+[ UU @ame UU []t A'erage "ar4s+[M printf0[Q/. 3rite a C99 program to create a class called C%"PLEE and implement the follo*ing o'erloading f nctions ADD that ret rn a comple) n mber+ 0i1 ADD0a! s\$1 R *here Sa’ is an integer 0real part1 and s\$ is a comple) @ mber 0ii1 ADD0s2! s\$1 R *here s2 and s\$ are comple) n mbers.Calc latePA'erageP"ar4s01M st dentIiJ.hZ class C%"PLEE 5 pri'ate+ int a! imaginaryM p blic+ 'oid <eadPdata01M 'oid Add0C%"PLEE s2! C%"PLEE s\$1M 'oid Add0int realn m! C%"PLEE s\$1M DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 3.hZ Yincl de Uconio.DisplayPData01M 7 7 3.

imaginary1M ret rn o tM 7 'oid main01 5 C%"PLEE s2! s\$! sA! sBM clrscr01M co t UU [Addition of t*o comple) n mbers #[ UU endlM s2.imaginaryM 7 'oid C%"PLEE++Add0int realn m! C%"PLEE s\$1 5 a 6 realn m 9 s\$.imaginaryM 7 ostreamK operatorUU0ostreamK o t! C%"PLEE t1 5 o t UU t.imaginary U /1 o t UU [#i[M else o t UU [9i[M o t UU abs0t.a 9 s\$.aM imaginary 6 s2.imaginary 9 s\$.Add0realn m! s\$1M co t UU [The res ltant comple) n mber+ [M co t UU sB UU endlM 7 DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING 3/ .<eadPdata01M sA.<eadPdata01M s\$.aM imaginary 6s\$.Add0s2!s\$1M co t UU [The res ltant comple) n mber is+ [M co t UU sA UU endlM co t UU [Addition of a real n mber only#[ UU endlM co t UU [Enter the real part+ [M int realn mM cin ZZ realn mM sB.aM if0t.friend ostreamK operator UU 0ostreamK o t! C%"PLEE t1M 7M 'oid C%"PLEE++<eadPdata01 5 co t UU [Enter the real part and imaginary part+ [M cin ZZ a ZZ imaginaryM co t UU endlM 7 'oid C%"PLEE++Add0C%"PLEE s2!C%"PLEE s\$1 5 a 6 s2.

(.hZ class LIST 5 p blic+ int infoM LIST \ne)tM 7M class LI@KEDPLIST 5 LIST \headM p blic+ LI@KEDPLIST01 5 head 6 @HLLM 7 'oid Insert(01M 'oid Delete(01M 'oid DisplayPList01M 7M 'oid LI@KEDPLIST++Insert(01 5 LIST \tempM int itemM co t UU [Enter the data+ [M cin ZZ itemM co t UU endlM temp 6 ne* LISTM temp#Zinfo 6 itemM temp#Zne)t 6 @HLLM if0head 66 @HLL1 head 6 tempM else temp#Zne)t 6 headM head 6 tempM 7 'oid LI@KEDPLIST++Delete(01 5 LIST \tempM if0head 66 @HLL1 co t UU [@o data is present[ UU endlM DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING (0 .hZ Yincl de Ustring. 3rite a C99 program to create a class called LIST 0lin4ed list1 *ith member f nctions to insert an element at the front as *ell as to delete an element from the front of the list.hZ Yincl de Uconio.hZ Yincl de Uprocess. Demonstrate all the f nctions after creating a list ob:ect. Yincl de Uiostream.

Delete(01M brea4M case A + s2. Yincl de Uiostream.DisplayPList01M brea4M defa lt+ co t UU [3rong choice^[ UU endlM co t UU [Enter the choice again! *ith / to .Insert(01M brea4M case \$ + s2. 3rite a C99 program to create a template f nction for T ic4sort and demonstrate sorting of integers and do bles.else 5 temp 6 headM head 6 head#Zne)tM co t UU [The deleted data is+ [ UU temp#Zinfo UU endlM delete tempM 7 7 'oid LI@KEDPLIST++DisplayPList01 5 if0head 66 @HLL1 co t UU [@o data is present[ UU endlM else for0LIST \temp 6 headM temp ^6 @HLLM temp 6temp#Zne)t1 co t UU temp#Zinfo UU [#Z[ UU endlM 7 'oid main01 5 LI@KEDPLIST s2M clrscr01M int ch62M *hile0ch1 5 co t UU [2 InsertPfront\$ DeletePfrontA Display List/ E)it]n[M cin ZZ chM s*itch0ch1 5 case 2 + s2. it[ UU endlM cin ZZ chM 7CCend s*itch 7 CCend *hile0ch1 7CCend main01 ).hZ DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING (1 .

Yincl de Uconio.eM p blic+ THICKPS%<T0int n1 5 si.eM i991 cin ZZ aIiJM 7 templateUclass TZ 'oid THICKPS%<TUTZ++T ic40int lo*! int high1 5 int :M if0lo* U6 high1 5 : 6 Partition0lo*!high1M T ic40lo*! :#21M T ic40:92! high1M 7 7 templateUclass TZ int THICKPS%<TUTZ++Partition0int lo*! int high1 5 int i! :M T 4eyM I 6 lo* 9 2M _ 6 highM Key 6 aIlo*JM *hile021 5 *hile0I U high KK 4ey Z6 aIiJ1 i99M DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING (% .e6nM 7 'oid GetPData01M 'oid T ic40int lo*! int high1M int Partition0int lo*! int high1M 'oid DisplayPData01M 7M templateUclass TZ 'oid THICKPS%<TUTZ++GetPData01 5 co tUU[Enter the elements to be inserted[ UU endlM for0int i6/M iUsi.hZ Yincl de Uprocess.hZ template Uclass TZ class THICKPS%<T 5 pri'ate+ T aI\$/JM int lo*! high! si.

GetPData01M T2.GetPData01M DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING (3 .eM i991 co t UU [! [UUaIiJM co t UU endlM 7 'oid main01 5 int n! chM clrscr01M co tUU[Enter n mber of data+ [M cinZZnM co t UU endlM THICKPS%<TUintZT20n1M THICKPS%<TUdo bleZT\$0n1M co t UU [2.*hile04ey UaI:J1 :##M if0I U :1 5 T temp 6 aIiJM aIiJ 6 aI:JM aI:J 6 tempM 7 else 5 T temp 6 aI:JM aI:J 6 aIlo*JM aIlo*J 6 tempM ret rn :M 7 7CCend *hile 7CCend THICKPS%<TUTZ templateUclass TZ 'oid THICKPS%<TUTZ++DisplayPData01 5 int iM co t UU [The sorted list is[M for0i6/M iUsi.To sort do ble data[ UU endlM co t UU [A.DisplayPData01M brea4M case \$+ T\$. it[ UU endlM co t UU [Enter yo r choice[ UU endlM cin ZZ chM s*itch0ch1 5 case 2+ T2.To .To sort integer data [ UU endlM co t UU [\$.T ic40/!n#21M T2.

e 6 nM 7 'oid operator 90int )1M 'oid operator #01M friend ostream Koperator UU 0ostream Ko t! STACK st1M 7M 'oid STACK++operator90int )1 5 if0top 66 si.8andle the STACK empty and f ll conditions.e#21 co t UU [Stac4 is o'erflo*[ UU endlM else aI99topJ 6 )M 7 'oid STACK++operator #01 5 if0top 66 #21 co t UU [Stac4 is nderflo*[ UU endlM else co t UU [The popped element is[ UUa Itop##J UU endlM DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING (( .T\$..hZ Yincl de Uconio.DisplayPData01M brea4M 7 getch01M 7CCend main01 .T ic40/!n#21M T\$.hZ Yincl de Uprocess. Implement the follo*ing operations by o'erloading the operators S9’ and S#S+ 0i1 s2 6 s2 9 elementM *here s2 is an ob:ect of the class STACK and element is an integer to be p shed on the top of the stac4 0ii1 s2 6 s2# M *here s2 is an ob:ect of the class STACK. 3rite a C99 program to create a class called STACK sing an array of integers.e! topM p blic+ STACK0int n1 5 top 6 #2M si. Yincl de Uiostream. S#S operator pops the element.hZ class STACK 5 pri'ate+ int aI2/J! si. Also display the contents of the stac4 after each operation! by o'erloading the UU operator.

7 ostream KoperatorUU0ostream Ko t! STACK st1 5 if0st.aIiJ UU [#Z[M co t UU endlM ret rn o tM 7 'oid main01 5 int n!ch!)M clrscr01M co t UU [Enter si.top 66 #21 co t UU [Stac4 is nderflo*[ UU endlM else for0int i6st.topM iZ6/M i##1 co t UU st.e of stac4+[M cin ZZ nM STACK s20n1M *hile021 5 co t UU endl UU V2 To p sh\$ To popA To displayB To e)it[UU endlM co t UU [Enter yo r choice+[M cin ZZ chM s*itch0ch1 5 case 2+ co t UU [Enter the data to p sh+[M cin ZZ )M s29)M brea4M case \$+ #s2M brea4M case A+ co t UU [The content of stac4+[M co t UU s2M brea4M defa lt+ co t UU [Program is terminated]n[M e)it0/1M 7CCend s*itch getch01M 7CCend *hile 7CCend main DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING () .

0ii1 d\$ 6 d2 9 noPofPdaysM *here d2 is a DATE ob:ect and noPofPdays is an integer.hZ Yincl de Uprocess. 3rite a C99 program to create a class called DATE. Implement the follo*ing operations by o'erloading the operators S9’ and S#S.monthM i991 intP'al e9aIiJM intP'al e99M 7 else for0int i6/MiUD2.hZ class DATE 5 pri'ate+ int flag! day! month! yearM p blic+ DATE0int d! int m! int y1 5 day 6 d! month 6 m!year 6 yM if00yearQB1 66 /1 flag62M else flag6/M 7 int operator #0DATE D\$1M DATE operator 90int n1M friend ostream KoperatorUU0ostream Ko t!DATE D21M int ret rnPintegerPdate0DATE D21M 7M int aI2AJ65/!A2!\$L!A2!A/!A2!A/!A2!A2!A/!A2!A/!A27M int bI2AJ65/!A2!\$O!A2!A/!A2!A/!A2!A2!A/!A2!A/!A27M int DATE++ret rnPintegerPdate0DATE D21 5 int intP'al e 6 D2. 0i1 noPofPdays 6 d2 R d\$M *here d2 and d\$ are DATE ob:ects! and noPofPdays is an integer.-. Accept t*o 'alid dates in the form ddCmmCyy.After e'ery operation display the res lts by o'erloading the operator UU.monthMi991 intP'al e6intP'al e9aIiJM ret rn intP'al eM 7 int DATE++operator #0DATE D\$1 5 DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING (.hZ Yincl de Uconio.flag 66 21 KK 0D2.month Z \$11 5 for0int i 6 /M iUD2. Yincl de Uiostream.dayM if00D2. .

month 66 D\$.monthJ1 5 D.year1 ) 6 )9a2#a\$M else 5 ) 6 )9a2M if0D\$.month KK D2.day99M if0D.month99M DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING (- .month99M 7 7 else 5 D.monthJ1 5 D.flag6/M if0D.year#2M i Z D\$.year 66 D\$.day KK D2.yearQB 66 /1 5 D.flag62M if0D.day62M D.yearM i##1M 5 if0iQB 66 /1 ) 6 )9ADDM else ) 6 )9AD?M 7 if0D2.day 66 D\$.int a2! a\$!) 6 /M DATE D20day! month! year1M if0D2.day Z aID.day 6 2M D.year 66 D\$.yearQB 66 /1 ) 6 )90ADD#a\$1M else ) 6 )90AD?#a\$1M 7 ret rn )M 7 DATE DATE++operator90int n1 5 DATE D0day! month! year1M for0int i6/M iUnM i991 5 D.year1 ret rn )M a2 6 ret rnPintegerPdate0D21M a\$ 6 ret rnPintegerPdate0D\$1M for0int i 6 D2.day Z bID.

month UU [C[ UU D2.yearM ret rn o tM 7 'oid main01 5 int d! m! y! noPofPdaysM clrscr01M co t UU [Enter A0WALID1DATE]n[M co t UU [E@TE< DA= 0dd1+[M cin ZZ dM co t UU [E@TE< "%@T80mm1+[M cin ZZ mM co t UU [E@TE< =EA<0yyyy1+[M cin ZZ yM co t UU endlM DATE D20d!m!y1M co t UU [Enter another0Walid1DATE0Earlier to that entered abo'e1]n[M co t UU [E@TE< DA=0dd1+[M cin ZZ dM co t UU [E@TE< "%@T80mm1+[M cinZZmM co tUU[E@TE< =EA<0yyyy1+[M cin ZZ yM co t UU endlM DATE D\$0d!m!y1M co t UU [(irst DATE E@TE<ED+[ UU D2 UU endl UU endlM co t UU [Second DATE E@TE<ED+[ UU D\$ UU endl UU endlM noPofPdays 6 D2#D\$M co t UU[The difference bet*een the \$ days+[UUnoPofPdaysUUendlUUendlM co t UU [Enter a no.year99M 7 7 ret rn DM 7 ostream KoperatorUU0ostream Ko t!DATE D21 5 co t UU D2. .+[M cin ZZ noPofPdaysM D2 6 D\$ 9 noPofPdaysM co tUU[]n The res lting dare from the DATE[UUD\$UU[IS+[UUD2UUendlM getch01M 7 DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING (.month Z 2\$1 5 D.month62M D.7 7 if0D.day UU [C[ UU D2.

hZ Yincl de Uprocess.arrIiJI:JM ret rn "AM DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING (/ . Perform the addition and s btraction by o'erloading the 9 and R operators respecti'ely.n1M for0int i6/MiU"2. If 0m266m\$1 5 mA6m29m\$M mB6m2#m\$M 7 else display error.m!"2.n11 ret rn 2M ret rn /M 7 "AT<IE operator90"AT<IE "2!"AT<IE "\$1 5 "AT<IE "A0"2.m66"\$. Display the res lts by o'erloading the operator UU.hZ Yincl de Uconio.mMi991 for0int :6/M:U"2. Yincl de Uiostream.arrIiJI:J6"2..m1 KK 0"2.. Implement the follo*ing operations by o'erloading the operator 99 *hch chec4s the compatibility of t*o matrices to be added and s btracted.nM:991 "A.arrIiJI:J 9 "\$.n66"\$.ed constr ctor 5 m6aM n6bM 7 friend int operator660"AT<IE!"AT<IE1M friend "AT<IE operator90"AT<IE!"AT<IE1M friend "AT<IE operator#0"AT<IE!"AT<IE1M 'oid get01M friend ostreamK operatorUU0ostreamK!"AT<IE1M C\ "AT<IE operator60"AT<IE r1M\C 7M CCend of class defn int operator660"AT<IE "2!"AT<IE "\$1 5 if00"2.hZ class "AT<IE 5 int m! nM int arrI\$/JI\$/JM p blic+ "AT<IE0int a! int b 1 CCparametri. 3rite a C99 program to create a class called "AT<IE sing t*odimensional array of integers.

arrIiJI:J6"2.arrIiJI:JM ret rn "AM 7 'oid "AT<IE++get01 5 for0int i6/MiUmMi991 for0int :6/M:UnM:991 5 co tUU[Enter the element at ro* [UUi92UU[ and col mn[UU:92UU[ +[M cinZZarrIiJI:JM 7 7 ostreamK operatorUU0ostreamK o t!"AT<IE s1 5 for0int i6/MiUs.7 "AT<IE operator#0"AT<IE "2!"AT<IE "\$1 5 "AT<IE "A0"2.0c!d1!r0a!b1M co tUU[Enter "atri) A+[UUendlM p..arrIiJI:J # "\$.nM:991 o tUUs.mMi991 for0int :6/M:U"2.n1M for0int i6/MiU"2.arrIiJI:JUU[ [M o tUUendlM 7 ret rn o tM 7 int main01 5 int a!b!c!d!chM clrscr01M co tUU[Enter the n mber of ro*s in matri) A+[M cinZZaM co tUU[Enter the n mber of col mns in matri) A+[M cinZZbM co tUU[Enter the n mber of ro*s in matri) >+[M cinZZcM co tUU[Enter the n mber of col mns in matri) >+[M cinZZdM "AT<IE p0a!b1!.nM:991 "A.get01M co tUU[Enter "atri) >+[UUendlM .m!"2.get01M lblmen + co tUU[21 Add \$1 S btract A1 T it +[M DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING )0 .mMi991 5 for0int :6/M:Us.

hZ Yincl de Umath.cinZZchM if0chU2 `` chZA1 goto lblmen M if0ch6621 5 if0p66. Yincl de Uiostream.1M co tUUrM 7 else co tUU[Cant s btract.M co tUUrM 7 else co tUU[Cant add.[UUendlM 7 if0ch66A1 5 e)it0/1M 7 goto lblmen M 7 /.hZ class octal 5 pri'ate+ int oM p blic+ octal01M octal0int1M Noctal01M DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING )1 .hZ Yincl de Uconio. Also display the 'al es of h and y.[UUendlM 7 if0ch66\$1 5 if0p66. Implement the follo*ing operations by *riting an appropriate constr ctor and an o'erloaded operator 9. 0ii1 int y 6 h 9 4M *here h is an %CTAL ob:ect and 4 is an integer Display the %CTAL res lt by o'erloading the operator UU . 3rite a C99 program to create a class called %CTAL *hich has the characteristics of an octal n mber.1 5 r6p9.1 5 r60p#. 0i1 %CTAL h 6 )M *here ) is an integer.

int dectooct0int )1M int octtodec0int )1M friend ostream KoperatorUU0ostream Kprint!octal1M int operator 90int1M 7M octal++octal01 5 7 octal++octal0int )1 5 o6dectooct0)1M 7 octal++Noctal01 5 7 int octal++dectooct0int )1 5 int i6/!s m6/!remM *hile0)^6/1 5 rem6)QLM s m6s m9rem\po*02/!i1M i99M )6)CLM 7 ret rn s mM 7 int octal++octtodec0int )1 5 int i6/!s m6/!remM *hile0)^6/1 5 rem6)Q2/M s m6s m9rem\po*0L!i1M i99M )6)C2/M 7 ret rn s mM 7 ostream KoperatorUU0ostream Kprint!octal )1 5 printUU).oM ret rn printM 7 int octal++operator90int )1 5 ret rn octtodec0o19)M DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING )% .

Demonstrate the operations by displaying the contents of the . e e01 5 f6#2M r6#2M 7 DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING )3 .7 main01 5 clrscr01M int )!y!4M co tUUendlUU[Enter the 'al e of ) in decimal notation+[M cinZZ)M octal h0)1M co tUUendlUU[Corresponding 'al e of ) in octal notation!h6[UUhM co tUUendlUU[Enter the 'al e of 4 in decimal notation+[M cinZZ4M co tUU[The 'al e of 46[UU4M y6h94M co tUUendlUU[The 'al e of h94 in decimal notation!y6[UUyM getch01M ret rn /M 7 10.eJM int f!rM p blic+ . 3rite a C99 program to create a class called THEHE *ith member f nctions to add an element and to delete an element from the .e A templateUclass tZ class . e e.hZ Yincl de Uconio. Yincl de Uiostream. e e01M N.hZ Ydefine si. e e 5 pri'ate+ t aIsi. e eUtZ++.hZ Yincl de Uiomanip. e e of integers and do ble. e e after e'ery operation. e e01M 'oid add01M 'oid del01M 'oid dis01M 7M templateUclass tZ . Hsing the member f nctions! implement a .

e eUintZ. e eUtZ++dis01 5 if0f66#21 co tUUendlUU[. e eUtZ++add01 5 if0r66si.e#21 co tUUendlUU[. e eUtZ++N. e e01 5 7 templateUclass tZ 'oid . e eUtZ++del01 5 if0f66#21 co tUUendlUU[. e e is empty[M else 5 co tUUendlUU[Content of .M DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING )( . e e+[UUendlM for0int i6fMiU6rMi991 co tUUset*0?1UUaIiJM 7 7 templateUclass tZ 'oid . e e is f ll[M else 5 r99M co tUUendlUU[Enter the data+[M cinZZaIrJM if0f66#21 f6/M 7 7 templateUclass tZ 'oid . e e is empty[M else 5 co tUUendlUU[Deleted element is[UUaIfJM if0f66r1 f6r6#2M else f6f92M 7 7 main01 5 .templateUclass tZ .

add01M .. e e+[M co tUUendlUU[Enter / to .int ch62M clrscr01M *hile0ch1 5 co tUUendlUU[Enter 2 to add a data to . it+[M co tUUendlUU[Enter yo r choice+[M cinZZchM s*itch0ch1 5 case 2+ .hZ Yincl de Ustdlib. e e+[M co tUUendlUU[Enter \$ to delete a data from the .del01M . 3rite a C99 program to create a class called DLIST 0do bly Lin4ed List1 *ith member f nctions to insert a node at a specified position and delete a node from a specified position of the list. Demonstrate the operations by displaying the content of the list after e'ery operation..dis01M brea4M case \$+ .dis01M brea4M 7 7 getch01M ret rn /M 7 11.hZ str ct node 5 int dataM node \llin4!\rlin4M 7M class dlist 5 pri'ate+ str ct node \headM p blic+ dlist01M DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING )) .hZ Yincl de Uconio. Yincl de Uiostream.hZ Yincl de Uiomanip...

.Ndlist01M 'oid create01M 'oid addatpos01M 'oid delatpos01M 'oid dis01M 7M dlist++dlist01 5 head6@HLLM 7 dlist++Ndlist01 5 delete headM 7 'oid dlist++create01 5 int no!iM str ct node \nM co tUUendlUU[Enter n mber of elements+[M cinZZnoM for0i62MiU6noMi991 5 n6ne* nodeM n#Zrlin46@HLLM n#Zllin46@HLLM co tUUendlUU[Enter the data+[M cinZZn#ZdataM if0head66@HLL1 head6nM else 5 n#Zrlin46headM head#Zllin46nM head6nM 7 7 ret rnM 7 'oid dlist++addatpos01 5 str ct node \nM int pM co tUUendlUU[Enter position+[M cinZZpM n6ne* nodeM n#Zllin46@HLLM n#Zrlin46@HLLM DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING ).

co tUUendlUU[Enter data+[M cinZZn#ZdataM if0p6621 5 n#Zrlin46headM head#Zllin46nM head6nM 7 else 5 int i62M str ct node \tM t6headM *hile0iU6p#\$1 5 t6t#Zrlin4M i99M 7 n#Zrlin46t#Zrlin4M t#Zrlin4#Zllin46nM n#Zllin46tM t#Zrlin46nM 7 ret rnM 7 'oid dlist++delatpos01 5 str ct node \tM int i!pM co tUUendlUU[Enter position+[M cinZZpM if0p6621 5 head6head#Zrlin4M head#Zllin46@HLLM ret rnM 7 t6headM i62M *hile0iUpKKt^6@HLL1 5 t6t#Zrlin4M i99M 7 if0t#Zrlin466@HLL1 t#Zllin4#Zrlin46@HLLM else DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING )- .

5 t#Zllin4#Zrlin46t#Zrlin4M t#Zrlin4#Zllin46t#Zllin4M 7 ret rnM 7 'oid dlist++dis01 5 str ct node \tM t6headM if0t66@HLL1 co tUUendlUU[Empty list+[M else 5 co tUUendlUU[Content of the list[UUendlM *hile0t^6@HLL1 5 co tUUset*0?1UUt#ZdataM t6t#Zrlin4M 7 7 ret rnM 7 main01 5 dlist dM int ch62M clrscr01M *hile0ch1 5 co tUUendlUU[Enter 2 to create do ble lin4ed list+[M co tUUendlUU[Enter \$ to add element at position+[M co tUUendlUU[Enter A to delete an element at a position+[M co tUUendlUU[Enter / to , it+[M co tUUendlUU[Enter yo r choice+[M cinZZchM s*itch0ch1 5 case 2+ d.create01M d.dis01M brea4M case \$+ d.addatpos01M d.dis01M brea4M case A+ DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING ).

d.delatpos01M d.dis01M brea4M 7 7 getch01M ret rn /M 7

1%. 3rite a C99 program to create a class called STHDE@T *ith data members HS@!
@ame and Age. Hsing inheritance! create the classes HGSTHDE@T and PGSTHDE@T ha'ing fields as Semester! (ees and Stipend. Enter the data for at least ? st dents. (ind the semester#*ise a'erage age for all HG and PG st dents separately.

Yincl deUiostream.hZ Yincl deUiomanip.hZ Yincl deUconio.hZ class st dent 5 pri'ate+ char nameI\$/JM int reg!ageM p blic+ st dent01M Nst dent01M 'oid getsdata01M int gi'eage01M 7M st dent++st dent01 5 7 st dent++Nst dent01 5 7 int st dent++gi'eage01 5 ret rn ageM 7 'oid st dent++getsdata01 5 co tUUendlUU[@ame+[M cinZZnameM co tUU[<eg.@o.+[M DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING )/

cinZZregM co tUU[Age+[M cinZZageM 7 class gst dent+p blic st dent 5 pri'ate+ int sem!fee!stiM p blic+ gst dent01M N gst dent01M 'oid get gdata01M int gi'esem01M 7M gst dent++ gst dent01 5 7 gst dent++N gst dent01 5 7 'oid gst dent++get gdata01 5 getsdata01M co tUU[Semester+[M cinZZsemM co tUU[(ee+[M cinZZfeeM co tUU[Stipend+[M cinZZstiM 7 int gst dent++gi'esem01 5 ret rn semM 7 class pgst dent+p blic st dent 5 pri'ate+ int sem!fee!stiM p blic+ pgst dent01M Npgst dent01M 'oid getpgdata01M int gi'esem01M 7M pgst dent++pgst dent01 5 7 DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING ,0

gi'esem0166s1 5 s m6s m9 IiJ.pgst dent++Npgst dent01 5 7 'oid pgst dent++getpgdata01 5 st dent++getsdata01M co tUU[Semester+[M cinZZsemM co tUU[(ee+[M cinZZfeeM co tUU[Stipend+[M cinZZstiM 7 int pgst dent++gi'esem01 5 ret rn semM 7 main01 5 gst dent I2/JM pgst dent pI2/JM int i!nM clrscr01M co tUUendlUU[Enter n mber of st dents+[M cinZZnM for0i62MiU6nMi991 5 co tUUendlUU[Enter the details of HG st dent[UUiUUendlM IiJ.gi'eage01M flag62M co 99M 7 if0flag6621 co tUUendlUUsUU[Semester[UU[a'erage age is[UUs mCco M 7 for0i62MiU6nMi991 5 co tUUendlUU[Enter thge details of PG st dent[UUiUUendlM DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING .1 .get gdata01M 7 for0int s62MsU6LMs991 5 float s m6/M int flag6/!co 6/M for0i62MiU6nMi991 if0 IiJ.

0i1 ST<I@G s2 6 VWTHX 0ii1 ST<I@G s\$ 6 V>ELGAH"X 0iii1 ST<I@G sA 6 s2 9 s\$ 0Hse copy constr ctor1 Yincl deUiostream. 3rite a C99 program to create a class called ST<I@G and implement the follo*ing operations.hZ Yincl deUconio.pIiJ.gi'eage01M flag62M co 99M 7 if0flag6621 co tUUendlUUsUU[Semester[UU[a'erage age is[UUs mCco M 7 getch01M ret rn /M 7 13.hZ Yincl deUstring.hZ class string 5 pri'ate+ char sI\$/JM p blic+ string01M Nstring01M string0char )IJ1M string0string K )1M friend string operator90string s2!string s\$1M friend ostream K operatorUU0ostream Kprint!string )1M 7M string++string01 5 7 string++string0char )IJ1 DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING . Display the res lts after e'ery operation by o'erloading the operator UU.getpgdata01M 7 for0s62MsU6LMs991 5 float s m6/M int flag6/!co 6/M for0i62MiU6nMi991 if0pIiJ.gi'esem0166s1 5 s m6s m9pIiJ.% .

3 . Create a >I@PT<EE ob:ect and demonstrate the tra'ersals.5 strcpy0s!)1M 7 string++string0string K )1 5 strcpy0s!).hZ Yincl deUconio.hZ str ct node 5 DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING .s1M ret rn tempM 7 ostream K operatorUU0ostream K print!string )1 5 printUU).hZ Yincl deUstdlib. Yincl deUiostream.s1M 7 string++Nstring01 5 7 string operator90string s2!string s\$1 5 string temp0s21M strcat0temp.sUUendlM ret rn printM 7 main01 5 clrscr01M string s26[WTH[M co tUUendlUU[(irst string is[UUs2M string s\$6[>ELAGAH"[M co tUUendlUU[Second string is[UUs\$M string sA6s29s\$M co tUUendlUU[<es ltant string is[UUsAM getch01M ret rn /M 7 1(. 3rite a C99 program to create a class called >I@PT<EE 0>inary Tree1 *ith member f nctions to perform in#order! preorder and post#order tra'ersals.hZ Yincl deUiomanip.s!s\$.

( .int dataM node\llin4!\rlin4M 7M class btree 5 pri'ate+ node\rootM p blic+ btree01M Nbtree01M str ct node\create01M 'oid inorder0node \root1M 'oid preorder0node \root1M 'oid postorder0node \root1M 7M btree++btree01 5 root6@HLLM 7 btree++Nbtree01 5 delete rootM 7 node \btree++create01 5 node \n!\f!\cM int i!noM co tUUendlUU[Enter member of elements in the tree+[M cinZZnoM for0i62MiU6noMi991 5 n6ne* nodeM n#Zllin46@HLLM n#Zrlin46@HLLM co tUUendlUU[Enter the data+[M cinZZn#ZdataM if0root66@HLL1 root6nM else 5 f6rootM c6rootM *hile0c^6@HLL1 5 f6cM if0n#ZdataUc#Zdata1 c6c#Zllin4M DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING .

create01M co tUUendlUU[Inorder tra'ersal+[UUendlM b.else c6c#Zrlin4M 7 if0n#ZdataUf#Zdata1 f#Zllin46nM else f#Zrlin46nM 7 7 ret rn rootM 7 'oid btree++inorder0str ct node \root1 5 if0root^6@HLL1 5 inorder0root#Zllin41M co tUUroot#ZdataUUset*0?1M inorder0root#Zrlin41M 7 7 'oid btree++preorder0str ct node \root1 5 if0root^6@HLL1 5 co tUUroot#ZdataUUset*0?1M preorder0root#Zllin41M preorder0root#Zrlin41M 7 7 'oid btree++postorder0str ct node \root1 5 if0root^6@HLL1 5 postorder0root#Zllin41M postorder0root#Zrlin41M co tUUroot#ZdataUUset*0?1M 7 7 main01 5 clrscr01M btree bM str ct node \rootM root6b.inorder0root1M co tUUendlUU[Preorder tra'ersal+[UUendlM DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING .) .

postorder0root1M getch01M ret rn /M 7 1). .preorder0root1M co tUUendlUU[Postorder tra'ersal+[UUendlM b. Hsing appropriate member f nctions con'ert a gi'en 'alid Infi) e)pression into postfi) form. Display the infi) and postfi) e)pressions.hZ class e)pression 5 pri'ate+ char infi)I\$/J!postfi)I\$/J!stac4I\$/JM int topM p blic+ e)pression01M e)pression0char sI\$/J1M Ne)pression01M 'oid p sh0char ch1M char pop01M int priority0char ch1M 'oid infi)topostfi)01M 'oid dis01M 7M e)pression++e)pression01 5 top6#2M 7 e)pression++e)pression0char sI\$/J1 5 strcpy0infi)!s1M top6#2M 7 e)pression++Ne)pression01 5 7 DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING . Yincl deUiostream..hZ Yincl deUctype.hZ Yincl deUstring.hZ Yincl deUconio.b. 3rite a C99 program to create a class called EEP<ESSI%@.

- .'oid e)pression++p sh0char ch1 5 top6top92M stac4ItopJ6chM 7 char e)pression++pop01 5 char chM ch6stac4ItopJM top6top#2M ret rn chM 7 int e)pression++priority0char ch1 5 int pM s*itch0ch1 5 case&C&+ case&###BOT_TEXT###amp;+ p6\$M brea4M case&9&+ case&P&+ p62M brea4M case&0&+ p6/M brea4M case&Y&+ p6#2M brea4M 7 ret rn pM 7 'oid e)pression++infi)topostfi)01 5 int i!pM char chM i6/M p6/M p sh0&Y&1M *hile0infi)IiJ^6&]/&1 5 ch6infi)IiJM s*itch0ch1 5 case&0&+ DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING .

.p sh0ch1M brea4M case&1&+ *hile0stac4ItopJ^6&0&1 5 postfi)IpJ6pop01M p6p92M 7 pop01M brea4M case&###BOT_TEXT###amp;+ case&C&+ case&9&+ case&#&+ *hile0priority0stac4ItopJ1Z6priority0ch11 5 postfi)IpJ6pop01M p6p92M 7 p sh0ch1M brea4M defa lt+ postfi)IpJ6chM p6p92M 7 i6i92M 7 *hile0stac4ItopJ^6&Y&1 5 postfi)IpJ6pop01M p6p92M 7 postfi)IpJ6&]/&M ret rnM 7 'oid e)pression++dis01 5 co tUUpostfi)M 7 main01 5 char sI\$/JM clrscr01M co tUUendlUU[Enter a 'alid infi) e)pression+[M cinZZsM e)pression e)0s1M e). .infi)topostfi)01M DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING .

co tUU[Con'erted postfi) e)pression+[M e).dis01M getch01M ret rn /M 7 DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING ./ .