Introduction to the language C++, (Part 1) During this session you will learn about: Basc data types. Ouafers. Varabes decaraton and defnton and usage. Recursve functon. Scope rues and Storage specfer - automatc, statc, externa, regster. Contro fow Branchng and Loopng statements. The break and contnue statements. The C anguage has, over the past few years, became one of the most popuar programmng anguage. Ths rapd popuarty, amongst other reasons, can be attrbuted to the sheer power and smpcty of the anguages. The C++ became st popuar because t mantans the smpcty of the C Programmng anguage and aso makes t more powerfu by supportng the Ob|ect Orented Programmng concepts. Ths chapter ntroduces severa features of these anguages. If you aready know C or even f you have not earnt the anguage earer, ths chapter prepares you to expore the anguage C++. 1.1.Literals (Constants) Constants are data storage locations whose address is not accessible for the user. Ther vaue s not changed durng the course of the program. Ltera constant : represented by ther vaue. Symboc constants : represented by ther symbos / names.
e.g. sum = num1 + 10;
// 10 s a tera constant. 120 // sum s a symboc constant. Constants as we as varabes have types assocated wth them. The foowng tabe summarzes the data types , ther szes and ther range, for a 16-bt machne. Type Sze n Bytes Range Unsgned short nt. 2 0 to 65,535 Short nt. 2 -32,768 to 32767 Unsgned ong nt. 4 0 to 4,294,967,295 Long nt. 4 -2,147,483,648 to 2,147,483,647 nt. 2 -32,768 to 32,767 Unsgned nt. 2 0 to 65,535 Char 1 256 character vaues Foat 4 1.2e-308 to 3.4e38 Doube 8 2.2e-308 to 1.8e308 1.2. Integer literal Integer are numbers wthout fractona parts. e.g. 20 // Decma 024 // Octa 0x14 // Hexadecma To denote ong, unsgned, suffxes such as L, U, , u can be used. e.g. 128U, 1028u, 1L, 8LU, 71( 71 and sma L) . 1.3. Floating literal They can be wrtten n common decimal as we as scientific notation( floating point representation). By default it is of type double. F, L are apped ony to common decma notaton. 121 e.g. 3.1415F , 1.0E-3, 12.345L, 2. , 3E1, 1.0L 1.. !oolean constants It can hod 2 vaues true(1) or fase(0). 1.". Character literal Character teras are characters , dgts and some speca symbos, whch are encosed n snge quotes and requre a snge byte of memory. e.g. a, 2, ., (bank) -uses a byte. 1.#. S$ecial Character set ( %sca$e Se&uences)' When norma characters are preceded wth a \ (back sash) , they work n a dfferent way. These are caed escape sequences. e.g. \n new ne \t horzonta tab \v vertca tab \" doube quotes. They can aso be represented usng tera constants . e.g. \14 nstead of \n for newne. 1.(. String literal' An array of constant characters s represented as strngs. 122 Zero or more characters are represented wthn doube quotaton marks. These are termnated by a nu character. The comper does ths. e.g. " " -- nu strng "a" "\ncc\toptons\tfe.|cc|\n" " a mutne \ strng tera sgnas ts \ contnuaton wth a backsash" 1.). *ualifiers A varabes by defaut are sgned ( the sgn bt s aso stored as a part of the number ). If t s known beforehand that the vaue of a varabe w not be sgned, then the keyword unsigned can precede a varabe, thus decarng t an unsgned varabe. Ths s caed as a qualifier. e.g. unsgned nt num = 341; unsgned arr = 20; Note that n the second exampe the data type s omtted, n whch case t defauts to beng an nteger. There are many occasons when vaues to be stored n the varabe exceeds the storage space aocated to them. For nstance, an nteger on a 16-bt processor s aocated 2 bytes, whch can store at the most 65535, f the varabe s unsgned. If a bgger number s to be stored n a varabe , then the quafer long can be used. e.g. ong nt num = 1234354; 123 ong emp = 1234321L; unsgned ong nt unum = 0; unsgned ong unum; Note that the two quafers wth one varabe decaraton can aso be gven. In ths case the ast two varabes can have doube the amount of storage and are unsgned. Aso note that the etter L or succeeds ong constants. Smary, there s another quafer short, whch gves storage equa to, or ess than an nteger, dependng upon the mpementaton. e.g. short nt ; Some mpementatons have the quafer signed. A the varabes by defaut are sgned, therefore ths quafer s not of much use. 1.+. ,aria-les Informaton stored n a varabe can change n the course of the program. The type used n the defnton descrbes the knd of nformaton the symbo can store. Variables are addressable. 1.1.. /ules for naming the 0aria-les' Can have characters, dgts and underscore. Can start wth character or underscore. Are case senstve .e., fan s dfferent from Fan and FAN. Cant use keywords No mts on the ength of the word. e.g. nt poode // Vad nt my_stud // Vad nt _mystud // Vad 124 nt 4ever // Invad starts wth number nt doube // Invad keyword nt Honk-Kong // Invad (dash) not aowed as t // s a speca character. Varabes hep us to reuse the codes. To fnd the vaue of power of some number we may wrte, e.g. To fnd the vaue of power of some number we may wrte, cout << 2*2*2*2*2*2*2*2*2*2 for 28. /* cout s equvaent to prntf() n C. It prnts the teras or vaues of varabes.*/
If we want to fnd the power of some number or f we want to change the number we have to type the whoe sentence agan. We can generaze ths operaton by usng 2 varabes as foows. e.g.
nt va = 4, pow =10, cnt ; for ( cnt =1; cnt <= pow; ++cnt ) { res = res*va; } Ths s fexbe compared to prevous method but not reusabe. By usng functons we can make them reusabe too. e.g. nt pow( nt va , nt exp ) { for ( res =1 ; exp>0 ; --exp ) { res = res * va; return res; } } You can ca ths functon any number of tmes wth dfferent arguments. ,aria-les can alternati0el1 -e called as 2-3ects. 125 There are two terms associated with a variable : 1. r-vaue ( read vaue) : Data. Ths can be a tera or varabe name. 2. -vaue (ocaton vaue) : Address n the memory ocaton where data s stored. e.g. ch = ch1 - 0; where ch s -vaue,ch1 s r-vaue symbo,0 s r-vaue tera. You can have the same symbo n both -vaue and r-vaue. e.g. ch = ch - 0; 0 = 1; // Error, cannot have a tera as -vaue.
saary + extra = newsa // Error, vaue must be an // addressabe varabe and not an expresson. Ob|ects or varabes can have ony a snge ocaton. So, they cant be defned twce. However, they can be decared twce. Defnton sets memory asde for a varabe where as decaraton |ust nforms the comper that ths varabe s defned somewhere n the program. Some varabes may be needed n two or more fes. In such cases we can defne t n one fe and decare t n a the fes that use ths varabe. e.g. // fe feno1.cpp strng fename; ' ' // fe feno2.cpp extern strng fename; ' 126 ' The keyword etern nforms the comper that the fename s defned somewhere outsde the exstng fe. If you need to decare many varabes n dfferent fes you can decare once n a header fe and ncude t n fes where the decaratons are needed. 1.11. 4he definition of an o-3ect(0aria-le )' We can defne a varabe(set memory to the varabe) n the foowng ways. e.g. doube saary; nt month; When more than one varabe of same type are needed a comma can be used to decare mutpe varabes. e.g. doube sa , wage; nt m , d , y , k , a ; // Can span mutne too. If the varabes are decared gobay, they are ntazed to zero by defaut constructors( functons that are used to ntaze the varabes) that are nbut . If they are decared ocay we have to ntaze them as they may have some |unk vaue stored n them. e.g. nt x; // Goba , ntazed to zero. vod man() { nt ; // Loca , not ntazed; } You can initialize the variables in the following ways. e.g. 127 nt va =100; nt va(100); doube sa =10.0, wage = sa + 10; nt mon = 06, day = 19, year =1975; In C++, speca constructors are nbut that support ntazaton. e.g. nt va = nt(); // Sets va = 0 ; doube dva = doube() ; // Sets dva to 0.0;
An ob|ect can be ntazed wth an arbtrary compex expresson. e.g. doube pr =199.99. dsc = 0.16; doube sae( pr * dsc ); 1.12. /ecursi0e Functions Recurson s a process by whch a functon nvokes tsef wth a condton for ts safe ext. It s best sutabe for a recursve probem. A typca exampe s the factora probem, the programs wthout and wth recursve functons are shown beow. vod man() { ong factora ( nt num); // Forward decaraton of //a functon nt num; prntf("\n Enter a number:"); scanf("5d",&num); prntf(" Factora of 5d s %d",num,factora(num)); } ong factora(nt num) // Non recursve { ong f=1; 128 whe ( n) { f = f * n; n--; } return(f); } ong factora(nt num) // Recursve { f(n == 1) return (1); ese return( n* factora(n-1)); } 1.13. Sco$e /ules and Storage Classes The storage cass determnes the fe of a varabe n terms of ts duraton or ts scope. There are four storage casses : automatc statc externa regster 1.13.1 5utomatic ,aria-les Automatc varabes are varabe whch are defned wthn the functons. They ose ther vaue when the functon termnates. It can be accessed ony n that functon. A varabes when decared wthn the functon are , by defaut, are automatc. However, we can expcty decare them by usng the keyword !automatic". e.g. vod prnt() { auto nt =0; cout << " Vaue of before ncrementng s :<< ; = + 10; 129 cout <<"\n"<< " Vaue of after ncrementng s :<<; } vod man() { prnt(); prnt(); prnt(); } Output: Vaue of before ncrementng s : 0 Vaue of after ncrementng s : 10 Vaue of before ncrementng s : 0 Vaue of after ncrementng s : 10 Vaue of before ncrementng s : 0 Vaue of after ncrementng s : 10 1.13.2. Static ,aria-les Statc varabes have the same scope s automatc varabes, but , unke automatc varabes, statc varabes retan ther vaues over number of functon cas. The fe of a statc varabe starts, when the frst tme the functon n whch t s decared, s executed and t remans n exstence, t the program termnates. They are decared wth the keyword static. e.g. vod prnt() { statc nt =0; cout << " Vaue of before ncrementng s :<< ; = + 10; cout <<"\n"<< " Vaue of after ncrementng s :<<; } vod man() { prnt(); prnt(); prnt(); 130 } Output: Vaue of before ncrementng s : 0 Vaue of after ncrementng s : 10 Vaue of before ncrementng s : 10 Vaue of after ncrementng s : 20 Vaue of before ncrementng s : 20 Vaue of after ncrementng s : 30 It can be seen from the above exampe that the vaue of the varabe s retaned when the functon s caed agan. It s aocated memory and s ntazed ony for the frst tme. 1.13.3. %6ternal ,aria-les Dfferent functons of the same program can be wrtten n dfferent source fes and can be comped together. The scope of a goba varabe s not mted to any one functon , but s extended to a the functons that are defned after t s decared. However, the scope of a goba varabe s mted to ony those functons, whch are n the same fe scope. If we want to use a varabe defned n another fe, we can use etern to decare them. e.g. // FILE 1 g s goba and can be used ony n man() and // // fn1(); nt g = 0; vod man() { : : } vod fn1() { : : }
131 // FILE 2 If the varabe decared n fe 1 s requred to be used n fe 2 then t s to be decared as an extern. extern nt g = 0; vod fn2() { : : } vod fn3() { : } 1.13.. /egister ,aria-le Computers have nterna regsters, whch are used to store data temporary, before any operaton can be performed. Intermedate resuts of the cacuatons are aso stored n regsters. Operatons can be performed on the data stored n regsters more qucky than on the data stored n memory. Ths s because the regsters are a part of the processor tsef. If a partcuar varabe s used often for nstance, the contro varabe n a oop, can be assgned a regster, rather than a varabe . Ths s done usng the keyword register. However, a regster s assgned by the comper ony f t s free, otherwse t s taken as automatc. Aso, goba varabes cannot be regster varabes. e.g. vod oopfn() { regster nt ; for(=0; < 100; ++) { cout << ; } } 132 1.1. 2$erators The varabes, whch are decared and defned, are the operands, whch are operated upon by the operators. Operators specfy what operatons are to be performed on the operands. The anguage offers a range of operators, rangng from arthmetc, reatona and ogca operators to bt-wse ogca , compound assgnment and shft operators. 1.1.1. 5ssignment 2$erators The equa (=) sgn s used for assgnng a vaue to another. The eft hand sde has to be a varabe (vaue, whch excudes constants, expressons, functons etc.). e.g. x = 10; y = x; 1.1.2. 5rithmetic 2$erators We can cassfy the arthmetc operators as UNARY and BINARY operators. 1.1.2.1. 7nar1 2$erators Unary operators are those, whch operate on a snge operand. 7nar1 8inus 2$erator( 9egation) Ths operand can be used to negate the vaue of a varabe. It s aso used to specfy a negatve number, here a mnus(-) sgn s prefxed to the number. e.g. nt x = 5; nt z = -10; 133 y = -x; a = z; The vaue of y now becomes 5 and 'a' becomes -10. However, the anguage does not offer any unary + operator. Increment and :ecrement 2$erators. The operator for ncrement s ++ and decrement s -. These operators ncrease or decrease the vaue of a varabe on whch they are operated, by one(1). They can be used as prefx or postfx to the varabe, and ther meanng changes dependng on ther usage. When used as prefx, the vaue of the varabe s ncremented/ decremented before usng the expresson. But when used as postfx, ts vaue s frst used and then the vaue s ncremented or decremented. e.g. --x; x--; In the above exampe t does not matter whether the decrement operator s prefxed or suffxed. It w produce the same resut. However, n the foowng exampe t does make a dfference : nt a =0, b=10; a = ++b; s dfferent from a=b++; In the frst case, the vaue of a after the executon of ths statement w be 11, snce b s ncremented and then assgned. In the second case, the vaue of a w be 10 , snce t s assgned frst and then ncremented. The vaue of b n both the cases w be 11. The unary operators have a hgher precedence than the bnary arthmetc operators. 1.1.2.2. !inar1 2$erators
There are fve bnary operators. These operators, requre two operands. 134 + for addton. - for subtracton. * fro mutpcaton. / for dvson . % for moduus. e.g. z = x + y; f = 10 / 3; f = 10 % s; x = a + b c / d * e; x = ((a + (b c) / d )* e; The second exampe w gve the quotent of 10 dvded by 3, where as the thrd exampe w gve the remander after dvson. The expressons n the fourth exampe s evauated accordng to the precedence of operators, whch s as foows: %, /, * on the same eve, evauated from eft to rght. +, - on the same eve, evauated from eft to rght. Arthmetc expressons can aso contan parenthess to overrde the precedence, as shown n the ast exampe. 1.1.3. Com$ound 5ssignment 2$erators Apart from the bnary and the unary arthmetc operators, we aso have compound assgnment operators. These are +=, -=, *=, /=, %=. Usng these operators, the expresson x = x + 5; can aso be wrtten as x += 5; Ths heps n wrtng compact code. 1.1.. /elational 2$erators A reatona operator s used to make comparson between two vaues. A these operators are bnary and requre two operands. There are the foowng reatona operators : 135 == equa to != not equa to > greater than >= greater than or equa to < ess than <= ess than or equa to e.g. number < 6 ch != a tota == 1000 Note that no space s gven between the symbos. A these operators have equa precedence amongst themseves and a ower precedence than the arthmetc operators. 1.1.". Logical 2$erators We say any expresson that evauates to zero s a FALSE ogc condton and that evauatng to non-zero vaue s a TRUE condton. Logca operators are usefu n combnng one or more condtons. The foowng are the ogca operators : && AND || OR ! NOT The frst two operators are bnary, whereas the excamaton(!) s a unary operator. It s used to negate the condton. e.g. x<0 && y>10 evauates to true f both condtons are true x < 0 || z = = 0 evauates to true, f one of the condtons s true !(x == 0) evauates to true f condton s fase. The unary negaton operator(!) has a hgher precedence amongst the these, foowed by the and (&&) operator and then the or(||) operator, and are evauated from eft to rght. 136 1.1.#. !it;<ise 2$erators Some appcatons requre operatons to be done on dfferent bts of a byte separatey. Bt-wse operators offer a facty to do |ust that. There are severa bt-wse operators : 7nar1 2$erator ' 2ne=s Com$lement 2$erator(>) Ths operator s a unary operator that causes the bts of ts operand to be nverted, .e. 1 becomes 0 and 0 becomes 1. for nstance, to see the argest possbe number, whch can be stored n an unsgned nteger, a zero can be assgned to t. A the bts n ths word w be zeros. When the ones compement operator s used on ths word, a the bts w be nverted to ones, gvng the argest possbe number. The program to show ths converson s beow : man() { unsgned u = 0; prntf("Vaue before converson : %d\n",u); u = -u; prntf("Vaue After converson : %d\n",u); } !inar1 logical -it;<ise o$erators There are three ogca bt-wse operators : & and | or excusve or These are bnary operators. The operatons are carred out ndependenty on each par of the correspondng bts of the operands. .e. the bt 1 of operand 1 s ogcay operated wth the bt 1 of operand 2. the operatons of these operators are summarzed n the foowng tabe: 137 BIT1 BIT2 BIT1 & BIT1 BIT1 | BIT2 BIT1 BIT2 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 e.g. char x, y, z, a, b; a = 0x01; /* 0000 0001 */ b = 0x05; /* 0000 0101 */ x = a & b; y = a b; z = a | b; x &= y; y |= z; The resut of x s 0x01, snce a = 0 0 0 0 0 0 0 1 & & & & & & & & b = 0 0 0 0 0 1 0 1 x = 0 0 0 0 0 0 0 1 1.1.(. 4he Shift 2$erators There are two shft operators : eft shft ( <<) and rght shft (>>). These are bnary operators. The format s operand >> number or operand << number The frst operand s the vaue, whch s to be shfted. The second s the number of bts by whch t s shfted. The eft shft operators shft number bts to the eft, whereas the rght shft operators shft number bts to the rght. The eftmost and the rghtmost bts are shfted out and are ost. 138 e.g. char x, y = 0x80; y = y >> 3; x = y <<2; y <<= 1; x >>=2; The char y( whch s aocated a byte of space on a 16-bt machne) w have ts bts shfted to the rght three paces. The vaue of y whch was 0x80(1000 0000) s changed to 0xFo(1111 0000) , after y = y>>3. 1.1.). Precedence and 2rder of e0aluation The anguages foow a standard precedence for basc operators. Precedence rues hep n removng ambguty of the order of operatons performed whe evauatng an expressons. Aso mportant for ths purpose s the assocatvty of the operators, assocatvty defnes the drecton n whch the expresson s evauated when the operator s nvoved. The precedence and assocatvty of the operators s summarzed beow: 2$erator 5ssociati0it1 () || -> eft to rght ! - ++ -- (type)* szeof rght to eft * / % eft to rght + - eft to rght << >> eft to rght == != eft to rght & eft to rght 139 eft to rght | eft to rght && eft to rght || eft to rght ? : rght to eft = += -= etc. rght to eft , eft to rght Operators on the same ne have the same precedence; rows are n order of decreasng precedence, so, for exampe, *, /, % a have the same precedence whch are hgher than that of + and on the next ne. 1.1.+. 4he si?eof() o$erator Ths s a pseudo-operator gven by the anguage, whch returns the number of bytes taken up by a varabe or data type. The vaue returned by ths operator can be used to determne the sze of a varabe. szeof(nt); // returns 2 on a 16bt machne szeof(foat); // returns 4 on a 16bt machne 1.1". 8i6ed 8ode %6$ressions and Im$licit t1$e Con0ersions A mxed mode expresson s one n whch the operands are not of the same type. In ths case, the operands are converted before evauaton, to mantan compatbty of the data types. The foowng tabe shows the converson :
2$erand1 o$erand 3 /esult char nt nt 140 nt ong ong nt doube doube nt foat foat nt unsgned unsgned ong doube doube doube foat doube e.g. char ch = A; ch = ch + 32; Here, ch w be converted to an nteger, snce there s an nteger(32) n the expresson. The resut w be an nteger. e.g. foat f = 10.0; nt = 0; = f / 3; In ths expresson , the constant 3 w be converted to a foat and then foatng pont dvson w take pace, resutng n 3.33333, but snce the vaue s an nteger the vaue w be automatcay truncated to 3 and the fracton part s ost. ( mpct converson from foat to nt ). 1.1#. 41$e Casting Impct type conversons, as aowed by the anguage, can ead to errors creepng n the program f care s not taken. Therefore, expct type conversons may be used n mxed mode expressons. Ths s done by type-castng a vaue of a partcuar type, nto the desred type. Ths s done by usng the (type) operator as foows: (type) expresson expresson s converted to the gven type by the rues stated above. 141 e.g. foat a = 10.0, b = 3.0, c; c = a / b; Ths expresson w resut n 3.333333 beng stored n c. If the appcaton requres nteger dvson of two foatng pont numbers, then the foowng expresson wth the type cast can be used: c = (nt)a / (nt)b; or c = (nt) (a / b); 1.1(. Control Flo< The contro fow statements are used when t s requred that the fow of the program s to be changed after takng some decson. Ths contro fow statement thus specfy the order n whch the computatons are carred out. The anguage offers for# while# do$ while# if$else# else$if# switch# goto as contro statements. We can cassfy them as branching and looping structures. 1.1(.1. !ranching Statements The contro fow statements used for branchng are f-ese, ese-f and swtch. 1.1(.1.1. 4he if;else and else;if statements. The syntax of f ese statement s : f(expresson 1) { statements; } ese { statements; } 142 If the expresson1 s evauated to be true the statements under t are executed otherwse f t s wrong the statements wrtten after the keyword else are executed. e.g. f( ch < 0 || ch > 9) { cout << " Not a Number); } ese // n case of a snge statement the braces can be avoded. cout<<" Ths s a number"; A snge f(expresson) wthout an ese can aso be used for checkng a snge condton. A mut-way decson makng segment can be wrtten by usng f statements nsde the ese part, whch gves the ese-f construct. e.g. f( opton == 1) cout<<" 11111"; ese f( opton == 2) cout<<" 22222"; ese f( opton == 3) cout<<" 33333"; ese cout << " nvad "; They can be nested as we: e.g. f(expresson 1) { f ( expresson 2) { : : } ese { 143 } } ese { f ( expresson 2) { : : } ese { } }
1.1(.1.2. 4he Conditional %6$ression 2$erator An aternate method to usng a smpe f-ese construct s the condtona expressons operator, ?: A condtona expresson operator s a ternary operator, t has three operand, whose genera format s: expresson1 ? expresson2 : expresson3 Here the expresson1 s evauated frst, f t s true then the expresson 2 s the vaue of the condtona operator, otherwse the expresson 3 s the vaue. e.g. The f ese construct f(a>b) { z = a; } ese { z = b; } Ths can be wrtten as 144 z = (a>b) ? a: b; 1.1(.1.3. 4he S<itch Construct The swtch statement s a mut-way decson-makng construct that tests whether an expresson matches one of a number of constant vaues, and branches accordngy. The swtch statement s another aternatve to usng nested f-ese statements. The genera format s as foows : swtch(expresson) { case vaue1 : statements; : : break; case vaue2 : statements; : : break; case vaue3 : statements; : : break; defaut : statements; : : } The expresson must be decared n the parentheses, and the body of the swtch statement must be encosed n braces. The vaues wth case shoud be constants. The expresson s evauated and compared wth the vaues n cases, f t matches the statements under t are executed t t encounters a break statement. If the vaue does not match wth any of the case statements then the statements under the defaut abe are executed. Omsson of break takes contro through the next case statements regarded whether the vaue of case matches or not. Ths 145 can aso be used constructvey when same operaton has to be performed on a number of cases. e.g. swtch(ch) { case a : case e : case : case o : case u : cout << "Vowe"; defaut : cout << " Consonant "; } In the above exampe f the vaue of ch s any of a,e,,o,u then they are prnted as vowes , otherwse they are prnted as consonants. 1.1(.2 Loo$ing Statements The statements generay used for oopng are for# do$while# while. The goto statement can be used for looping# but its use is generally avoided as it leads to hapha%ard code and also increases the chances of errors. 1.1(.2.1. 4he for Loo$ Ths s a controed form of oop. The genera format s : for( ntaze ; test ; update) { statements; : : } The ntaze part s executed ony once, before enterng the oop. If test evauates to fase then the next statement after for oop s executed. If the test evauates to true then the updatng takes pace. e.g. 146 for( nt = 0; < 10; ++) // In C++ you can decare a varabe here. { cout << ; } Ths w prnt from 0 to 10. The expressons n the for oop are optona but the sem-coons are necessary, .e., for( ; ; ) { cout<<"heo"; } Ths s an nfnte oop, wth no expresson. e.g. nt = 0 for(; < 10; ) { cout << ; ++; } Ths s equvaent to our exampe, whch prnted from 0 to 9. More than one expresson can aso be nsde the for oop by separatng them usng commas. e.g. for( nt = 0, nt |=10; < 10 && y>0 ; ++, y--) { cout << ; } 1.1(.2.2. 4he <hile Loo$ The for oop s a form of a controed oop. When the number of teratons to be performed are not known beforehand the whe oop can be used. The genera format s : 147 whe(condton) { statements; : } The statements n the oop are executed as ong as the condton s true . e.g. nt x = 0; whe( x < = 10) { cout << x; } Ths exampe prnts from 0 to 10 . 1.1(.2.3. 4he do..<hile Loo$ The genera format s as foows : do { statements; : : } whe(condton); e.g. do { cout << x; } whe( x < = 10); Ths works exacty ke our prevous exampe . the do.. whe oop s exacty ke whe oop, wth one dfference. Here testng s done after executng the statements nsde the oop and f the condton evauates to true then we enter the oop agan ,whereas n whe ony 148 after the expresson s checked we enter the oop. We can say do oop s executed at east once. 1.1(.3. 4he -rea@ statement The break statement, whch was aready covered n the swtch.. case , can aso be used n the oops. When a oop statement s encountered n the oops the contro s transferred to the statement outsde the oop. When there are nested oops t breaks ony from the current oop n whch t was wrtten. 1.1(.. 4he continue statement The contnue statement causes the next teraton of the encosng oop to begn. When ths s encountered n the oop , the rest of the statements n the oop are skpped and contro passes to the condton. Let us see an exampe that accepts a varabe amount of numbers from the keyboard and prnts the sum of ony postve numbers. e.g. vod man() { nt num, tota = 0; do { cout << " enter 0 to qut "; cn >> num; // equvaent to scanf() f(num == 0) break; f(num < 0) contnue; tota+=num; }whe(1); cout << tota; } 149 1.1(.". 4he goto statement Ths statement can be used to branch to another statement of the program. Ths s rarey used as t voates the prncpe of structured programmng. However we can use t when we want to ext from deepy nested oops. The genera format s : goto abe; where abe s a name(tag) foowed by a coon. e.g. for( . . . ) { for( . . . ) { for( . . . ) { for( . . . ) { f( condton) goto ceanup; } } } } ceanup: statements; : : A good programmer w use contro statements effectvey n order to avod the usage of uncondtona branchng statement goto. Ths sesson ntroduced some features of the C and C++ anguages. The data types offered, quafers to the data types, the scope rues and storage methods were aso dscussed n ths sesson. The contro fow requred for any anguage to be structured was aso 150 dscussed n deta. The anguage offers a varety of operators. The next sesson ntroduces some of the advanced topcs. ------------ -------------- ----------- ------------ ------------ Session 2 Some features of C and Introduction to the language C++, (Part 2) During this session you will learn about: Array types. Ways of ntazng the arrays. Ponter types. Ponter Arthmetc. Reatonshp between Arrays and Ponters. Structures. Enumerated Constants. Reference Types. Dfference between a Ponter and a Reference. Unons. In ths sesson we w earn about storng a set of ke type data members. We w earn how to bunde reated data members of may be dfferent names under the same name. We w earn a few advanced topcs of the anguage construct. 2.1. 5rra1 t1$es An array s a coecton of ob|ects of a snge data type. The ndvdua ob|ects are accessed by ther poston n the array. Ths way of accessng s caed ndexng or subscrptng. e.g. nt arr|10|; // Decares array of 10 nteger ob|ects nt va = arr|2|; // Assgns the vaue of thrd eement n the array nto va arr|0| = va; // Assgns the vaue of va n to array 151 eement arr|0|
An array defnton conssts of a type specfer, an dentfer ,and a dmenson. Dmenson specfes the number of eements contaned n the array. An array must be gven dmenson sze greater than or equa to 1. The dmenson vaue must be a constant expresson. .e., the vaue shoud be avaabe at compe tme. e.g. extern nt getsze(); const nt a = 10, b = 20; nt c = 30; char c_arr|a|; // vad nt _arr|b-3|; // vad ,constant expresson. Evauates to 17 durng compaton. nt _arr|c|; // ERROR: non-constant varabe. Though t s ntazed, access to ts vaue can ony be accompshed runtme. nt _arr|get_sze()|; // ERROR: non-constant expresson The eements of an array are numbered begnnng wth 0. For an array of 10 eements , the ndex vaues are 0 through 9. 2.2. ,arious <a1s of initiali?ing the 5rra1s. The for oop ntazes 10 eements wth the vaue of ther ndex. vod man() { const nt sze = 10; nt arr|sze|; for(nt = 0; < sze ; ++ ) // You can decare a varabe here n C++. { arr|| = ; } } An array can be eplicitly ntazed as foows. 152 e.g. nt arr|3| = {0,1,2}; An expcty ntazed array need not specfy sze but f specfed the number of eements provded must not exceed the sze. If the sze s gven and some eements are not expcty ntazed they are set to zero e.g. nt arr|| = {0,1,2};
nt arr1|5| = {0,1,2}; // Intazed as {0,1,2,0,0}
const char a_arr1|| = {c.+,+} //sze = 3; const char a_arr2|| = {"c++"} //sze = 4 because of nu character at the end of the strng; const char a_arr3|6| = "Dane"; // ERROR; Dane has 7 eements An array cannot be ntazed wth or assgned to another array. We cannot have array of references. e.g. nt x,y,z; nt *arr|| = {&x,&y,&z}; //Can have array of ponters nt &arr|| = {x,y,z}; // ERROR: cannot have array of references. nt arr2|| = {1,2,3}; // vad nt arr1|| = arr2; // ERROR: cant ntaze one array to anther arr1 = arr2; // ERROR: cant assgn one array to another. 153 To copy one array to another each eement has to be coped usng for structure. Any expresson that evauates nto an ntegra vaue can be used as an ndex nto array. e.g. arr|get_vaue()| = somevaue; 2.3. 8ultidimensional 5rra1s Each dmenson s specfed n separate brackets e.g. nt arr|4||3|; Ths s a two-dmensona array wth 4 as row dmenson and 3 as a coumn dmenson. Mutdmensona array can be ntazed as foows e.g. nt arr|4||3| = {{0,1,2},{3,4,5},{6,7,8},{9,10,11}}; The nested brackets are optona. e.g. nt arr|4||3| = { 0,1,2,3,4,5,6,7,8,9,10,11}; nt arr|4||3| = {{0},{1},{2},{3}}; // Frst eement of rows are 0,1,2,3 and remanng are consdered zero. nt arr|4||3| = {1,2,3}; // Intazes frst three eement of frst row as 1,2,3, and remanng ee- ments are consdered Zero. Intazaton usng nested oops. 154 e.g. nt arr|10||10|; for(nt = 1;< = 10;++) for(nt | = 1; |< = 10;|++) { arr||||| = +|; } Instead of arr|1||2| f you gve arr|1,2| s consdered as arr|2|. 2..Pointer 41$es Ponter hods the address of an ob|ect, aowng for the ndrect manpuaton of that ob|ect. They are used n creatng nked data structures ke sts, trees and management of ob|ects that are dynamcay created durng program executon. Ponters are decared usng the (*) operator. The genera format s:
type *ptrname; type can be of any data type and ponter name becomes the ponter of that data type.
e.g. nt *ptr; char *cptr; foat *fptr;
The ponter ptr stores the address of an nteger. In other words t ponts to an nteger, cptr to a character and fptr to a foat vaue. Once the ponter varabe s decared t can be made to pont to a varabe wth the hep of a address(reference) operator(&). 155 .e xe e.g. nt num = 1024; nt *ptr; ptr = # // ptr ponts to the varabe num. In the foowng exampe ptr1 s a ponter to ong varabe and ptr2 s a norma ong varabe. e.g.
ong *ptr1, ptr2; You can decare a ponter varabe n two ways. However, the second format s not recommended as t may ead to the confuson that when we decare varabes ke |ust shown above coud be correct. e.g. strng *sptr; strng * sptr; The ponter can hod the vaue of 0 , ndcatng that t ponts to no ob|ect or t can hod the address of same data type as mentoned earer. e.g. nt va = 1024; nt *ptr1 = 0, *ptr2 = &va; ptr1 = ptr2 // both address va ptr2 = 0; // ptr2 now addresses to no ob|ect. Ponters can never store a non-address vaue. e.g. ptr1=va; // nvad, va s not address. A ponter of one type cannot be assgned the address vaue of the ob|ect of another type. 156 e.g. doube dva, *dptr = &dva; // aowed ptr = &dva ; //not aowed However you can compare or nterchange 2 types of address vaues usng vod ponter. e.g. vod *vptr = ptr; vptr = dptr; We cannot operate on an ob|ect ponted by vod. They are ony for transport of the varabes. Once the ponter s defned. The varabe t ponts to can be accessed by usng the ndrecton operator (*) aso caed the dereferencng operator. e.g. nt va1 = 1024, va2 = 2084; nt * ptr = &va1; * ptr = va2; // va1 = va2 * ptr = abs(*ptr); // va1 = abs(va1) * ptr = * ptr + 1; // va1 = va1 + 1; You can aso have second eve of ndrecton .e., you can have ponter to ponter to nt. e.g. 157 nt **ptrptr = &ptr; We dereference t as foows. nt *ptr3 = *ptrptr; // content s an address. 2.". Pointer 5rithmetic We can manpuate the ponters too. We can perform operatons ke addton, subtracton, ncrement and decrement etc.,. Snce the ponter varabes contan address, addng or subtractng a number resuts n another address, whch s at an offset from the orgna address. Ths may be memory address occuped by another varabe. e.g. nt , |, k ; nt *ptr = &; *ptr = *ptr + 2; // I = I + 2; ptr = ptr + 2 // adds 2 to address. These are usefu when usng arrays. e.g. nt arr|10|; nt *ptrb = &arr|0|; nt *ptre = &arr|10|; Whe ( ptrb != ptre) { Do somethng wth the vaue f (*ptrb); ++ptrb; } 158 2.#. /elationshi$ -et<een an 5rra1 and Pointers. Consder the foowng. nt arr|| = {0,1,2,3,4,5,6,7,8,9}; If we wrte arr , t s consdered as the address of the frst eement of an array. Hence, arr s equvaent to &arr|0|; arr|1| <==>arr+1; Smary to access the vaue we can wrte , arr|0| or *arr; arr|1| or *(arr+1); :iff -et<een A(arr+1 ) and Aarr+1 *(arr+1) means the address of arr s ncreased by 1 and then the contents are fetched. *arr+1 means the contents are fetched from address arr and one s added to the content. The traversa of an array can be made ether through subscrptng or by drect ponter manpuaton. e.g. vod prnt(nt *arr_beg, nt *arr_end) { whe(arr_beg ! = arr_end) { cout << arr_beg; ++arr_beg; } } vod man() { nt arr|| = {0,1,2,3,4,5,6,7,8,9} prnt(arr,arr+9); } 159 arr_end ntazes eement past the end of the array so that we can terate through a the eements of the array. Ths however works ony wth ponters to array contanng ntegers. 2.(. Structures A structure s a derved data type. It s a combnaton of ogcay reated data tems. Unke arrays, whch are a coecton of ke data types, structures can be made of members of unke data type. The data tems n the structures generay beong to the same entty , ke nformaton of an empoyee, payers etc. The genera format of structure decaraton s: struct tag { type member1; type member2; type member3; : : }varabes; We can omt the varabe decaraton n the structure decaraton and defne t separatey as foows : struct tag varabe; In C++ we can omt struct and smpy wrte : tag varabe; e.g. Structure defnton. struct account { nt accnum; char acctype; char name|25|; foat baance; }; 160 Structure decaraton. struct account odcust; |or| account newcust; We can refer to the member varabes of the structures by usng a dot operator (.). e.g. newcust.baance = 100.0 cout << odcust.name; We can ntaze the members as foows : e.g. account customer = { 100, w, Davd, 6500.00}; We cannot copy one structure varabe nto another. If ths has to be done then we have to do memberwse assgnment. We can aso have nested structures as shown n the foowng exampe : struct date { nt dd, mm, yy; };
struct account { nt accnum; char acctype; char name|25|; foat baance; struct date d1; }; Now f we have to access the members of date then we have to use the foowng method. account c1; 161 c1.d1.dd=21; We can pass and return structures nto functons . The whoe structure w get copes nto forma varabe . We can aso have array of structures. If we decare array to account structure t w ook ke, account a|10|; Every thng s same as that of a snge eement except that t requres subscrpt n order to know whch structure we are referrng to. We can aso decare ponters to structures and to access member varabes we have to use the ponter operator -> nstead of a dot operator. account *aptr; cout << aptr->name; A structure can contan ponter tsef as one of the varabes ,aso caed sef-referenta structures. e.g. struct nfo { nt ,|,k; nfo *next; }; 2.).%numerated Constants Enumerated constants enabe the creaton of new types and then defne varabes of these types so that ther vaues are restrcted to a set of possbe vaues. e.g. enum Coour{RED, BLUE, GREEN, WHITE, BLACK}; 162 Coour s the name of an enumerated data type. It makes RED a symboc constant wth the vaue 0, BLUE a symboc constant wth the vaue 1 and so on. Every enumerated constant has an nteger vaue. If the program doesnt specfy otherwse, the frst constant w have the vaue 0, the remanng constants w count up by 1 as compared to ther predecessors. Any of the enumerated constant can be ntased to have a partcuar vaue, however, those that are not ntased w count upwards from the vaue of prevous varabes. e.g.
enum Coour{RED = 100, BLUE, GREEN = 500, WHITE, BLACK = 1000}; The vaues assgned w be RED = 100,BLUE = 101,GREEEN = 500,WHITE = 501,BLACK = 1000 You can defne varabes of type Coour, but they can hod ony one of the enumerated vaues. In our case RED,BLUE,GREEEN,WHITE,BLACK . You can decare ob|ects of enum types. e.g. enum Days{SUN, MON, TUE, WED, THU, FRI, SAT}; Days day; Day = SUN; Day = 3; // error nt and day are of dfferent types Day = heo; // heo s not a member of Days. Even though enum symboc constants are nternay consdered to be of type unsgned nt we cannot use them for teratons. e.g. enum Days{SUN, MON, TUE, WED, THU, FRI, SAT}; for(enum = SUN; <SAT; ++) //not aowed. 163 There s no support for movng backward or forward from one enumerator to another. However whenever necessary, an enumeraton s automatcay promoted to arthmetc type. e.g. f( MON > 0) { cout << "gh|f"; } nt num = 2*MON; These are aowed. 2.+. /eference 41$es The symbo "&" s nterpreted as an address operator as we as AND operator. Ths operator s aso used to decare a "reference variable". A reference s referred to an alias, serves as an aternatve name for the ob|ect. e.g. nt va = 1024; nt &rva = va; // rva s reference to va A reference varabe shoud be ntazed at tme of decaraton tsef. e.g. nt &ref; // wrong nt &ref = va //o.k. Once a reference has been made to a varabe , t cannot be changed to refer to another varabe. e.g. vod man() { nt num1 = 10, num2 = 200; 164 . ex e nt &ref = num1; cout<< num1 << num2 << ref ; //10,200,10; ref = num2; cout << num1 << num2 << ref ; //200,200,200 } It changes the contents of the orgna varabe, whch s not the desred acton. Athough a reference to a varabe serves as a knd of ponter, we cannot ntaze the address of an ob|ect to t. e.g. nt va = 1000; nt &refva = &va; //the error message by the //comper woud be- can not // convert nt* to nt. However , we can defne a ponter to a reference. e.g. nt *p = &va; nt *&ptr_ref = p; A the operatons on the reference varabes are actuay apped to the ob|ect to whch t refers. e.g. refva = refva + 2;// va = va + 2 ,1000 + 2 =1002 nt = refva; // = 1002; nt *p = &refva //p = &va; A constant reference can be ntazed to an ob|ect of a dfferent type as we as to non-addressabe vaues, such as tera constants . e.g. doube dva = 3.1415; const nt &r = 1024; const nt &r2 = dva; 165 const doube &dr = dva +1.0; The same ntazatons are not ega for non-constant references. Internay, a reference mantans the address of the ob|ect for whch t s an aas. In case of non-addressabe vaues, such as tera constant and ob|ects of dfferent types, the comper generates a temporary ob|ect that reference actuay addresses but user has no access to these addresses. e.g. doube dva = 1024; const nt &r = dva; The comper transforms ths as, nt temp = dva; const nt &r = temp; Now f we try to change r, t actuay changes temp and not dva as t s a constant We can ntase a reference to the address of a constant ob|ect. If we wrte, const nt va = 1000; nt *&p_ref = &va; // we requre constant reference. If we wrte, const nt *&p_ref = &va; /* ths s reference to a ponter to an ob|ect of type nt defned to be a constant. Our reference s not to a constant but rather to a non- constant, whch addresses a constant ob|ect.*/ The correct form s, nt *const &p_ref = &va //o.k. 2.1.. :ifferences -et<een a $ointer and a reference 166 1. A reference must aways pont to some ob|ect where as ths restrcton s not mposed on a ponter. e.g. nt *p = 0; // ponter can pont to no ob|ect. const nt &r = 0 woud be converted as , nt temp = 0; const nt &r = temp; 2. The assgnment of one reference wth another changes the ob|ect beng referenced and not the reference tsef. e.g. nt va1 = 1000, va2 = 2000; nt *p1 = &va1, *p2 = &va2; nt &r1 = va1, &r2 = va2; p1 = p2; va1 remans unchanged but p1 and p2 now address the same ob|ect va2. r1 = r2; va1 becomes 2000. r1 and r2 st refer to va1 and va2 respectvey. 2.11. 7nions A unon s aso ke a structure , except that ony one varabe n the unon s stored n the aocated memory at a tme. It s a coecton of mutuay excusve varabes , whch means a of ts member varabes share the same physca storage and ony one varabe s defned at a tme. The sze of the unon s equa to the argest member varabes. A unon s defned as foows : unon tag { type memvar1; 167 type memvar2; type memvar3; : : };
A unon varabe of ths data type can be decared as foows, Unon tag varabe_name; e.g. unon utag { nt num; char ch; }; unon tag fed; The above unon w have two bytes of storage aocated to t. The varabe num can be accessed as fed.sum and ch s accessed as fed.ch. At any tme, ony one of these two varabes, can be referred to. Any change made to one varabe affects another. Thus unons use memory effcenty by usng the same memory to store a the varabes, whch may be of dfferent types, whch exst at mutuay excusve tmes and are to be used n the program ony once. Ths sesson covered advanced concepts of the anguage ke ponters, arrays, references, and reaton between them . As can be seen ponters and references can be used to return more than one vaue from the functons, to speed the processng and to use memory more effcenty. The sesson aso covered the concepts of structures and unons. The structures or records are the basc eements of a database. When they are used wth ponters, arrays etc, compex database management can be reazed. The unons are used to store varabes of dfferent types that are requred at mutuay excusve tmes. 168 %6ercises 1. Wrte a Program(WAP) to prnt a gven nteger n the reverse order. .e. 12345 s prnted as 54321 2. WAP a program to prnt frst N prme numbers where N s accepted from the user. 3. WAP to prnt the sum of squares between 1 & N, where N s accepted from the user. 4. WAP to convert a decma number nto ts equvaent of any other base(2,8,16). 5. WAP to accept an array of character strngs and prnt them n descendng order. --------------- ----------------- ---------------- ------------- Session 3 2-3ect 2riented Programming ' 5n Introduction During this session you will learn about : Procedura, Structura and Ob|ect-Orented Programmng ogc. Dfferent mpementaton of OOP. Introducton to C++. C++ and OOP. Dfferences between C and C++. - Addtona keywords n C++. - Comments . - Varabe decaratons. Defaut arguments. The new and deete operators. The cn and cout ob|ects. In earer sessons we earnt about anguage features whch had nothng to do wth Ob|ect Orented Programmng technques. Ths sesson ntroduces the features of Ob|ect Orented programmng and aso dscusses other programmng methods. We can aso see features of C++ that are not present n C. 169 3.1 Procedural, Structured, and 2-3ect;2riented Programming logic Unt recenty, programs were envsoned as a seres of procedures that acted on data. A procedure# or functon, was defned as a set of specfc nstructons executed n sequenta manner. The data s kept separate from the procedures, and the trck n programmng was to keep track of, whch functons caed whch functons, and whch data was changed. To make sense of ths potentay confusng stuaton, structured programmng was created. Pasca s a anguage, whch uses procedura method of programmng. The prncpa dea behnd structured programming was as smpe as the dea of "dvde and conquer." A computer program coud be regarded as consstng of a set of tasks. Any task that was too compex to be smpy descrbed woud be broken nto a set of smaer component tasks, unt the tasks were suffcenty sma and sef- contaned to be easy understood. The anguage C uses structured programmng approach. Structured programmng remans an enormousy successfu approach for deang wth compex probems. By the ate 1980s, however, some of ts defcences had become a too cear. Frst, the separaton of data from the tasks that manpuate the data became ncreasngy dffcut to comprehend and mantan. It s natura to thnk of data (empoyee records, for exampe) and ways that data can be manpuated (sort, edt, and so on) as reated deas. Second, programmers found themseves constanty renventng new soutons to od programs. Renventng n a way s opposte of reusabty. &eusability nvoves budng components that have known propertes, and then puggng those components nto a program, as the programmer needs them. Ths software concept s modeed after the hardware word; when an engneer needs a new transstor, she doesnt usuay nvent one but goes to bg bn of transstors and fnds one that fts her needs, or perhaps modfes the found transstor. No smar opton exsted for a software engneer unt reusabty was deveoped. Ob|ect-orented programmng (OOP) attempts to meet these needs, provdng technques for managng enormous compexty, achevng reuse of software components, and coupng data wth the tasks that manpuate the data. 170 The essence of ob'ect$oriented programming s to treat data and the procedures that act on the data as a snge "ob|ect" a sef- contaned entty wth an dentty and certan characterstcs of ts own. 3.2 :ifferent im$lementations of 22P Ob|ect-orented programmng s not partcuary concerned wth the detas of the program operaton. Instead, t deas wth the overa desgn of the program . The OOP features can be mpemented n many anguages that support them. C++ s one anguage that supports a the features of OOP. Other anguages ncude Common Lsp ob|ect system, Smatak, Effe, Actor and the atest verson of Turbo Pasca, |ava. However, C++ s the most wdey used ob|ect-orented programmng anguage. 3.3. Introduction to C++ C++ was deveoped by B|arne Stroustrup at Be Laboratores n 1983. Orgnay, t was caed as " C wth cass". C+ as an enhancement to the C anguage was deveoped prmary to factate managng, programmng and mantanng arge software pro|ects. The most mportant aspect of the C anguage s, probaby, the fexbty to do whatever the programmer wants. The mts of the anguage are defned by the programmers magnaton. Unfortunatey, wth very arge pro|ects n whch many programmers use shared routnes, ths berty can ead to what are caed as sde effects . Ths s one probem, whch C++ attempts to resove by restrctng ndscrmnate access. At the same tme, C++, aso attempts to keep the freedom and fexbty gven by the anguage. A the keywords of C are keywords of C++ aso. In addton we have some new ones too. However, C++ s not merey an extenson of the C anguage, where some new symbos have been added. The basc purpose of C++ anguage s to add features to the C anguage that supports the concepts of OOP. There are severa C++ products avaabe Turbo C++, Zortech C++, AT&T C++, Sun C++ etc., Turbo C++ and Borand C++ are most wdey used. AT & T however s the most advanced one. 171 3.. C++ and 2-3ect;2riented Programming C++ fuy supports ob|ect-orented programmng, ncudng the four pars of ob|ect-orented deveopment : encapsulation# data hiding# inheritance# and polymorphism. Before dscussng these pars et us know about some other terms assocated wth OOP. The most mportant term s (bstraction". Abstracton means gnorng those aspects of a sub|ect that are not reevant to the current purpose n order to concentrate more fuy on those that are reevant. To an anayst who s as good as a sub|ect expert t means choosng certan thngs or aspects of the system over others at a tme. Most of the thngs n the rea word are ntrnscay compex, far more compex than one can comprehend at a tme. By usng abstracton one seects ony a part of the whoe compex nstead or workng wth the whoe thng. It does not mean gnorng the detas atogether but ony temporary, the detas are embedded nsde and are deat wth at a ater stage. Abstracton s used by OOP as a prmary method of managng compexty. (ssociation s the prncpe by whch deas are connected together or unted. Assocaton s used to te together certan thngs that happen at some pont n tme or under smar condtons. )ommunicating with messages s the prncpe for managng compexty, whch s used when nterfaces are nvoved to communcate between the enttes. OOP uses casses and ob|ects have attrbutes, whch can be excusvey accessed by servces of the ob|ects. To change the attrbutes of the ob|ect (a data member of the ob|ect), a message has to be sent to the ob|ect to nvoke the servce. Ths mechansm heps n mpementng encapsuaton and data abstracton. 3..1. %nca$sulation and :ata Biding The property of beng a sef-contaned unt s caed encapsulation. The dea that the encapsuated unt can be used wthout knowng how t works s caed data hdng. Encapsuaton s the prncpe by whch reated contents of a system are kept together. It mnmzes traffc between dfferent parts 172 of the work and t separates certan specfc requrements from other parts of specfcaton, whch use those requrements. The mportant advantage of usng encapsuaton s that t heps mnmze rework when deveopng a new system. The part of the work, whch s prone to change, can be encapsuated together. Thus any changes can be made wthout affectng the overa system and hence changes can be easy ncorporated. As noted before, when an engneer needs to add resstor to the devce she s creatng, she doesnt typcay bud a new one from the scratch. She waks over to a bn of resstors, examnes the bn of resstors, examnes the coored bands that ndcate the propertes, and pcks the one she needs. The resstor s a "back box" as far as the engneer s concerned that s, she doesnt care how t does ts work as ong as t conforms to her specfcatons. A the resstors propertes are encapsuated n the resstor ob|ect they are not spread out through the crcutry. It s not necessary to understand how the resstor works to use t effectvey, because ts data s hdden nsde the resstors casng. C++ supports the propertes of encapsuaton and data hdng through the creaton of user-defned types, caed classes. Once created, a we-defned cass acts as a fuy encapsuated entty and can be used as a whoe unt. The actua nner workngs of the cass shoud be hdden; users of we-defned cass do not need to know how the cass works, ony how to use t. 3..2. Inheritance and /euse Consder a car manufacturng company. When they want to bud a new car, they have two choces. They can start from the scratch, or they can modfy an exstng mode. Perhaps ther former mode s neary perfect (say CAR1), but they woud ke to add a turbocharger and a sx-speed transmsson. The chef engneers woud prefer to use the earer mode and make some changes to t than creatng a new one (CAR2). C++ supports the dea of reuse through inheritance. Through ths concept, a new type can be decared that s an extenson of the exstng type. Ths new subcass s sad to derve from the exstng type and s sometmes caed a derived type. 173 3..3. Pol1mor$hism The CAR2 n the above exampe may respond dfferenty than the CAR1 when the car acceerates. The CAR2 mght engage fue n|ecton and a turbocharger, for exampe, whereas the CAR1 smpy get petro nto ts carburetor. A user, however, does not have to know about these dfferences; the user smpy presses the acceerator and the car responds wth the correct functon. C++ supports ths dea that dfferent ob|ects do "the rght thng " through functon poymorphsm and cass poymorphsm. *oly means many, whereas morph means form. Thus, polymorphism refers to the same name takng many forms. 3.". Some :ifferences !et<een C and C++ There are severa dfferences between the C anguage and C++, whch have nothng to do wth OOP. Some of them are hghghted beow. 3.".1. 5dditional @e1<ords in C++ cass frendvrtua nne prvate pubc protected const ths new deete operator The actua use and descrpton of these addtona keywords w be covered n ther specfc contexts. 3.".2. Comments Comments are ntegra part of any program . Comments hep n codng, debuggng and mantanng a program . The comper gnores them. They shoud be used beray n the program . In C++, a comment starts wth two forward sashes ( // ) and ends wth the end of that ne. A comment can start at the begnnng of the ne or on a ne foowng the program statement. Ths form of gvng comments s partcuary usefu for the short ne comments. If a comment contnues on more than a ne, the two forward sashes shoud be gven on every ne. 174 The C stye of gvng a comment s aso avaabe n C++. Ths stye ( /*..*/) s partcuary usefu when the comment spans more than a ne. e.g. vod man() { /* ths s a good od stye of gvng a comment. It can be contnued to next ne and has to be ended wth */ crscr(); // )lears the +creen nt()_; // ,nitiali%e variables. : : } 3.".3. ,aria-le :eclaration Ths decaraton of varabes n the C anguage s aowed ony n the begnnng of ther bock, pror to executabe program statements. In C++ decaraton of varabes can be nterspersed wth executabe program statements. The scope d varabes, however, remans the same the bock n whch they are decared. e.g. vod man() { nt x = 10; prntf (" the vaue of x= % d\n",x); nt y = 0; for( nt z= 0; z < 10; ; z++) // variable declared here. { y ++; x ++; } 175 } Athough, a devaton from the od stye of decarng a varabes n the begnnng of the bock, ths does save some amount of memory, .e., a varabe s not gven a memory unt the decaraton statement. Aso, snce a varabe can be decared |ust before usng t s suppose to gve a better contro over varabes. 3.".. 4he Sco$e /esolution 2$erator( '' ) Goba varabes are defned outsde any functons and thus can be used by a the functons defned thereafter. However, f a goba varabe s decared wth the same name as that of a oca varabe of a functon , the oca varabe s the one n the scope when the program executes that functon . The C++ anguage provdes the scope resouton operator ( :: ) to access the goba varabe thus overrdng a oca varabe wth the same name. Ths operator s prefxed to the name of the goba varabe . The foowng exampe shows ts usage. nt goba = 10; vod man() { nt goba = 20; prntf(" |ust wrtng goba prnts : %d\n", goba); prntf(" Wrtng ::goba prnts : %d\n", ::goba); } The output of ths program w be: |ust wrtng goba prnts : 20 Wrtng ::goba prnts : 10
3.".". :efault 5rguments A defaut argument s a vaue that s automatcay assgned to a forma varabe, f the actua argument from the functon ca s omtted. e.g. 176 vod drawbox( nt x1=1, nt y1=1, nt x2=25, nt y2=80, nt coor=7); // *rototype
vod man ( vod ) { drawbox(10,1,25,80,14); // parameters passed drawbox(); // uses defaut arguments } vod drawbox( nt x1, nt y1, nt x2, nt y2, nt coor) { // Body of the function }
Functon drawbox() draws a box around the edges of the coordnates passed as parameters. If these parameters are omtted, then the defaut vaues, as gven n the decaraton are passed. When a functon s decared, defaut vaues must be added from right to left. In other words, a defaut vaue for a partcuar argument cannot be gven uness a defaut vaues for the arguments to ts rght are gven. Ths s qute ogca, snce, f there are some arguments mssng n the mdde then the comper woud not know as to whch arguments have been specfed and whch shoud be taken as defaut. e.g. vod drawbox( nt x1=1, nt y1=1, nt x2=25, nt y2=80, nt coor = 7); // Valid vod drawbox( nt x1, nt y1, nt x2, nt y2, nt coor = 7); // Valid vod drawbox( nt x1=1, nt y1=1, nt x2=25, nt y2=80, nt coor ); // -ot Valid Defaut arguments are usefu when the arguments amost have the same vaue. They are aso usefu to ncrease the number of arguments to a functon n an aready workng program. In ths case, usng defaut arguments mean that exstng functon cas need not be modfed, whereas, new functon cas pass more number of arguments. 177 3.".#. 4he new and delete o$erators The C anguage has defned brary functons- maoc() and free() for dynamc aocaton and de-aocaton of memory. C++ provdes yet another approach to aocate bocks of memory the new operator. Ths operator aocates memory for a gven sze and returns a ponter to ts startng pont. C++ aso provdes delete, to reease the memory aocated by new. The ponter returned by the new operator need not be typecasted. e.g. char arr|100|; // )ompile.time allocation of an array char *arr; // )haracter pointer arr = new char|sze|; //Run time allocation of an //array. +i%e can be a //constant or a variable. In the above exampe, new returns a ponter to a bock of sze bytes. It s synonymous wth decarng a character array. However, decarng an array s an exampe of statc bndng the array s but at the compe-tme. Ths array remans n exstence rght from the begnnng of the program to ts end, even f not n use. Whereas , the array decared by new operator can be aocated memory ony when requred and can be reeased when over wth, usng the delete operator. Ths s an exampe of dynamc bndng. It s possbe that the system may not have enough memory avaabe to satsfy a request by the new operator. In ths case, new returns a nu ponter. Thus, the returned vaue from the new shoud aways be checked before performng any operatons on t, whch otherwse may ead to an adverent system crashes. Once the new operator aocates memory, t can be accessed usng the ndrecton operator (*) or the array subscrpts. e.g. nt *some = new nt |10|; // ( bloc0 of 12 integers doube *d5 = new doube|5|; // ( bloc0 of 3 doubles 178 char *cp; cp = new char; // 4ne character only. deete some; // &elease memory. deete d5;
char *ptr , *str = "the shy s bue "; ptr = new char |stren(str)+1|; // )haracter array f( ptr != 0) { strcpy(ptr,str); : : } ese { prntf(" not enough memory "); } struct date { nt dd,mm,yy; }; date *dp = new date; // Ths aocated a new structure // to the ponter varabe dp prntf(" enter day "); scanf("%d",&dp->dd); : } 924% ' 4he cin and cout objects In C++ the keyword cin wth the extracton operator " >> " s used to accept the nput and the keyword cout wth the nserton operator " << " s used to dspay strng teras and vaues, n pace of scanf() and prntf() functons of C. However, here we do not need any type specfers ke %d , %f etc., to denote the varabes type. cin and cout can be used n context wth any basc data types. 179 e.g. nt var; foat fvar; char cvar; char name|10|; cn >> var ; cn >> fvar >> cvar >> name; cout<< " var = " << var << end; cout<< " fvar = " <<fvar << " cvar= " << cvar << name; It s cear n the above exampe, how we can accept and dspay varabes. We can aso concatenate varous varabes, usng the nserton operator and extracton operator. Whe dspayng, f you wrte some text n the quotes they are dspayed as t s. Another manpuator endl can be used to end the ne and get the cursor back to next ne. We w study about these n deta n ater sessons. Ths sesson ntroduced the concept of Ob|ect-Orented Programmng. OOP mproves upon the defcences of the tradtona structured programmng. Data abstracton, encapsuaton and data hdng are some of the buzzwords of OOP. OOP, as seen, can be mpemented n many anguages. C++ s the most wdey amongst them. It s based on the C anguage and s thus a compete superset of the orgna C anguage. Some addtona features of C++ anguage were covered n ths sesson. The actua mpementaton features are covered from next sesson onwards. 5ercises 1. WAP to sort an array of strngs. Use new and deete operators. 2. WAP to wrte a program to fnd the factora of a number usng recurson. If we do not accept the number from the user to fnd the factora, then aways prnt the factora of 4. Use defaut argument methods. --------- -------- -------- --------- -------- ------- 180 Session Classes and 2-3ects During this session you will learn about: Structures Revsted. Introducton to cass. How to defne a user-defned varabe cass. How to create varabes (ob|ects) of cass. Access specfers Prvate, Pubc and Protected. Member functons of the cass. Passng and returnng ob|ects. Ponters to ob|ects. Array of ob|ects. Intazng the array of ob|ects. The speca this" pointer. Ob|ect-orented programmng (OOP) s a conceptua approach to desgn programs. Ths sesson w contnue our dscusson on OOP and C++. Some of the features of OOP are Data encapsuaton and data hdng, and these possbe because of data abstracton. A these features have one thng n common the vehce to mpement them. Ths vehce s class. It s a new data type smar to structures. Snce, the structure data type s a steppng-stone to ths snguary mportant concept of C++, et us take another ook at t.
.1. Structures A structure s a user-defned data type, whch may contan dfferent data types as ts members. Creatng a structure s a two-part process. Frst, a structure tempate s defned. Ths tempate gves a ot of nformaton to the comper. For nstance, How t s stored n the memory? How many member varabes are there n ths composte data eement? What are the types of ts member varabes? For data types ke nt, foat, doube, char ths nformaton s but nto the comper. But for the user-defned data types ke structures, t has to be provded to the comper. Ths s gven n the defnton of the structure tempate. Ths tempate creates a new data type. Varabes of 181 ths new data type can then be decared and used ke basc data types. e.g. struct Student { nt Rono; char Name|15|; nt Marks|6|; foat percent; }; The above exampe depcts structure caed students wth encosed data varabes. The keyword struct s used to defne a structure tempate. Student s a name or tag. The varabes of ths type can be decared as foows : struct Student s1,s2; |or | In C++ you can even omt the struct tag and decare the varabes as, Student s1 = ( 100, "Sanket" , 20,10,30,40,50,60, 35.0}; Student s2,|ack; Student *sptr = &s1; Student s|100|; In C++ , functons aso can be decared n a structure tempate. These functons are caed as member functons. e.g. struct Student { nt Rono; char Name|15|; nt Marks|6|; foat percent; vod Getdetas(); 182 vod Putdetas(); nt CacPercent(); }; There are three functons n the tempate gven above. These functons have been ncorporated n the structure defnton to make t a fundamenta unt. The budng together of data and the functons that operate on that data s caed as data encapsulation. But the probem s that the member varabes of ths structure can be accessed by functons other than the ones decared n the structure tempate. Ths drect access of member varabes of a structure by functons outsde the structure s not what OOP has to offer. The actua OOP methodoogy n ths regard s mpemented n C++ not by the structure data type, but by the data type class. The data type class s |ust ke structures, but wth a dfference. It aso has some access specfer, whch contros the access to member varabes of a cass . 4.2. Introducton to Casses Ob|ect-orented programmng (OOP) s a conceptua approach to desgn programs. It can be mpemented n many anguages, whether they drecty support OOP concepts or not. The C anguage aso can be used to mpement many of the ob|ect-orented prncpes. However, C++ supports the ob|ect-orented features drecty. A these features ke Data abstracton, Data encapsuaton, Informaton hdng etc have one thng n common the vehce that s used to mpement them. The vehce s " class." )lass s a user defned data type |ust ke structures, but wth a dfference. It aso has three sectons namey private, public and protected. Usng these, access to member varabes of a cass can be strcty controed. .3. Class :efinition The foowng s the genera format of defnng a cass tempate: cass tag_name { pubc : // 6ust type member_varabe_name; : type member_functon_name(); 183 : prvate: // 4ptional type member_varabe_name; : type member_functon_name(); : }; The keyword class s used to defne a cass tempate. The prvate and pubc sectons of a cass are gven by the keywords !private" and !public" respectvey. They determne the accessbty of the members. A the varabes decared n the cass, whether n the prvate or the pubc secton, are the members of the cass. Snce the cass scope s prvate by defaut, you can aso omt the keyword prvate. In such cases you must decare the varabes before pubc, as wrtng pubc overrdes the prvate scope of the cass. e.g. cass tag_name {
type member_varabe_name; // prvate : type member_functon_name(); // prvate : pubc : // 6ust type member_varabe_name; : type member_functon_name(); : }; The varabes and functons from the pubc secton are accessbe to any functon of the program. However, a program can access the private members of a cass ony by usng the public member functons of the cass. Ths nsuaton of data members from drect access n a program s caed information hiding. 184 e.g. cass payer { pubc : vod getstats(vod); vod showstats(vod); nt no_payer; prvate : char name|40|; nt age; nt runs; nt tests; foat average; foat cacaverage(vod); }; The above exampe modes a crcket payer. The varabes n the private secton name, age, runs, hghest, tests, and average can be accessed ony by member functons of the cass cacaverage(), getstats() and showstats(). The functons n the pubc secton - getstats() and showstats() can be caed from the program drecty , but functon cacaverage() can be caed ony from the member functons of the cass getstats() and showstats(). Wth nformaton hdng one need not know how actuay the data s represented or functons mpemented. The program need not know about the changes n the prvate data and functons. The nterface(pubc) functons take care of ths. The OOP methodoogy s to hde the mpementaton specfc detas, thus reducng the compextes nvoved. .. Classes and 2-3ects As seen earer, a cass s a vehce to mpement the OOP features n the C++ anguage. Once a cass s decared, an ob'ect of that type can be defned. An ob'ect s sad to be a specfc nstance of a cass |ust ke Marut car s an nstance of a vehce or pgeon s the nstance of a brd. Once a cass has been defned severa ob|ects of that type can be decared. For nstance, an ob|ect of the cass defned above can be decared wth the foowng statement: payer Sachn, Dravd, Mohan ; 185 |Or| cass payer Sachn , Dravd, Mohan ; where Sachn and Dravd are two ob|ects of the cass payer. Both the ob|ects have ther own set of member varabes. Once the ob|ect s decared, ts pubc members can be accessed usng the dot operator wth the name of the ob|ect. We can aso use the varabe no_payer n the pubc secton wth a dot operator n functons other than the functons decared n the pubc secton of the cass. e.g. Sachn.getstats(); Dravd.showstats(); Mohan.no_payer = 10; .". Pu-lic, Pri0ate and Protected mem-ers' Cass members can ether be decared n pubc,protected or n the prvate sectons of the cass. But as one of the features of OOP s to prevent data from unrestrcted access, the data members of the cass are normay decared n the prvate secton. The member functons that form the nterface between the ob|ect and the program are decared n pubc secton ( otherwse these functons can not be caed from the program ). The member functons whch may have been broken down further or those, whch do not form a part of the nterface, are decared n the prvate secton of the cass. By default all the members of the class are private. The thrd access specfer protected" that s not used n the above exampe, pertans to the member functons of some new cass that w be nherted from the base cass. As far as non-member functons are concerned, private and protected are one and the same. .#. 8em-er Functions of a Class A member functon of the cass s same as an ordnary functon. Its decaraton n a cass tempate must defne ts return vaue as we as the st of ts arguments. You can decare or defne the functon n the cass specfer tsef, n whch case t s |ust ke a norma functon. But snce the functons wthn the cass specfer s consdered inline by the comper we shoud not defne arge functons and functons wth 186 contro structures, teratve statements etc shoud not be wrtten nsde the cass specfer. However, the defnton of a member functon dffers from that of an ordnary functon f wrtten outsde the cass specfer. The header of a member functon uses the scope operator (::) to specfy the cass to whch t beongs. The syntax s: return_type cass_name :: functon_name (parameter st) { : } e.g. vod payer :: getstats (vod) { : } vod payer :: showstats (vod) { : : } Ths notaton ndcates that the functons getstats () and showstats() beong to the cass payer. .(. Passing and /eturning 2-3ects Ob|ects can be passed to a functon and returned back |ust ke norma varabes. When an ob|ect s passed by content , the comper creates another ob|ect as a forma varabe n the caed functon and copes a the data members from the actua varabe to t. Ob|ects can aso be passed by address, whch w be dscussed ater. e.g. cass check { 187 pubc : check add(check); vod get() { cn >> a; } vod put() { cout << a; } prvate : nt a; }; vod man() { check c1,c2,c3; c1.get(); c2.get(); c3 = c1.add(c2); c3.put(); } check check :: add ( check c2) { check temp; temp.a = a + c2.a; return ( temp); } The above exampe creates three ob|ects of cass check. It adds the member varabe of two casses, the nvokng cass c1 and the ob|ect that s passed to the functon , c2 and returns the resut to another ob|ect c3. You can aso notce that n the cass add() the varabe of the ob|ect c1 s |ust referred as a where as the member of the ob|ect passed ..e. c2 s referred as c2.a . Ths s because the member functon w be ponted by the ponter named ths n the comper where as what we pass shoud be accessed by the extracton operator .. we may pass more than one ob|ect and aso norma varabe. we can return an ob|ect or a norma varabe from the functon. We have 188 made use of a temporary ob|ect n the functon add() n order to factate return of the ob|ect. .). Pointers to 2-3ects Passng and returnng of ob|ects s, however, not very effcent snce t nvoves passng and returnng a copy of the data members. Ths probem can be emnated usng ponters. Lke other varabes, ob|ects of cass can aso have ponters. Decarng a ponter to an ob|ect of a partcuar cass s same as decarng a ponter to a varabe of any other data type. A ponter varabe contanng the address of an ob|ect s sad to be pontng to that ob|ect. Ponters to ob|ects can be used to make a ca by address or for dynamc memory aocaton. |ust ke structure ponter, a ponter to an ob|ect aso uses the arrow operator to access ts members. Lke ponters to other data types, a ponter to an ob|ect aso has ony one word of memory. It has to be made to pont to an aready exstng ob|ect or aocated memory usng the keyword !new". e.g. strng str; // 4b'ect strng *sp; // *ointer to an ob'ect sp = &str; // (ssigns address of an eisting ob'ect sp = new strng // (llocates memory with new. A smpe exampe of usng ponters to ob|ects s gven beow. cass payer { pubc : vod getstats(vod); vod showstats(vod); prvate : char name|40|; nt age; nt runs; nt tests; foat average; foat cacaverage(vod); }; vod man() 189 { payer Sachn; Sachn.getstats(); Sachn.showstats(); payer *Dravd; Dravd = new payer; Dravd->getstats(); Dravd->showstats(); } .+. 5rra1 of 2-3ects As seen earer, a cass s a tempate, whch can contan data tems as we as member functons to operate on the data tems. Severa ob|ects of the cass can aso be decared and used. Aso, an array of ob|ects can be decared and used |ust ke an array of any other data type. An exampe w demonstrate the use of array of ob|ects. e.g. cass student { pubc : vod getdetas(); vod prntdetas(); prvate : nt rono; char name|25|; nt marks|6|; foat percent; }; vod student :: getdetas() { nt ctr,tota; cout << "enter rono"; cn >> rono ; 190 cout << "enter name"; cn >> name; cout << " enter 6 marks " ; for( ctr = 1 ;ctr <= 6 ; ctr++ ) { cn >> marks|ctr|; tota = tota + marks|ctr|; } percent = tota / 6; } vod student :: prntdetas () { cout << rono << name << percent ; } vod man() { student records|50|; nt x=0; cout << " How many students "; cn >> x; for ( nt =1; <= x; ++) { records||.getdeats(); } for ( nt =1; <= x; ++) { records||.prntdeats(); } } As can be seen above, an array of ob|ects s decared |ust ke any other array. Members of the cass are accessed, usng the array name quafed by a subscrpt. The statement, 191 records|y|.prntdetas(); nvokes the member funs prntdetas() for the ob|ect gven by the subscrpt y. For dfferent vaues of subscrpt, t nvokes the same member functon, but for dfferent ob|ects. .1.. 4he S$ecial Pointer Cthis= When severa nstances of a cass come nto exstence, t naturay foows that each nstance has ts own copy of member varabes. If ths were not the case, then for obvous reasons t woud be mpossbe to create more than one nstance of the cass. On the other hand, even though the cass member functons are encapsuated wth the data members nsde the cass defnton, t woud be very neffcent n terms of memory usage to repcate a these member functons and store the code for them wthn each nstance. Consequenty, ony one copy of each member functon per cass s stored n memory, and must be shared by all of the nstances of the cass. But ths poses a bg probem for the comper: How can any gven member functon of a cass knows whch nstance t s supposed to be workng on ? In other words, up to now n a cass member functon you have smpy been referrng to the members drecty wthout regard to the fact that when the nstantatons occur each data member w have a dfferent memory address. In other words, a the comper knows s the offset of each data member from the start of the cass. The souton to ths demma s that, n pont of fact, each member functon does have access to a ponter varabe that ponts to the nstance beng manpuated. Fortunatey ths ponter s supped to each member functon automatcay when the functon s caed, so that ths burden s not paced upon the programmer. Ths ponter varabe has a speca name this" (reserved word). Even though the this ponter s mpcty decared, you aways have access to t and may use the varabe name anywhere you seem approprate. e.g. 192 cass try_ths { pubc : vod prnt(); try_ths add(nt); prvate : nt var; }; vod prnt() { cout << var; cout << ths -> var ; } The functon prnt refers to the member varabe var drecty. Aso, an expct reference s made usng the this ponter. Ths speca ponter s generay used to return the ob|ect, whch nvoked the member functon. For exampe, vod man() { try_ths t1,t2; t2 = t1.add(3); t2.prnt(); } try_ths try_ths :: add(nt v) { var = var + v; return ( *ths); } In the above exampe f var for t1 s 10 and vaue n v s 2, then the functon add() adds them and var for t1 becomes 12 . We want to store ths n another ob|ect t2, whch can be done by returnng the ob|ect t1 usng *ths to t2. The resut of t2.prnt() now w be 12. :ereferencing the Pointer this 193 Sometmes a member functon needs to make a copy of the nvokng nstance so that t can modfy the copy wthout affectng the orgna nstance. Ths can be done as foows : try_ths temp(*ths); try_ths temp = *ths ; In OOP emphass s on how the program represents data. It s a desgn concept wth ess emphass on operatona aspects of the program. The prmary concepts of OOP s mpemented usng cass and ob|ects. A cass contans data members as we as functon members. The access specfers contro the access of data members. Ony the pubc members of the cass can access the data members decared n prvate secton. Once cass has been defned, many ob|ects of that cass can be decared. Data members of dfferent ob|ects of the same cass occupy dfferent memory area but functon members of dfferent ob|ects of the same cass share the same set of functons. Ths s possbe because of the nterna ponter *ths whch keeps track of whch functon s nvoked by whch ob|ect. 5ercises: 1. Defne a cass to mode a bankng system. The functon members shoud aow ntazng the data members, a query to factate for account and a facty to depost and wthdraw from the account. WAP to mpement the same. 2. Create a cass caed Tme that has separate nt member data for hours, mnutes and seconds. Wrte functons for acceptng tme and dspayng tme. ------------ -------------- -------------- ----------- ---------- Session " Constructor and Destructor Functons During this session you will learn about : Automatc ntazaton of data members - constructors Constructor wth one argument, mut arguments Usng the constructor 194 Destructor Defaut constructor and destructor Snce C++ supports the concept of user-defned casses and the subsequent ntatons of these casses, t s mportant that ntazaton of these nstantatons be performed so that the state of any ob|ect does not refect " garbage". One of the prncpes of C++ s that ob|ects know how to ntaze and ceanup after themseves. Ths automatc ntazaton and cean up s accompshed by two member functons the constructor and the destructor. ".1 Constructors By defnton, a constructor functon of some cass s a member functon that automatcay gets executed whenever an nstance of the cass to whch the constructor beongs comes nto exstence. The executon of such a functon guarantees that the nstance varabes of the cass w be ntazed propery. A constructor functon s unque from a other functons n a cass because t s not caed usng some nstance of the cass, but s nvoked whenever we create an ob|ect of that cass. A constructor may be overoaded to accommodate many dfferent forms of ntazaton for nstances of the cass. .e. for a snge cass many constructors can be wrtten wth dfferent argument sts . S1nta6 rules for <riting constructor functions Its name must be same as that of the cass to whch t beongs. It s decared wth no return type (not even vod). However, t w mpcty return a temporary copy of the nstance tsef that s beng created. It cannot be decared statc (a functon whch does not beong to a partcuar nstance), const( n whch you can not make changes). It shoud have pubc or protected access wthn the cass. Ony n very rare crcumstances the programmers decare t n prvate secton. 195 e.g. cass boxcass { pubc : boxcass ( nt x1, nt y1, nt x2, nt y2); vod dsp(vod); prvate : nt x1, y1; nt x2, y2 ; }; boxcass::boxcass(nt ax1,nt ay1, nt ax2, nt ay2) { x1 = ax1 ; y1 = ay1 ; x2 = ax2 ; y2 = ay2 ; } ".2.1 7sing the Constructor There are bascay three ways of creatng and ntazng the ob|ect. The frst way to ca the constructor s eplicitly as : boxcass bgbox = boxcass ( 1,1,25,79); Ths statement creates an ob|ect wth the name bgbox and ntazes the data members wth the parameters passed to the constructor functon. The above ob|ect can aso be created wth an implicit ca to the constructor : boxcass bgbox(1,1,25,79); Both the statements gven above are equvaent. Yet, another way of creatng and ntazng an ob|ect s by drect assgnment of the data tem to the ob|ect name. But# this approach wor0s if there is only one data item in the class. Ths s obvous because we cannot assgn more than one vaue at a tme to a varabe. e.g. 196 cass counter { pubc : counter ( nt c) // constructor. { count = c; }; prvate : nt count; }; we can now create an ob|ect as, counter cnt = 0; In the above exampe , ob|ect cnt s ntazed by a vaue zero at the tme of decaraton. Ths vaue s actuay assgned to ts data member count. Ths s the thrd way to ntaze an ob|ects data member. Thus, a the foowng statements to ntaze the ob|ects of the cass counter are equvaent: counter c1(20); counter c1 = counter(30); counter c1= 10; Once the constructor for a cass has been decared and defned, the program must use t. In other words, ob|ects cannot be decarng wthout ntazng them. For nstance, n the above exampe, an ob|ect of cass counter has to be decared and ntazed n one of the three ways gven above. Unntazed ob|ects ke : counter cx,cy; are not aowed. However, sometmes the data members of an ob|ect may not requre ntazaton. May be they have to be accepted from the user ater. C++ s not so rgd n ts approach. It has defned means of crcumventng such a probem. The key to defnng an unntazed ob|ect s to have a constructor wth defaut arguments. 197 e.g. cass counter { pubc : counter ( nt c = 0) // )onstructor. { count = c; }; prvate : nt count; }; In the exampe above, f the actua argument s not gven, then the vaue of the forma varabe c n the constructor defauts to zero. Thus, decaraton of ob|ects of ths cass can be unntazed as we. counter c1(20); counter c2 = counter(30); counter c3 = 10; counter c4,c5; A constructor can be used to generate temporary nstances as we , as gven beow : counter create( nt cc) { return counter(c); } An array of ob|ects can be ntazed at the tme of decaraton. A constructor has to be provded foe the same. The exampe gven beow uses the cass empoyee to ustrate ths. cass empoyee { pubc : empoyee(char *n, nt a, doube s); 198 prvate: char name|40|; nt age; doube saary; }; empoyee :: empoyee (char *n , nt a, doube s) { strcpy( name, n ); age = a; saary = s; } vod man() { empoyee E|3| = { empoyee("sanat",25,9600), empoyee("sanket",35,12600), empoyee("prya",28,21600) }; } ".3. :estructors A destructor functon gets executed whenever an nstance of the cass to whch t beongs goes out of exstence. The prmary usage of a destructor functon s to reease memory space that the nstance currenty has reserved. S1nta6 rules for <riting a destructor function Its name s the same as that of the cass to whch t beongs, except that the frst character of the name s the symbo tde ( - ). It s decared wth no return type ( not even vod ) snce t cannot ever return a vaue. It cannot be statc, const or voate. It takes no nput arguments , and therefore cannot be overoaded. It shoud have pubc access n cass decaraton. 199 Generay the destructor cannot be caed expcty (drecty) from the program. The comper generates a cass to destructor when the ob|ect expres. Cass destructor s normay used to cean up the mess from an ob|ect. Cass destructors become extremey necessary when cass constructor use the new operator, otherwse t can be gven as an empty functon. However, the destructor functon may be caed expcty aowng you to reease the memory not requred and aocate ths memory to new resources, n Borand C++ verson 3.1. 3.7.The default )onstructor and Destructor If you fa to wrte a constructor and destructor functon, the comper automatcay suppes them for you. These functons have pubc access and essentay do nothng usefu. If you were to wrte these functons yourseves, ths woud ook ke: cass empoyee { pubc : empoyee() { } -empoyee(); { } }; ".". 5 Constructi0e %6am$le Consder an exampe , to mode a user-defned data type for strngs. The ob|ect smuates a character array ( strng ) usng a character ponter and an nteger varabe for ts actua sze, whch can be determned at ts run-tme. The ob|ect doesnt use a character array , snce t may mpose a mt on the number of characters that can be stored. e.g. # ncude <ostream.h > # ncude < strng.h> cass strng 200 { pubc : strng ( char *s); -strng(); vod putstr();
prvate : char *cptr; nt sze; }; vod man(vod) { strng s1(" Heo student \n"); strng s2 = " Wecome to C++ \n"; strng s3 = strng ( " ts fun \n"); s1.putstr(); s2.putstr(); s3.putstr(); } strng::strng(char *s) { sze = stren(s); cptr = new char|sze + 1|; strcpy(cptr,s); } strng::-strng() { deete cptr; } vod strng::putstr() { cout << cptr; } The cass defned n the above exampe contans a character ponter, whch aocates memory at runtme, after determnng the actua sze requred. Ths programme demonstrates the use of cass aong wth the constructor and destructor to create a user defned data 201 type Strng. The constructor functon contans a defaut argument of nu character, whch w be assgned to the varabe cptr n the absence of an actua parameter. The destructor uses the delete operator to reease the memory aocated by the constructor . A cass can contan data members as we as functon members. A member functon s the ony way to access the prvate secton members of a cass. For ntazng the data members of the cass, we may wrte a functon |ust ke any other functon. But then, we have to nvoke ths functon expcty. C++ provdes a speca functon caed constructor. Ths functon s caed automatcay when we create an ob|ect. It contans code to ntaze the member varabes usng the forma parameters f they are passed va ob|ects. If we wrte such a functon then we must pass parameters each tme. To evade ths probem we can wrte many constructors to gve some fexbty to create ob|ects wth dfferent parameter sts. We can aso use defaut arguments n the constructor. C++ aso provdes a speca member functon caed destructor, whch s caed automatcay when an ob|ect expres as per the scope rues. Both constructor and destructors do not have return types, not even vod. The destructor cannot have any parameters as we. %6ercises 1. Create a cass caed Tme that has a separate data members for day, month and year. A constructor shoud be used to ntaze these members. Then wrte a functon to add these dates and store the resut n a thrd ob|ect and dspay t. 2. WAP to add co-ordnates of the pane. The cass contans x and y co-ordnates. Create three ob|ects. Use a constructor to pass one par of co-ordnates and a functon to accept the second par. Add these varabes of two ob|ects and store the resut n the thrd. -------- ------- -------- -------- --------- ----------- Session # 202 2$erator 20erloading During this session you will learn about: Introducton to Operator Overoadng. Operator Overoadng Fundamentas. Impementng the operator functons. Rues for overoadng the operators. Ponter oddtes (assgnment) and Operator Overoadng. Copy Constructor (to sove the probem of ntazaton). Converson functons. A computer anguages have but n types ke ntegers, rea numbers, characters and so on. Some anguages aow us to create our own data types ke dates, compex numbers, co-ordnates of a pont. Operatons ke addton, comparsons can be done ony on basc data types and not on derved (user-defned) data types. If we want to operate on them we must wrte functons ke compare (), add (). e.g. f (compare (v1, v2) = = 0) : : where v1 and v2 are varabes of the new data type and compare () s a functon that w contan actua comparson nstructons for comparng ther member varabes. However, the concept of Operator Overoadng, n C++, aows a statement ke f (v1 = = v2) : : where the operaton of comparng them s defned n a member functon and assocated wth comparson operator(==). The abty to create new data types, on whch drect operatons can be performed s caed as extensbty and the abty to assocate an exstng operator wth a member functon and use t wth the ob|ects of ts cass, as ts operands, s caed as Operator Overoadng. 203 Operator Overoadng s one form of Polymorphism ,an mportant feature of ob|ect-orented programmng .Poymorphsm means one thng havng many forms, .e. here an operator can be overoaded to perform dfferent operatons on dfferent data types on dfferent contexts. Operator Overoadng s aso caed operatona poymorphsm. Another form of poymorphsm s functon overoadng. #.1. 2$erator 20erloading Fundamentals The C anguage uses the concept of Operator Overoadng dscreety. The astersk (*) s used as mutpcaton operator as we as ndrecton (ponter) operator. The ampersand (&) s used as address operator and aso as the btwse ogca AND operator. The comper decdes what operaton s to be performed by the context n whch the operator s used. Thus, the C anguage has been usng Operator Overoadng nternay. Now, C++ has made ths facty pubc. C++ can overoad exstng operators wth some other operatons. If the operator s not used n the context as defned by the anguage, then the overoaded operaton, f defned w be carred out. For exampe, n the statement x = y + z; If x, y and z are nteger varabes, then the comper knows the operaton to be performed. But, f they are ob|ects of some cass, then the comper w carry out the nstructons, whch w be wrtten for that operator n the cass. #.2. Im$lementing 2$erator Functions The genera format of the Operator functon s: return_type operator o$ ( argument st ); Where op s the symbo for the operator beng overoaded. Op has to be a vad C++ operator, a new symbo cannot be used. e.g. Let us consder an exampe where we overoad 204 unary arthmetc operator ++. cass Counter { pubc : Counter(); vod operator++(vod); prvate : nt Count; }; Counter::Counter() { Count = 0; } vod Counter::operator++(vod) { ++ Count ; } vod man() { Counter c1; c1++; // ncrements Count to 1 ++c1; // ncrements Count to 2 } In man() the ncrement operator s apped to a specfc ob|ect. The functon tsef does not take any arguments. It ncrements the data member Count. Smary, to decrement the Counter ob|ect can aso be coded n the cass defnton as: vod operator--(vod) { -- Count ; } and nvoked wth the statement --c1; or c1--; 205 In the above exampe , the comper checks f the operator s overoaded and f an operator functon s found n the cass descrpton of the ob|ect, then the statement to ncrement gets converted, by the comper, to the foowng: c1.operator++(); Ths s |ust ke a norma functon ca quafed by the ob|ects name. It has some speca characters ( ++) n t. Once ths converson takes pace, the comper treats t |ust ke any other member functon from the cass. Hence, t can be seen that such a facty s not a very bg overhead on the comper. 8owever# the operator function in the above eample has a potential glitch. 4n overloading # it does not wor0 eactly li0e it does for the basic data types. 9ith the increment and decrement operators overloaded# the operator function is eecuted first# regardless of whether the operator is postfi or prefi. If we want to assgn vaues to another ob|ect n man() we have to return vaues to the cang functon. Counter Counter :: operator++(vod) { Counter temp; temp.Count = ++ Count ; return ( temp ); } vod man() { Counter c1,c2; c1 = c2 ++; //ncrements to 1, then assgns. } In ths exampe , the operator functon creates a new ob|ect temp of the cass Counter, assgns the ncremented vaue of Count to the data member of temp and returns the new ob|ect. Ths ob|ect s returned to man(). We can do ths n another way by creatng a nameess temporary ob|ect and return t. cass Counter 206 { pubc : Counter(); // CONSTRUCTOR WITHOUT ARGUMENTS Counter( nt c); // CONSTRUCTOR WITH 1 ARGUMENT Counter operator++(vod);
prvate : nt Count; }; Counter::Counter() // CONSTRUCTOR WITHOUT ARGUMENTS { Count = 0; } Counter::Counter( nt c) // CONSTRUCTOR WITH 1 ARGUMENT { Count = c; } Counter Counter::operator++(vod) { ++ Count ; return Counter(Count); } One change we can see s a constructor wth one argument. No new temporary ob|ect s expcty created. However return statement creates an unnamed temporary ob|ect of the cass Counter ntazes t wth the vaue n Count and returns the newy created ob|ect. Hence one argument constructor s requred. Yet another way of returnng an ob|ect from the member functon s by usng the this ponter. Ths speca ponter ponts to the ob|ect, whch nvokes the functon. The constructor wth one argument s not requred n ths approach. Counter Counter :: operator++(vod) { ++ Count ; return ( * ths); } 207 Consder a cass COMPLEX for Compex numbers. It w have a rea and an magnary member varabe. Here we can see binary operator overloaded and also how to return values from the functions. cass COMPLEX { pubc: COMPLEX operator+(COMPLEX); prvate: nt rea, magnary; }; Suppose that C1, C2 and C3 are ob|ects of ths cass. Symbocay addton can be carred out as C3 = C1 + C2; The actua nstructons of the operator are wrtten n a speca member functon. e.g. COMPLEX COMPLEX :: operator+( COMPLEX C2) { COMPLEX temp; temp.rea = rea + C2.rea; temp.magnary = magnary + C2. magnary; return (temp); } The above exampe shows how Operator Overoadng s mpemented. It overoads "+" operator to perform addton on ob|ects of COMPLEX cass. Here we have overoaded a bnary operator(+). #.3. /ules for o0erloading an o$erator 208 Ths summarzes the most mportant ponts you need to know n order to do operator functon overoadng. The ony operators you may overoad are the ones from the C++ st and not a of those are avaabe. You cannot arbtrary choose a new symbo (such as @) and attempt to "overoad t. Start by decarng a functon n the norma functon fashon, but for the functon name use the expresson: Operator op Where op s the operator to be overoaded. You may eave one or more spaces before op. The pre-defned precedence rues cannot be changed. .e. you cannot, for exampe, make bnary + have hgher precedence than bnary *. In addton, you cannot change the assocatvty of the operators. The unary operators that you may overoad are: ;D indirect mem-er o$erator E not & address A dereference + $lus - minus ++ $refi6 increment ++ $ostfi6 increment ($ossi-le in 54 F 4 0ersion 2.1) ;; $ostfi6 decrement ;; $refi6 decrement ($ossi-le in 54 F 4 0ersion 2.1) G one=s com$lement 4he -inar1 o$erators that 1ou ma1 o0erload are' (), HI, ne<, delete, A, J , K, + , ; , LL,DD, L, LM, D, DM, MM,E M, F, N, O, FF, OO, M, AM, JM, KM, +M, ;, M, LLM, DDM, FM,E M, NM, P,P(Comma). 4he o$erators that can not -e o0erloaded are' . direct mem-er 209 .A direct $ointer to mem-er '' sco$e resolution Q' ternar1 9o default arguments are allo<ed in o0erloaded o$erator functions. 5s <ith the $redefined o$erators, an o0erloaded o$erator ma1 -e unar1 or -inar1. If it is normall1 unar1, then it cannot -e defined to -e -inar1 and 0ice 0ersa. Bo<e0er, if an o$erator can -e -oth unar1 and -inar1, then it can -e o0erloaded either <a1 or -oth. 4he o$erator function for a class ma1 -e either a non; static mem-er or glo-al friend function. 5 non;static mem-er function automaticall1 has one argument im$licitl1 defined, namel1 the address of the in0o@ing instance (as s$ecified -1 the $ointer 0aria-le this). Since a friend function has no this $ointer, it needs to ha0e all its arguments e6$licitl1 defined). 5t least one of the arguments to the o0erloaded function e6$licit or im$licit must -e an instance of the class to <hich the o$erator -elongs. Consider an e6am$le, <hich de$icts o0erloading of +M (Com$ound assignment), L, D, MM (%&ualit1),EM, + (Concatenation) using String class. class String R $u-lic ' String ()S String ( char str HI )S 0oid $utstr()S String o$erator + (String)S String o$erator +M (String s2)S int o$erator L (String s2)S int o$erator D (String s2)S int o$erator MM (String s2)S int o$erator EM (String s2)S $ri0ate ' char sH1..IS
TS 210 String''String () JJ C29S4/7C42/ UI4B R JJ 92 5/V78%94S sH.I M .S TS String'' String( char str HI ) JJ C29S4/7C42/ UI4B R JJ 29% 5/V78%94 strc$1(s,str) TS 0oid String'' $utstr()JJ F79C4I29 42 P/I94 S4/I9V R cout LL s S TS String String '' o$erator+(String s2) R String tem$S strc$1(tem$.s,s)S strcat(tem$.s,s2.s)S return (tem$)S T String String '' o$erator+M(String s2) R
strcat(s,s2.s)S return (Athis)S T int String''o$erator L (String s2) R return (strcm$ (s, s2.s ) L .)S
T int String''o$erator D (String s2) 211 R return (strcm$ (s, s2.s ) D .)S T int String''o$erator MM (String s2) R return (strcm$ (s, s2.s ) MM .)S T int String''o$erator EM (String s2) R return (strcm$ (s, s2.s ) EM .)S T 0oid main() R String s1 M W<elcome WS String s2 M W to the <orld of c++XS String s3S cout LL endl LL Ws1 M WS s1.$utstr()S cout LL endl LL Ws2 M WS s2.$utstr()S s3 M s1 + s2S cout LL endl LL W s3 M WS s3.$utstr()S String sS cout LLendlLLX AAAAAAAAAAAAAAAAAAAAAXS s M s1 + M s2S cout LL endl LL W s M WS s.$utstr()S String s" M W 5???? WS String s# M W 5$$le WS 212 if( s" L s# ) R s".$utstr()S cout LL X L XS s#.$utstr()S T else if( s" D s# ) R s".$utstr()S cout LL X D XS s#.$utstr()S T else if( s" MM s# ) R s".$utstr()S cout LL X M XS s#.$utstr()S T else if( s" EM s# ) R s".$utstr()S cout LL X L XS s#.$utstr()S T T 2ut$ut' S1 M <elcome S2 M to the <orld of C++ S3 M <elcome to the <orld of c++ AAAAAAAAAAAAAAAAAAAAAAAAAA S M <elcome to the <orld of c++ 6.4. Ponter Oddtes and Operator Overoadng Consider an e6am$le , <here the data mem-ers contain $ointers and ha0e -een allocated memor1 using the o$erator new. In this case using an assignment o$erator to assign one o-3ect to another <ill result in the $ointer 0aria-le -eing co$ied rather than the contents at the address. 4he follo<ing e6am$le e6$lains this $ro-lem. 213 class String R $u-lic ' String (char As M WX) JJ C29S4/7C42/ R si?e M strlen(s)S c$tr M ne< char Hsi?e + 1IS strc$1(c$tr,s)S TS GString() R delete c$trS T 0oid $utstr() JJ F79C4I29 42 P/I94 S4/I9V R cout LL c$tr S TS $ri0ate ' char Ac$trS int si?eS TS 0oid main() R String s1(Whello students W)S String s2S s2 M s1S JJ 5ssignment s1.$utstr()S s2.$utstr()S T 214 4he constructor function allocates a string and co$ies the contents of its formal 0aria-le in it. 4he assignment o$erator in main() assigns the o-3ect s1 to s2. the data mem-ers= c$tr and si?e , of o-3ect s1, gets assigned to s2. 4he out$ut of the $rogram is ' hello students hello students 9ull $ointer assignment Uh1 does the $rogram gi0e a Cnull $ointer assignment= message Q 5fter the $rogram is o0er, the destructor function is called automaticall1, <hich releases the memor1 allocated -1 new to the data mem-er c$tr. !ut, after the assignment, the data mem-er c$tr of -oth the o-3ects $oint to the same location in the memor1. 4hus, the delete o$erator called for the first o-3ect releases the memor1 and for the second call attem$ts to release the same memor1 location again, resulting in the error message. 4he solution to this $ro-lem is to define an o$erator function for the assignment o$erator . It can -e done as follo<s' String o$erator M (String s2) R delete c$trS si?e M strlen ( s2.c$tr )S c$tr M ne< char Hsi?e + 1IS strc$1(c$tr, s2.c$tr)S return (Athis)S T 2n including this mem-er function in the class definition of the a-o0e e6am$le , the $rogram out$uts the follo<ing ' hello students hello students Bence, the o$erator function for assignment of an o-3ect to another of the same class remo0es the &uir@s associated <ith $ointers as data mem-ers. 6.5. Copy Constructor 215 Similar $ro-lems occur at the time of initiali?ation of an o-3ect <ith another of the same class . 5lthough initiali?ation and assignment -oth assign 0alues, initiali?ation ta@es $lace onl1 once <hen the o-3ect is created, <hereas assignment can occur <hene0er desired in the $rogram. 4herefore, the1 differ conce$tuall1. String s1(Wthis is a stringX)S String s2(s1)S JJInitiali?ation 4he first statement declares an o-3ect s1 and $asses a string as an argument to its constructor. 4he data mem-ers of s1 are initiali?ed using the String. 4he second statement declares another o-3ect s2 and contains an o-3ect as its argument. Since there is no constructor ha0ing an o-3ect as its formal argument, the com$iler itself initiali?es the second o-3ectCs data mem-ers <ith those of the formal o-3ect . 5nd since one of the mem-ers is a $ointer, the $ro-lem of assignment arises here too. 20erloading the assignment o$erator sol0es the $ro-lem of assignment. :efining a constructor function that ta@es o-3ect as its argument sol0es the $ro-lem of initiali?ation. 4his constructor is also called copy constructor . It is called in three conte6ts ' Uhen one o-3ect of a class is initiali?ed to another of the same class. Uhen an o-3ect is $assed -1 0alue as an argument to a function. Uhen a function returns an o-3ect. 5ll these situations result in a co$1 of one o-3ect to another. Bence , a co$1 constructor is 0er1 im$ortant if the class contains $ointer as data mem-er . 5 co$1 constructor for the a-o0e e6am$le is gi0en -elo< ' String (const String Fs2) R si?e M s2.si?eS c$tr M ne< charHsi?e + 1IS strc$1(c$tr,s2.c$tr)S T 216 It is 3ust li@e a normal constructor -ut the argument here is an o-3ect of the class . o-0iousl1 this e6isting instance should never -e modified -1 the co$1 constructor function , so the @e1<ord const should -e used in the function signature. #.#. Con0ersion Functions Converson functons are member functons used for the foowng purposes: 1. Converson of ob|ect to basc data type. 2. Converson of basc data type to ob|ect. 3. Converson of ob|ects of dfferent casses. Conversons of one basc data type to another are automatcay done by the comper usng ts own but-n routnes (mpct) and t can be forced usng but-n converson routnes (expct). However, snce the comper does not know anythng about user-defned types (casses), the program has to defne converson functons. e.g. nt = 2, | =19; foat f = 3.5; = f; // gets the vaue 3 , mpct converson f = (foat) |; // f gets 19.00, expct converson #.#.1. Con0ersion from !asic to 7ser;:efined 0aria-le Consder the foowng exampe. cass Dstance { pubc : Dstance(vod) // Constructor wth no { // argument feet = 0; nches = 0.0; }; Dstance(foat metres) { foat f; // Constructor wth 217 f = 3.28 * metres; // one argument feet = nt(f); // aso used for nches = 12 * ( f feet);// converson }; vod dspay(vod) { cout << " Feet = " << feet <<","; cout << " Inches = " << nches << end; }; prvate : nt feet; foat nches; }; vod man (vod) { Dstance d1 = 1.25; // Uses 2 nd constructor Dstance d2; // Uses 1 st constructor foat m; d2 = 2.0 ; // Uses 2 nd constructor
cout << " 1.25 metres s : " << d1.showdst() ; cout << " 2.0 metres s :" << d2.showdst(); } Output : 1.25 metres s :FEET = 4 , INCHES = 1.199999 2.0 metres s :FEET = 6 , INCHES = 6.719999 The above program converts dstance n metres ( basc data type) nto feet and nches ( members of an ob|ect of cass Dstance ). The decaraton of frst ob|ect d1 uses the second constructor and converson takes pace. However, when the statement encountered s d2 = 2.0; 218 The comper frst checks for an operator functon for the assgnment operator. If the assgnment operator s not overoaded, then t uses the constructor to do the converson. #.#.2. Con0ersion from 7ser;:efined to !asic data t1$e The foowng program uses the program n the prevous secton to convert the Dstance nto metres(foat). cass Dstance { pubc : Dstance(vod) // Constructor wth no { // argument feet = 0; nches = 0.0; }; Dstance(foat metres) { foat f; // Constructor wth f = 3.28 * metres; // one argument feet = nt(f); // Aso used for nches = 12 * ( f feet); //converson }; operator foat(vod) // Converson functon { // from Dstance to foat foat f; f = nches / 12; f = f + foat (feet); return ( f/ 3.28 ); }; vod dspay(vod) { cout << " Feet = " << feet <<","; cout << " Inches = " << nches << end; }; prvate : nt feet; foat nches; 219 }; vod man (vod) { Dstance d1 = 1.25; // Uses 2 nd constructor Dstance d2; // Uses 1 st constructor foat m; d2 = 2.0 ; // Uses 2 nd constructor
cout << " 1.25 metres s :" << d1.showdst (); cout << " 2.0 metres s :" << d2.showdst ();
cout << " CONVERTED BACK TO METRES "; m = foat ( d1 ); // Cas functon expcty. cout << " d1 = " << m; m = d2; // Cas functon expcty. cout << " d2 = " << m; } Output:
1.25 metres s :FEET = 4 ,INCHES = 1.199999 2.0 metres s :FEET = 6 ,INCHES = 6.719999 CONVERTED BACK TO METRES d1 = 1.25 d2 = 2.00 Actuay, ths converson functon s nothng but overoadng the typecast operator foat(). The converson s acheved expcty and mpcty. m = foat (d1); s forced where as , n the second assgnment statement
m = d2; 220 frst the comper checks for an operator functon for assgnment ( = ) operator and f not found t uses the converson functon. The conversion function must not define a return type nor should it have any arguments. #.#.3. Con0ersion !et<een 2-3ects of :ifferent Classes Snce the comper does not know anythng about the user- defned type, the converson nstructons are to be specfed n a functon. The functon can be a member functon of the source cass or a member functon of the destnaton cass. We w consder both the cases. Consder a cass DstFeet whch stores dstance n terms of feet and nches and has a constructor to receve these. The second cass DstMetres store dstance n metres and has a constructor to receve the member. #.#.3.1. Con0ersion function in the Source Class cass DstFeet { pubc : DstFeet(vod) // Constructor wth no { // argument feet = 0; nches = 0.0; }; DstFeet(nt ft,foat n) { feet = ft; nches = n }; vod ShowFeet(vod) { cout << " Feet = " << feet << ","; cout << " Inches = " << nches << end; }; prvate : nt feet; foat nches; 221 }; cass DstMetres { pubc: DstMetres(vod) { metres = 0 ; // constructor 1. } DstMetres(foat m) { metres = m ; // constructor 2. } vod ShowMetres(vod) { cout << " Metres = " << metres << end; }; operator DstFeet(vod) // converson { // functon foat ffeet, nches; nt feet;
dm1.ShowMetres(); df1.ShowFeet(); } In the above exampe, DstMetres contans a converson functon to convert the dstance from DstMetres ( source cass), to DstFeet ( destnaton cass). The statement to convert one ob|ect to another df1 = dm1; cas the converson functon mpcty. It coud aso have been caed expcty as df1 = DstFeet(dm1); #.#.3.2.Con0ersion function in the :estination Class cass DstMetres { pubc: DstMetres(vod) { metres = 0 ; // Constructor 1. } DstMetres(foat m) { metres = m ; // constructor 2. } vod ShowMetres(vod) { cout << " Metres = " << metres << end; }; foat GetMetres(vod) { return(metres); } prvate: 223 foat metres; }; cass DstFeet {
pubc : DstFeet(vod) // Constructor1 wth no { // argument feet = 0; nches = 0.0; }; DstFeet(nt ft,foat n) { feet = ft; nches = n; }; vod ShowFeet(vod) { cout << " Feet = " << feet << end; cout << " Inches = " << nches << end; }; DstFeet( DstMetres dm) // Constructor 3 { foat ffeet; ffeet = 3.28 * dm.GetMetres(); feet = nt (ffeet); nches = 12 * (ffeet feet); }; prvate : nt feet; foat nches; }; vod man (vod) { DstMetres dm1 = 1.0; // Uses 2 nd constructor // cass DstMetres DstFeet df1; // Uses 1st constructor 224 // cass DstFeet df1 = dm1 ; // OR df1 = DstFeet(dm1); // Uses 3 rd converson functon dm1.ShowMetres(); df1.ShowFeet(); } Ths program works same as prevous functon. Here constructor s wrtten n the destnaton cass. Aso, we can see a new functon GetMetres() . The functon returns the data member metres of the nvokng ob|ect. The functon s requred because the constructor s defned n the DstFeet cass and snce metres s a prvate member of the DstMetres cass, t cannot be accessed drecty n the constructor functon n the DstFeet cass. Snce you can use any of the above methods, t s strcty a matter of choce whch method you choose to mpement. 4a-le for 41$e Con0ersions Operaton Functon n Destnaton Cass Operaton Functon n Source Cass Basc to cass Constructor Not Aowed Cass to Basc Not Aowed Converson Functon Cass to Cass Constructor Converson Functon 4his session co0ered 1et another conce$t of 22P Y Pol1mor$hism. It means one thing ha0ing man1 forms. It is 0er1 $o<erful, 1et, sim$le conce$t <hich gi0es the C++ language a facilit1 to redefine itself into a ne< language. 4here are t<o t1$es of Pol1mor$hism; o$erational and 225 functional. 4his session co0ered o$erational $ol1mor$hism also called as o$erator o0erloading. Ue <ill see function o0erloading in future. Exercses 1. WAP to add 2 compex number usng OOT(Operator Overoadng technques). 2. WAP to add 2 tmes usng OOT and dspay the resutant tme n watch format. 3. WAP to add, subtract and mutpy 2 matrces usng OOT. Sort an array of ob|ects. Each ob|ect has a strng as a member varabe. Overoad >= or <= operators to compare the two strngs. { make use of constructors and destructors whenever possbe } 4. WAP to create a cass caed DATE . Accept 2 vad dates n the form of dd/mm/yyyy. Impement the foowng by overoadng the operators Y and + . Dspay the resut after every operaton. a) no_of_dasy = d1 d2, where d1 and d2 are DATE ob|ects; d1 > = d2 ; and no_of_days s an nteger. b) d1 = d1 + no_of_days - where d1 s a DATE ob|ect and no_of_days s an nteger. 5. Modfy the matrx program (program 3) sghty. Overoad == operator to compare 2 matrces to be added or subtracted. .e., whether the coumn of frst and the row of second matrx are same or not. f(m1==m2) { m3=m1+m2; m4=m1-m2; } ese dspay error; 6. WAP to concatenate 2 strngs by usng a copy constructor. ------------ --------------- ---------------- -------------- Session ( Function 20erloading and /eferences 226 During this session you will learn about : Functon overoadng. Need to overoad functons. Precautons to be taken whe overoadng functons. Ca by reference. Passng and returnng reference varabes. Why usng references s a must n some occasons. Reference oddtes. 4he $re0ious session co0ered o$erator o0erloading. 2$erator o0erloading is nothing -ut defining a mem-er function, for a $articular o$erator, <hich <ill -e in0o@ed <hen the o$erator is used <ith o-3ects of that class. 4his is also called o$erational $ol1mor$hism. 4he second form of $ol1mor$hism in C++ is functional $ol1mor$hism also called function overloading. 7.1. Functon Overoadng Functon overoadng s a form of poymorphsm. Functon overoadng factates defnng one functon havng many forms. In other words t factates defnng severa functons wth the same name, thus overoadng the functon names. Lke n operator overoadng, even here, the comper uses context to determne whch defnton of an overoaded functon s to be nvoked. Functon overoadng s used to defne a set of functons that essentay, do the same thng, but use dfferent argument sts. The argument st of the functon s aso caed as the functons sgnature. You can overoad the functon ony f ther sgnatures are dfferent. The dfferences can be 1. In number of arguments, 2. Data types of the arguments, 3. Order of arguments, f the number and data types of the arguments are same. e.g. nt add( nt, nt ); nt add( nt, nt, nt ); 227 foat add( foat, foat ); foat add( nt, foat, nt ); foat add(nt,nt,foat); The compiler cannot distinguish if the signature is same and only return type is different. 8ence# it is a must# that their signature is different. The following functions therefore raise a compilation error. e.g. foat add( nt, foat, nt ); nt add( nt, foat, nt ); Consder the foowng exampe, whch rases a gven number to a gven power and returns the resut. ong ong_rase_to(nt num, nt power) { ong p = 1; for( nt = 1; <= power ; ++ ) { p = p * num ; } return p; } doube doube_rase_to( doube num, nt power) { doube dp = 1; for( nt = 1; <= power ; ++ ) { dp = dp * num ; } return dp; } vod man(vod) { cout<<"2 rase to 8 s <<ong_rase_to(2,8); 228 cout<<"2.5 rase to 4 s <<doube_rase_to(2.5,4); } In C we woud requred to wrte 2 dfferent functon names as can be seen from the above exampe. These functons do dentca tasks. However usng functon overoadng technques we can wrte the same program n C++ as shown: ong rase_to(nt num, nt power) { ong p = 1; for( nt = 1; <= power ; ++ ) { p = p * num ; } return p;
} doube rase_to( doube num, nt power) { doube dp = 1; for( nt = 1; <= power ; ++ ) { dp = dp * num ; } return dp;
} vod man(vod) { cout<<"2 rase to 8 s <<rase_to(2,8); cout<<"2.5 rase to 4 s <<rase_to(2.5,4); } The man () functon makes two cas to the functon rase_to() once wth 2 ntegers as arguments and agan wth an nteger and a doube. The comper uses the context to determne 229 whch of the functons to nvoke. Thus, frst tme t nvokes frst functon and then the second one. :.;. *recautions with function overloading Functon overoadng s a boon to desgners, snce dfferent names for smar functons need not be thought of, whch often s a cumbersome process gven that many tmes peope run out of names. But, ths facty shoud not be overused, est t becomes an overhead n terms of readabty and mantenance. Ony those functons, whch bascay do the same task, on dfferent sets of data, shoud be overoaded. (.3. Call -1 /eference Passng varabes(parameters) to a functon n C can be done n two ways pass by vaue, aso caed as ca by vaue and pass by address or aso caed as ca by address. C++ however , gves one more way to ca a functon ca by reference. In ca by vaue , a copy of the actua contents of the varabes s passed to the functon. In ths case, changes made to the forma varabe , as they are caed, are not refected back n the cang functon. Passng an address aows changes to be made drecty to the memory, whch are occuped by the actua varabe. However, a ca by address requres the forma varabe to be consdered as ponter and thus the ndrecton operator has to be used wth them. A reference on the other hand, s another name, for a prevousy defned varabe. In other words, after a reference s defned for a partcuar varabe, usng ts orgna name as we as the reference can refer to the varabe. Hence, a reference s nothng but an aas. Thus not passng a copy (ca by vaue) saves tme and s effcent. It does not have to create a temporary varabe /. And not passng the address(ca by address), emnates the use of ponters n the caed functons. But, at the same tme, the changes made to a forma varabe , usng ts reference or aas can be refected back n the cang functon. (.. 7sage of /eference ,aria-les. 230 C and C++ , both use the ampersand ( &) symbo as the address operator. It s aso overoaded to perform bnary AND operaton on ts operands. C++, once more overoads ths operator and uses t to decare a reference varabe . e.g. vod man() { nt num1 = 10, num2 = 200; nt &ref = num1; cout << "num1 = " << num1 << end; cout << "num2 = " << num2 << end; cout << "ref = " << ref << end; // & used ony to // decare. ref = num2; cout << " After change " <<end; cout << "num1 = " <<num1 << end; cout << "num2 = " <<num2 << end; cout << "ref = " << ref << end; } Output : num1 = 10 num2 = 200 ref = 10 After change num1 = 200 num2 = 200 ref = 200 A reference varabe decared n a functon shoud be ntazed at the tme of ts decaraton tsef. Aso, once a reference has been made to a varabe, t cannot be changes to refer to another varabe. The program gven above shows the resut of assgnng another varabe to a reference varabe. the output of the program shows that assgnng a varabe to a reference varabe, actuay assgns ts contents the orgna one. Hence , the reference to a partcuar varabe may not be changed ater n the program. 231 (.". Passing /eference to Functions. Reference varabes are partcuary usefu when passng to functons. The changes made n the caed functons are refected back to the cang functon . The program uses the cassc probem n programmng, swappng the vaues of two varabes. e.g. vod va_swap(nt x, nt y) // Ca by Vaue { nt t; t = x; x = y; y = t; } vod add_swap(nt *x, nt *y) // Ca by Address { nt t; t = *x; *x = *y; *y = t; } vod va_swap(nt &x, nt &y) // Ca by Reference { nt t; t = x; x = y; y = t; } vod man() { nt n1 = 25, n2 = 50; cout << "Before ca by vaue : "; cout << " n1 = " << n1 << " n2 = " << n2 << end; 0alZs<a$( n1, n2 )S 232 cout << " After ca by vaue : "; cout << " n1 = " << n1 << " n2 = " << n2 << end; cout << "Before ca by address : "; cout << " n1 = " << n1 << " n2 = " << n2 << end; 0alZs<a$( Fn1, Fn2 )S cout << " After ca by address : "; cout << " n1 = " << n1 << " n2 = " << n2 << end; cout << "Before ca by reference: "; cout << " n1 = " << n1 << " n2 = " << n2 << end; 0alZs<a$( n1, n2 )S cout << " After ca by vaue : " ; cout << " n1 = " << n1 << " n2 = " << n2 << end; } Output : Before ca by vaue : n1 = 25 n2 = 50 After ca by vaue : n1 = 25 n2 = 50 // x = 50, y = 25 Before ca by address : n1 = 25 n2 = 50 After ca by address : n1 = 50 n2 = 25 //x = 50, y = 25 Before ca by reference: n1 = 50 n2 = 25 After ca by reference : n1 = 25 n2 = 50 //x = 25, y = 50 You can see that the ony dfference n wrtng the functons n ca by vaue and ca by reference s whe recevng the parameters where as n pass by address the functon body has some changes, .e. they use (*) ndrecton operator to manpuate the varabes. (.#. /eturning /eferences from Functions |ust as n passng the parameters by reference, returnng a reference aso doesnt return back a copy of the varabe , nstead an aas s returned. e.g. nt &func(nt &num) { : : 233 return(num); } vod man() { nt n1,n2; : : n1 = fn( n2); } Notce that the functon header contans an ampersand (&) before the functon name. Ths s how a functon s made to return reference varabe. In ths case, t takes a reference to an nteger as ts argument and returns a reference to an nteger. Ths facty can be very usefu for returnng ob|ects and even structure varabes. (.(. 7se of /eference ,aria-le is not a lu6ur1 -ut a necessit1 The foowng exampe ustrates that the use of reference varabe sometmes becomes mperatve. It uses the Strng cass, whch has aready been covered earer. cass Strng { pubc : Strng (); Strng(char *s); -Strng(); Strng operator=(Strng str);
prvate : char *ptr; nt sze; }; Strng::Strng () //Constructor 1 { sze = 0; cptr = 0; cout << " Constructor = " << cptr << end; } 234 Strng::Strng(char *s) //Constructor 2 { sze = stren(s); cptr = new char|sze+1|; strcpy(cptr,s); cout << " Constructor = " << cptr << end; } Strng::-Strng() // Destructor { cout << " Destructor= " << cptr << end; deete cptr; } Strng::Strng operator=(Strng str) { deete cptr; sze = stren(str.cptr); cptr = new char|sze+1|; strcpy(cptr,str.cptr); return(*ths); } vod man() { Strng s1 = " You are earnng references"; Strng s2; S2 = s1; } Output: Constructor = You are earnng references Constructor = nu Destructor = You are earnng references Destructor = You are earnng references Destructor = You are earnng references Destructor = You are earnng references The exampe gven above decares two ob|ects s1 and s2 of cass Stng. The decaraton of the frst ob|ect nvokes the second constructor and the second ob|ect nvokes the frst constructor, whos argument beng nothng prnts nu. There s |ust one assgnment statement n 235 the program, whch assgns the contents n s1 to s2 usng the operator- overoaded functon. The destructor functon s caed automatcay by the comper after ths statement. However, t can be seen from the output that the destructor functon s caed four tmes for two ob|ects. The assgnment statement , s2 = s1; gets converted nto s2.operator=(s1); when the ob|ect s passed to the functon t s stored n a temporary ob|ect and whe returnng wth *ths, the comper creates an unnamed temporary ob|ect. Therefore the destructor functon s nvoked four tmes . the souton to ths s to pass and return ob|ects by reference. The operator functon needs to be changed sghty as gven beow: Strng &operator=(Strng &str) { deete cptr; sze = stren(str.cptr); cptr = new char|sze+1|; strcpy(cptr,str.cptr); return(*ths); } Now the output w be : Constructor = You are earnng references Constructor = nu Destructor = You are earnng references Destructor = You are earnng references (.). /eference 2ddities A reference varabe can refer to any nteger varabe, be t n an array or a member varabe from structure or cass. Reference varabes can refer to constants as we. For nstance, take a ook at the program gven beow. vod func(nt &ntref) { 236 ++ntref; } vod man() { ong nt = 20; nt snt = 10; cout << "Before ncrementng " << end; cout << "Sma nt = " << snt << end; cout << "Long nt = " << nt << end; func(snt); // Integer Varabe func(nt); // Long Varabe cout << "After ncrementng " << end; cout << "Sma nt = " << snt << end; cout << "Long nt = " << nt << end; func(25); // Integer Constant func(snt + 10); // Expresson } Output : Before ncrementng Sma Int = 10 Long Int = 20 After ncrementng Sma Int = 11 Long Int = 20 The program cas func() , whch receves a reference to an nteger, four tmes. Frst wth an nteger varabe , whch gets duy ncremented, as can be seen from the output. It agan cas the func() wth ong varabe. The comper does not gve a type msmatch error but nstead , t creates a temporary varabe of the correct type and assgns the vaue of the varabe nt to ths varabe. The func() ncrements the temporary varabe and therefore as can be seen from the output , nt st has the same vaue. Smary, the ast two cas do not resut n errors but temporary varabes are created for them |ust ke n the earer case. 237 However, snce a msmatch between the data types of the actua argument and the forma argument s sheded by these temporary reference varabes, programmers prefer to use ponters, f a functon has to change the vaue of an argument. Besdes havng the ponter notaton aso makes t obvous that the functon s ntended to make changes to the arguments. However, references are st used wth structures , casses and ob|ects extensvey.
Ths sesson aong wth the prevous sesson covered the most exctng feature of C++ polymorphism. Ths sesson aso dscussed yet another way of passng arguments to a functon, by makng a ca by reference. A ca by reference does not make a copy of the contents of the arguments nor does t uses the addresses; yet, t aows changes made n the caed functon to be refected back n the cang functon. %6ercises 1. WAP to create a cass caed as COMPLEX and mpement the foowng by overoadng the functon ADD whch returns a compex number. a) ADD(s1, s2) where s1 s an nteger ( rea ) and s2 s a COMPLEX number. b) ADD(s1, s2 )- where s1 and s2 are COMPLEX numbers. 2. Create a cass DateCass wth day, month and year as ts members. Wrte an overoaded functon for the mnus sgn. The frst functon returns the dfference between two dates n terms of days. e.g. DateCass date1, date2; nt dffdays; dffdays = date1 date2; The second overoaded functon s wrtten whch returns a date occurrng a gven number of days ago. e.g. DateCass newdate, somedate; nt days; newdate = somedate days; 238 ----------- ----------- ------------ ----------- ------------- Sesson 8 Inhertance During this session you will learn about : /eusa-ilit1. Inheritance conce$t. Bo< to define a deri0ed class Q Pri0ate, Pu-lic and Protected deri0ations. 4he access s$ecifiers. 7sing the deri0ed class . Ob|ect-orented programmng as seen n the precedng sessons emphaszes the data, rather than emphaszng agorthms. The prevous sessons covered OOP features ke extensbty, data encapsuaton, nformaton hdng, functona poymorphsm and operatona poymorphsm. OOP, however, has more |argon assocated to t, ke reusabty, nhertance. Ths sesson covers reusabty and nhertance. ).1. /eusa-ilit1
Reusabty means reusng code wrtten earer ,may be from some prevous pro|ect or from the brary. Reusng od code not ony saves deveopment tme, but aso saves the testng and debuggng tme. It s better to use exstng code, whch has been tme-tested rather than renvent t. Moreover, wrtng new code may ntroduce bugs n the program. Code, wrtten and tested earer, may reeve a programmer of the ntty-grtty. Detas about the hardware, user- nterface, fes and so on. It eaves the programmer more tme to concentrate on the overa ogstcs of the program. ).2. Uhat is inheritanceQ 239 Cass, the vehce, whch s used to mpement ob|ect-orented concepts n C++, has gven a new dmenson to ths dea of reusabty. Many vendors now offer brares of casses. A cass brary conssts of data and methods to operate on that data, encapsuated n a cass . The source code of these brares need not be avaabe to modfy them. The new dmenson of OOP uses a method caed nhertance to modfy a cass to sut ones needs. Inhertance means dervng new casses from the od ones. The od cass s caed the base class or parent class or super class and the cass whch s derved from ths base cass s caed as derived class or child class or sub class. Dervng a new cass from an exstng one , aows redefnng a member functon of the base cass and aso addng new members to the derved cass . and ths s possbe wthout havng the source of the course defnton aso. In other words, a derved cass not ony nherts a propertes of the base cass but aso has some refnements of ts own. The base cass remans unchanged n the process. In other words, the derved cass "s a " type of base cass, but wth more detas added. For ths reason, the reatonshp between a derved cass and ts base cass s caed an "s-a" reatonshp. Cass A Cass B Single Inheritance Here cass A s a base cass and the cass B s the derved cass. ).3. Bo< to define a deri0ed class Q A sngy nherted derved cass d defned by wrtng : The keyword class. The name of the derved cass . A snge coon (:). The type of dervaton ( prvate , protected, or pubc ). 240 The name of the base, or parent cass. The remander of the cass defnton. e.g. cass A { pubc : nt pubc_A; vod pubc_functon_A();
prvate : nt pr_A; vod prvate_functon_A(); protected : nt protected_A; vod protected_functon_A();
}; cass B : prvate A { pubc : nt pubc_B; vod pubc_functon_B(); prvate : nt pr_B; vod prvate_functon_B(); }; cass C : pubc A { pubc : nt pubc_C; vod pubc_functon_C(); prvate : nt pr_C; vod prvate_functon_C(); }; cass D : protected A 241 { pubc : nt pubc_D; vod pubc_functon_D(); prvate : nt pr_D; vod prvate_functon_D(); }; A derved cass aways contans a of the member members from ts base cass . you cannot "subtract" anythng from a base cass. However, accessng the nherted varabes s a dfferent matter. It s aso mportant to understand the prveges that the derved cass has nsofar as access to members of ts base cass are concerned. In other words, |ust because you happen to derve a cass does not mean that you are automatcay granted compete and unmted access prveges to the members of the base cass. to understand ths you must ook at the dfferent types of dervaton and the effect of each one. ).. Pri0ate deri0ation If no specfc dervaton s sted, then a prvate dervaton s assumed. If a new cass s derved prvatey from ts parent cass , then : The prvate members nherted from ts base cass are naccessbe to new member functons n the derved cass . ths means that the creator of the base cass has absoute contro over the accessbty of these members , and there s no way that you can overrde ths. The pubc members nherted from the base cass have prvate access prvege. In other words, they are treated as though they were decared as new prvate members of the derved cass, so that new member functons can access them. However, f another prvate dervaton occurs from ths derved cass, then these members are naccessbe to new member functons. e.g. cass base { 242 prvate : nt number; }; cass derved : prvate base { pubc : vod f() { ++number; // Prvate base member not accessbe } }; The comper error message s base :: number s not accessbe n the functon derved :: f(); e.g. cass base { pubc : nt number; }; cass derved : prvate base { pubc : vod f() { ++number; // Access to number O.K. } }; cass derved2 : prvate derved { pubc : vod g() { ++number; // Access to number s prohbted. } }; 243 The comper error message s base :: number s not accessbe n the functon derved2 :: g(); Snce pubc members of a base cass are nherted as prvate n the derved cass, the functon derved :: f() has no probem accessng t . however, when another cass s derved from the cass derved , ths new cass nherts number but cannot access t. Of course, f derved1::g() were to ca upon derved::f(), there s no probem snce derved::f() s pubc and nherted nto derved2 as prvate. .e. In derved2 we can wrte, vod g() { f(); } or there s another way. Wrtng access decaraton does ths. cass base { pubc : nt number; }; cass derved : prvate base { pubc : base :: number ; vod f() { ++number; // Access to number O.K. } }; cass derved2 : prvate derved { pubc : vod g() { ++number; // Access to number O.K } 244 };
As you have |ust seen prvate dervatons are very restrctve n terms of accessbty of the base cass members . therefore, ths type of dervaton s rarey used. ).". Pu-lic deri0ation Pubc dervatons are much more common than prvate dervatons. In ths stuaton : The prvate members nherted from the base cass are naccessbe to new members functons n the derved cass. The pubc members nherted from the base cass may be accessed by new members functons n the derved cass and by nstances of the derved cass . e.g. cass base { prvate : nt number; }; cass derved : pubc base { pubc : vod f() { ++number; // Prvate base member not accessbe } }; The comper error message s base :: number s not accessbe n the functon derved::f(); 245 Here, ony f the number s pubc then you can access t.
9ote ' 8owever eample ; and < in the above section wor0s here if you derive them as =public>. ).#. 4he Protected 5ccess rights In the precedng exampe, decarng the data member number as prvate s much too restrctve because ceary new members functon n the derved cass need to gan access to t and n order to perform some usefu work. To sove ths demma, the C++ syntax provdes another cass access specfcaton caed protected . here s how protected works : In a prvate dervaton the protected members nherted from the base cass have prvate access prveges. Therefore, new member functons and frend of the derved cass may access them. In a pubc dervaton the protected members nherted from the base cass retan ther protected status. They may be accessed by new members functon and frends of the derved cass . In both stuatons the new members functons and frends of the derved cass have unrestrcted access to protected members . however, as the nstances of the derved cass are concerned, protected and prvate are one and the same, so that drect access d aways dened. Thus, you can see that the new category of protected provdes a mdde ground between pubc and prvate by grantng access to new functon and frends of the derved cass whe st bockng out access to non-derved cass members and frend functons . cass base { protected : nt number; }; cass derved : pubc base { pubc : vod f() 246 { ++number; // base member access O.K. } }; ).(. Protected deri0ation In addton to dong prvate and pubc dervatons, you may aso do a protected dervaton. In ths stuaton : The prvate members nherted from the base cass are naccessbe to new member functons n the derved cass. ( ths s exacty same as f a prvate or pubc dervaton has occurred.) The protected members nherted from the base cass have protected access prvege. The pubc members nherted from the base cass have protected have protected access. Thus , the ony dfference between a pubc and a protected dervaton s how the pubc members of the parent cass are nherted. It s unkey that you w ever have occason to do ths type of dervaton. ).).Summar1 of access $ri0ileges 1. If the desgner of the base cass wants no one, not even a derved cass to access a member , then that member shoud be made prvate . 2. If the desgner wants any derved cass functon to have access to t, then that member must be protected. 3. f the desgner wants to et everyone , ncudng the nstances, have access to that member , then that member shoud be made pubc . ).+. Summar1 of deri0ations 1. Regardess of the type of dervaton, prvate members are nherted by the derved cass , but cannot be accessed by the new member functon of the derved cass , and certany not by the nstances of the derved cass . 247 2. In a prvate dervaton, the derved cass nherts pubc and protected members as prvate . a new members functon can access these members, but nstances of the derved cass may not. Aso any members of subsequenty derved casses may not gan access to these members because of the frst rue. 3. In pubc dervaton, the derved cass nherts pubc members as pubc , and protected as protected . a new member functon of the derved cass may access the pubc and protected members of the base cass ,but nstances of the derved cass may access ony the pubc members. 4. In a protected dervaton, the derved cass nherts pubc and protected members as protected .a new members functon of the derved cass may access the pubc and protected members of the base cass, both nstances of the derved cass may access ony the pubc members . ).1.. 4a-le of :eri0ation and access s$ecifiers Dervaton Type Base Cass Member Access n Derved Cass Prvate Prvate (naccessbe ) Pubc Prvate Protected Prvate Pubc Prvate (naccessbe ) Pubc Pubc Protected Protected Protected Prvate (naccessbe ) Pubc Protected Protected Protected ).11. 7sing the :eri0ed Class An nstance of a derved cass has compete access to the pubc members of the base cass . assumng that the same name does not exst wthn the scope of the derved cass , the members from the base cass w automatcay be used. Because there s no ambguty 248 nvoved n ths stuaton, you do not need to use scope resouton operator to refer to ths base cass member. cass base { pubc : base(nt n = 0) { number = n; } nt get_number(); protected : nt number; }; nt base :: get_number() { return number; } cass derved : pubc base {
};
vod man() { derved d; // Frst checks cass derved , then cass base cout << d.get_number(); // Goes drecty to cass base cout<< d.base ::get_number(); } Output: 249 0 0. Usng derved nstances to access functon members wthout the base cass name and scope resouton operator, the comper resoves the address by checkng : Does the member functon have scope n the derved cass ? f so, use t ; ese Does the member have scope n the parent cass ? f so, use t ; ese Does the member have scope hgher up n the herarchy ? f so use t; ese Does the member have accessbe cope hgher up n the herarchy? If so use t; ese Does the member exst n the fe scope ? f so use t ; ese generate a compaton error. Inhertance s the most powerfu use of cass and s aso, probaby, the most mportant concept of OOP. It s the mechansm usng whch reusabty of code s acheved. The facty to use the exstng tested code reduces the tme and cost of wrtng t a over agan. Ths sesson ntroduced the concept of nhertance. The next sesson covers more sutabe aspects of nhertance
---------- ---------------- -------------- ----------- ---------- Session + 8ore on Class Inheritance During this session you will learn about: Hdng overoaded functons. Constructor and destructor n derved cass . Ob|ect ntazaton and converson. Nested casses ( contaner casses). Muteve nhertance. Mutpe nhertance. Mutpe nhertance wth common base casses. 250 Vrtua base cass. Abstract cass. Ponters to ob|ects. Vrtua functon. Pure vrtua functon. Cass nhertance has gven a new dmenson to the dea of reusabty of code. The prevous sesson ntroduced the concept of nhertance. Ths sesson dscusses the more subte aspects assocated wth cass nhertance. +.1. Biding o0erloaded functions We cannot overoad a base cass functon by redefnng t n a derved cass wth a dfferent argument st. Consder exampes to see f same functon name exsts n base as we as derved casses. e.g. cass base { pubc : vod f(nt n ) { cout << " n = " << n; } }; cass derved : pubc base { pubc :a vod f(foat n ) { cout << " n = " << n; } };
vod man() { derved d; 251
d.f(1); } Output : n = 1.000000 Even though we have passed an nteger, the comper uses the functon of the derved cass because t s the one, comper knows about. If there s no convncbe match wthn the scope of the derved cass, the nherted members from the cass w not be examned. The foowng exampe shows ths. cass base { pubc : vod f(char *ptr) { cout << " ptr = " << ptr; } }; cass derved : pubc base { pubc : vod f(foat n ) { cout << " n = " << n; } };
vod man() { derved d; d.f("A"); } Output: Can not convert char* to doube 252 However, we can st access the hdden members from the base cass usng the scope resouton operator. So n the man f we ca d.base::f("A"); The output w be : ptr = A +.2. Constructor and :estructor function <ith deri0ed classes If there are constructors nvoved n the base cass and the derved cass, the comper automatcay cas both of them. Ths happens because as soon as the derved cass constructor gets contro and estabshes forma arguments, the base cass constructor w be caed mmedatey, .e., before the derved cass ntazaton st s honored. Syntax n the derved cass base/members ntazaton st : The base cass name ( name of base constructor ) A st of arguments between parentheses, as n any norma functon ca. To expcty nvoke the base cass defaut constructor , eave the argument st empty. Remember the base cass constructor aways s caed frst. cass base { pubc : base(nt n=0); -base(); nt get_base_number(); protected: nt base_number;
- derved(); nt get_derved_number(); prvate : nt derved_number;
}; derved::derved(nt b=0, nt d =0): base(b),derved_number(d) { cout << " derved constructor "; } derved::- derved() { cout << "derved destructor "; } nt derved::get_derved_number() { return derved_number; } 254 vod man() { derved d(1,2); cout < " d= " << d.get_base_number()<<","; cout << d.get_derved_number(); } Output: Base constructor Derved constructor D = 1,2 Derved destructor Base destructor As can be seen from the above exampe, the constructor for the base cass s nvoked before nvokng the constructor for the derved cass . Ths s ke budng the frst storey of the budng before proceedng for the second. Wth destructors, t s the other way round. Destructors for the derved cass are nvoked frst, so that they can cean up the mess done by the constructor of the derved cass . Then the destructor for the base cass s caed. It s ke demoshng the top foor of a budng before gong for the ower one. A destructor for the derved cass s to be defned ony f ts constructor aocates memory. Otherwse t can be |ust an empty functon . +.3. 2-3ect Initiali?ation An ob|ect of a derved cass can be ntazed to an ob|ect of a base cass . If both the casses have same data members , then no specfc constructor needs to be defned n the derved cass . It uses the constructor of the base cass . An ob|ect of a base cass can be assgned to the ob|ect of the derved cass , f the derved cass doesnt contan any addtona data members . However, f t does , then the assgnment operator w have to be overoaded for the same. +.. 2-3ect Con0ersions 255 |ust ke ntazaton , conversons are aso done automatcay when an ob|ect of a derved cass s assgned to an ob|ect of the base cass . However, the comper resorts to a member-wse assgnment n the absence of an overoaded functon for the assgnment operator . +.". 9ested Classes Many a tmes, t becomes necessary to have a cass contan propertes of two other casses. One way s to defne a cass wthn another that s a cass wth member casses aso caed nested casses. Ths has nothng to do wth nhertance. Another way s mutpe nhertance , whch w be dscussed ater. e.g. cass Acass { pubc : Acass(nt pv) { prvate_varabe_A = pv; } prvate : nt prvate_varabe_A; }; cass Bcass { pubc : Bcass(nt bpv, nt apv): Aob|(apv) { prvate_varabe_B = bpv; } prvate : nt prvate_varabe_B; Acass Aob|; // Decarng an ob|ect here. };
As can be seen , the cass Bcass contans an ob|ect Aob| n ts prvate secton as one of ts members. Aso, t contans a constructor functon wth the same name , to whch the two varabes passed are bpv and apv. The varabe bpv s used to ntaze the prvate varabe of Bcass. 256 Class B Class A However, the constructor contans somethng after the coon. The part after the coon n the defnton of a constructor s caed as initiali%ation section and the actua body of the constructor s caed as assignment section . Intazaton secton ntazes the base cass members , whereas assgnment secton contans statements to ntaze the derved cass members . As seen earer , n case of the derved casses, the name of the base cass constructor s wrtten after coon n the ntazaton secton. Ths base cass constructor s caed before the constructor n the derved cass. However, ths exampe does not contan a derved cass. Ths s the exampe of the nested cass . In ths case, the name of the ob|ect of the member cass Acass s wrtten after the coon. It tes the comper to ntaze the Aob| data member of Bcass wth the vaue n apv. It s exacty ke decarng an ob|ect of Acass wth the statement : Acass Aob|(apv); The ony change s that, t s wrtten after the coon n the ntazaton secton of the Bcass constructor. Its assgnment secton contans code to ntaze ts own members. The same constructor functon can aso be wrtten as : Bcass (nt bovne apv):Aob|(apv),prvate_varabe_B = bpv; +.#. 8ultile0el Inheritance In muteve nhertance there s a parent cass , from whom we derve another cass . now from ths derved cass we can derve another cass and so on.
+.(. 8ulti$le Inheritance Mutpe nhertance , as the name suggests , s dervng a cass from more than one cass . The derved cass nherts a the propertes of a ts base casses. Consder the foowng exampe : Cass A Cass B Cass C 8ulti$le Inheritance cass Acass { : : }; cass Bcass { : : }; cass Ccass : pubc Acass , pubc Bcass { prvate : : : pubc : Ccass(...) : Acass (...), Bcass(...) { }; }; 1
The cass Ccass n the above exampe s derved from two casses Acass and Bcass therefore the frst ne of ts cass defnton contans the name of two casses, both pubcy nherted. Lke wth norma nhertance , constructors have to be defned for ntazng the data members of a casses. The constructor n Ccass cas constructors for base casses. The constructor cas are separated by commas. +.). Pro-lems Uith 8ulti$le Inheritance The foowng exampe presents a probem wth mutpe nhertance. cass Acass { pubc : vod put() { : } }; cass Bcass { pubc : vod put() { : } }; cass Ccass : pubc Acass , pubc Bcass { pubc : : : };
vod man() { A ob|A; B ob|B; C ob|C; 2
ob|A.put(); // From Cass A ob|B.put(); // From cass B ob|C.put(); // AMBIGUOUS RESULTS IN ERROR } The above exampe has a cass C derved from two casses A and B. Both these casses have a functon wth the same name put(), whch assume, the derved cass does not have. The cass C nherts the put() functon from both the casses. When a ca to ths functon s made usng the ob|ect of the derved cass , the comper does not know whch cass t s referrng to. In ths case, the scope resouton operator has to be used to specfy the correct ob|ect . Its usage s very smpe. The statement gvng an error from the above exampe has to be repaced wth the foowng : ob|C.A::put(); // for cass A ob|C.B::put(); // for cass B +.+. 8ulti$le inheritance <ith a common -ase (B1-rid Inheritance) Inhertance s an mportant and powerfu feature of OOP. Ony the magnaton of the person concerned s the mt. There are many combnatons n whch nhertance can be put to use. For nstance, nhertng a cass from two dfferent casses, whch n turn have been derved from the same base cass . e.g.
3 base Class A Class B derived
B1-rid Inheritance cass base { : : }; cass Acass : pubc base { : : }; cass Bcass : pubc base { : : }; cass derved : pubc Acass, pubc Bcass { : : }; Acass and Bcass are two casses derved from the same base cass . The cass derved has a common ancestor cass base. Ths s mutpe nhertance wth a common base cass . However, ths subtety of cass nhertance s not a that smpe. One potenta probem here s that both, Acass and Bcass, are derved from base and therefore both of them, contans a copy of the data members base cass. The cass derved s derved from these two casses. That means t contans two copes of base cass members one from Acass and the other from Bcass. Ths gves rse to ambguty between the base data members. Another probem s that decarng an ob|ect of cass derved w nvoke the base cass constructor twce. The souton to ths probem s provded by vrtua base casses. 4
+.1.. ,irtual !ase Classes Ths ambguty can be resoved f the cass derved contans ony one copy of the cass base. Ths can be done by makng the base cass a vrtua cass. Ths keyword makes the two casses share a snge copy of ther base cass . It can be done as foows : cass base { : : }; cass Acass : vrtua pubc base { : : }; cass Bcass : vrtua pubc base { : : }; cass derved : pubc Acass, pubc Bcass { : : }; Ths w resove the ambguty nvoved. +.11. 5-stract Classes Abstract casses are the casses, whch are wrtten |ust to act as base casses. Consder the foowng casses. cass base { : : }; 5
cass Acass : pubc base { : : }; cass Bcass : pubc base { : : }; cass Ccass : pubc base { : : }; vod man() { Acass ob|A; Bcass ob|B; Ccass ob|C; : : } There are three casses Acass, Bcass, Ccass each of whch s derved from the cass base. The man () functon decares three ob|ects of each of these three casses. However, t does not decare any ob|ect of the cass base. Ths cass s a genera cass whose soe purpose s to serve as a base cass for the other three. Casses used ony for the purpose of dervng other casses from them are caed as abstract classes. They smpy serve as base cass , and no ob|ects for such casses are created. +.12. Pointers to 2-3ects Ponters, as seen earer, can be made to pont to ob|ects as we. The usage of ponter wth casses s exacty ke that of ts usage wth structures. As wth structures the structure ponter ( -> ) can be used to access members of the cass . The foowng exampe ustrates ts usage. 6
cass Person { pubc : vod getname() { cout << "enter name "<< end; cn >> name; } vod putname() { cout << " name = " << name ; } prvate : char name|50|; }; vod man() { Person B; B.getname(); B.putname(); Person *Bush; Bush = new Person; Bush->getname(); Bush->putname(); Deete Bush; } Ponters to ob|ects are generay used to form compex data structures ke nked sts and trees. However, wth nhertance, ponters can sometmes become probematc. The foowng exampe ustrates yet another probem wth cass nhertance . cass Shape { pubc : vod prnt() { cout << " I am a Shape " << end; } }; 7
cass Trange : pubc Shape { pubc : vod prnt() { cout << " I am a Trange " << end; } }; cass Crce : pubc Shape { pubc : vod prnt() { cout << " I am a Crce " << end; } }; vod man() { Shape S; Trange T; Crce C; S.prnt(); T.prnt(); C.prnt(); Shape *ptr; ptr = &S; ptr -> prnt(); ptr = &T; ptr -> prnt(); ptr = &C; ptr -> prnt(); } The exampe contans a base cass caed Shape. Two other casses Trange and Crce are derved from the base cass . The program decares three ob|ects of the three casses. The frst part of 8
the program cas prnt() functon reated to each of these casses. In the second part the program decares a ponter to the base cass Shape and assgns address of each of the ob|ect decared earer to ths ponter. What s the ob|ectve of assgnng addresses of the derved casses to a ponter of the base cass ? Further, how can the comper aow such a thng ? We, the comper does not gve an error on assgnng address of a derved cass to a ponter of the base cass, because ob|ects of the derved casses are type-compatbe wth ponters of base casses. Ths answers the second queston. As far as the frst queston s concerned, the answer s poymorphsm. That s, f the ponter ponts to the base cass Shape, then the prnt() functon from base cass s nvoked. Whereas, f the ponter s pontng to any of the derved cass Trange or Crce then the prnt()functon from these respectve casses s nvoked. That s what poymorphsm s a about gvng dfferent meanngs to the same thng. The output of the program s gven beow: I am a Shape I am a Trange I am a Crce I am a Shape I am a Shape I am a Shape As can be seen, the frst part works fne. But , for the second part, for each of the cas wth dfferent addresses, the functon from the base cass Shape s executed. What happens, here , s that the comper gnores the contents of the ponter. Instead, to determne whch functon shoud be nvoked, the comper chooses the functon from the same cass as that of the ponter. But , ths s not poymorphsm. The keyword virtual agan comes nto rescue, but n a dfferent context. +.13. ,irtual Functions The keyword vrtua was earer used to resove ambguty for a cass derved from two casses, both havng a common ancestor. These casses are caed vrtua base casses. Ths tme t heps n mpementng the dea of poymorphsm wth cass nhertance . The functon of the base cass can be decared wth the keyword virtual. The program wth ths change and ts output s gven beow. 9
ptr = &C; ptr -> prnt(); } The output of the program s gven beow: I am a Shape I am a Trange I am a Crce I am a Shape I am a Trange I am a Crce Now, the output of the derved casses are nvoked correcty. When decared wth the keyword virtual , the comper seects the functon to be nvoked, based upon the contents of the ponter and not the type of the ponter. Ths facty can be very effectvey used when many such casses are derved from one base cass . Member functons of each of these can be ,then, nvoked usng a ponter to the base cass . +.1. Pure ,irtual Functions As dscussed earer, an abstract cass s one, whch s used |ust for dervng some other casses. No ob|ect of ths cass s decared and used n the program. Smary, there are pure vrtua functons whch themseves wont be used. Consder the above exampe wth some changes. cass Shape { pubc : vrtua vod prnt() = 0; // Pure vrtua functon
{ cout << " I am a Trange " << end; } }; cass Crce : pubc Shape { pubc : vod prnt() { cout << " I am a Crce " << end; } }; vod man() { Shape S; Trange T; Crce C; Shape *ptr; ptr = &T; ptr -> prnt(); ptr = &C; ptr -> prnt(); } The output of the program s gven beow: I am a Trange I am a Crce It can be seen from the above exampe that , the prnt() functon from the base cass s not nvoked at a . even though the functon s not necessary, t cannot be avoded, because , the ponter of the cass Shape must pont to ts members. Ob|ect orented programmng has atered the program desgn process. Exctng OOP concepts ke poymorphsm have gven a bg boost to a ths. Inhertance has further enhanced the anguage. Ths 12
sesson has covered some of the fner aspects of nhertance. The next sesson w resove some fner aspects of the anguage. %6ercises' 1. Create a cass drugs contanng encapsuated data for medcne name, whether sod or qud, prce and purpose of use. From ths cass derve two casses, Ayurvedc and Aopathc. The cass Ayurvedc shoud addtonay store data on the herbs used, assocaton to be used (whether honey or water). The cass Aopathc shoud addtonay ncude data on the chemcas used and the weght n mgrams. The casses shoud contan constructors and destructors. They shoud contan functons to accept data and dspay the data. The man() shoud test the derved casses. ------------------- ----------------- -------------------- ------
Sesson 10 Addtona Features of C++ During this session you will learn about: Statc member and Statc functons. Frend functons. Frend functons and Operator Overoadng. Frend casses. Necessty of frends. Overoadng the extracton and nserton Operators. Inne functons Preprocess or Drectves Istream and ostream ob|ects and manpuators. An ntroducton to tempate functons and tempate casses. We have aready seen the powerfu features of OOP that make C++ such a strong anguage. In ths sesson we w contnue exporng some other features, whch make ths anguage more powerfu. 13
1..1. Static Class 8em-ers As we aready know a the ob|ects of the cass have dfferent data members but nvoke the same member functons. However, there s an excepton to ths rue. If the data member s decared wth the keyword static# then ony one such data tem s created for the entre cass, no matter how many ob|ects t has. Statc data members are usefu, f a ob|ects of a cass must share a common data tem. Whereas, the vsbty of ths data tem remans same, the duraton of ths varabe s for entre fetme of the program. For exampe, such a varabe can be partcuary usefu f an ob|ect requres to know how many ob|ects of ts knd exst. cass counter { pubc : counter (); nt getcount(); prvate: statc nt count; }; counter::counter () { count++; } nt counter::getcount() { return ( count ); } nt counter :: count = 0;// INITIALIZATION OF STATIC MEMBER. vod man() { counter c1,c2; cout << " Count = " << c1.getcount() << end; cout << " Count = " << c2.getcount() << end; counter c3; cout << " Count = " << c3.getcount() << end; 14
counter c4,c5; cout << " Count = " << c4.getcount() << end; cout << " Count = " << c5.getcount() << end; } Output: Count = 2 // not 1 because 2 ob|ects are aready created. Count = 2 Count = 3 Count = 5 Count = 5 In the above exampe, the cass counter demonstrates the use of statc data members. It contans |ust one data member count. -otice the initiali%ation of this static class member. For some compers t s mandatory. Even though the data member s n the prvate secton t can be accessed n ths case as a goba varabe drecty, but has to be preceded by the name of the cass and the scope resouton operator. Ths exampe contans a constructor to ncrement ths varabe. Smary, there can be a destructor to decrement t. You can use these to generate regster numbers for student ob|ects from a student cass. Whenever an ob|ect s created, he w be automatcay assgned a regster number f the regster number s a statc varabe and a constructor s used to wrte an equaton to generate separate regster numbers n some order. You coud ntaze the varabe to gve the frst regster number and then use ths n the constructor for further operatons. 1..2. Static 8em-er Functions A the ob|ects of the cass share statc data members of a cass. The exampe above demonstrates how to keep track of a the ob|ects of a cass whch are4 n exstence. However, ths functon uses exstng ob|ects to nvoke a member functon getcount(), whch returns the vaue of the statc data member. 9hat if the programme does not want to use ob'ects to invo0e this function and still the programme would li0e to 0now how many ob'ects have been created? ,f there is no ob'ect how the member function is invo0ed? Further, as can be seen from the prevous output, the number of ob|ects (count) remans same at a gven nstance no matter whch ob|ect s used to nvoke the 15
member functon. In fact, the use of exstng ob|ects, ke n the above exampe, s not an effectve way to access the vaue of the statc data member. A specfc ob|ect shoud not be used to refer to ths member, snce t does not beong to that ob|ect; t beongs to the entre cass. C++ gves a facty to defne statc functon members, for the same. That s, to nvoke such a functon, an ob|ect s not requred. It can be nvoked wth the name of the cass. The programme gven beow ustrates ts use. cass counter { pubc : counter (); statc nt getcount();
cout << " Count = " << counter :: getcount() << end; cout << " Count = " << counter :: getcount() << end; } Output: Count = 2 Count = 2 Count = 3 Count = 5 Count = 5 1...Friend Functions One of the man features of OOP s nformaton hdng. A cass encapsuates data and methods to operate on that data n a snge unt . The data from the cass can be accessed ony through member functons of the cass. Ths restrcted access not ony hdes the mpementaton detas of the methods and the data structure, t aso saves the data from any possbe msuse, accdenta or otherwse. However, the concept of data encapsuaton sometmes takes nformaton hdng too far. There are stuatons where a rgd and controed access eads to nconvenence and hardshps.
For nstance, consder a case where a functon s requred to operate on ob|ect of two dfferent casses. Ths functon cannot be made a member of both the casses. What can be done s that a functon can be defned outsde both the casses and made to operate on both. That s, a functon not beongng to ether, but abe to access both. Such a functon s caed as a frend functon. In other words, a frend functon s a nonmember functon, whch has access to a casss prvate members. It s ke aowng access to ones persona beongngs to a frend. 1..". 7sing a Friend Usng a frend functon s qute smpe. The foowng exampe defnes a frend functon to access members of two casses. cass Bcass; // Forward Decaraton cass Acass { 17
pubc : Acass(nt v) { Avar = v; } frend nt addup(Acass &ac, Bcass &bc); prvate : nt Avar; }; cass Bcass { pubc : Bcass(nt v) { Bvar = v; } frend nt addup(Acass &ac, Bcass &bc); prvate : nt Bvar; }; nt addup(Acass &ac, Bcass &bc) { return( ac.Avar + bc.Bvar); } vod man() { Acass aob|; Bcass bob|; nt tota; tota = addup(aob|,bob|); }
The program defnes two casses- Acass and Bcass. It aso has constructors for these casses. A frend functon, addup(), s decared n 18
the defnton of both the casses, athough t does not beong to ether. Ths frend functon returns the sum of the two prvate members of the casses. Notce, that ths functon can drecty access the prvate members of the casses. To access the prvate members, the name of the member has to be prefxed wth the name of the ob|ect , aong wth the dot operator. The frst ne n the program s caed forward decaraton. Ths s requred to nform the comper that the defnton for cass Bcass comes after cass Acass and therefore t w not show any error on encounterng the ob|ect of Bcass n the decaraton of the frend functon. Snce t does not beong to both the casses , whe defnng t outsde we do not gve any scope resouton and we do not nvoke t wth the hep of any ob|ect. Aso , the keyword frend s |ust wrtten before the decaraton and not used whe defnng. Sometimes friend functions can -e a0oided using inheritance and the1 are $referred. %6cessi0e use of friend o0er man1 classes suggests a $oorl1 designed $rogram structure. !ut sometimes the1 are una0oida-le. 1..#. Friend for 20erloading 2$erators Some tmes frend functons cannot be avoded. For nstance wth the operator overoadng. Consder the foowng cass that contans data members to smuate a matrx. Severa operatons can be performed on the matrces. One of them s to mutpy the gven matrx by a number( constant tera). There are two ways n whch we can do ths. The two ways are : Matrx * num;
|or| num * Matrx; In the frst case we can overoad * to perform the operaton and an ob|ect nvokes ths as the statement gets converted to : Mob|.operator*(num); Where Mob| s an ob|ect of Matrx and num s a norma nteger varabe. What happens to the second one ? It gets converted by the comper as : 19
num.operator*(Mob|); Let us see ths program n deta. cass Matrx { pubc: : : Matrx &operator*(nt num); frend Matrx &operator*(nt n, Matrx &m); prvate: nt mat|20||20|; nt rows, cos; } Matrx Matrx::operator*(nt num) { Matrx temp; temp.rows=rows; temp.cos=cos; for(nt =1; <=rows; ++) for(nt |=1; |<=cos; |++) temp.mat|||||=mat|||||*num; return (temp); } Matrx operator*(nt n, Matrx &m) { Matrx temp; temp= m*n; return temp; } vod man() { Matrx M1, M2, M3; nt num; : : // accept matrx one and num M2=M1*num; // cas member operator functon. M3=num*M1; // cas frend functon. 20
} Here when the comper comes across the mutpcaton of an ob|ect by a number t nvokes the operator member functon. When s encountered before mutpcaton symbo as n the second ca n the program, the comper cas frend functon . n frend functon we have |ust reversed the arguments, whch causes the member functon to be nvoked . Integent use of frend functons makes the code more readabe. 1..(. Vranting friendshi$ to another class 4o grant friendshi$ to another class, <rite the @e1<ord follo<ed -1 the class name. 4he @e1<ord class is o$tional. 9ote that this declaration also im$lies a for<ard declaration of the class to <hich the friendshi$ is -eing granted. 4he im$lication of this declaration is that all off the mem-er functions of the friend class are friend functions of the class that -esto<s the friendshi$. e.g. class 5class R $u-lic ' ' ' ' friend class !classS JJ Friend declaration. $ri0ate ' int 50arS TS class !class R $u-lic ' ' ' 0oid fn1(5class ac) R !0ar M ac. 50arS JJ 50ar can -e accessed. 21
T
$ri0ate ' int !0arS TS 0oid main() R 5class ao-3S !class -o-3S !o-3,fn1(ao-3)S T 4he $rogram declares class !class to -e a friend of 5class. It means that all mem-er functions of !class ha0e -een granted direct access to all mem-er functions of 5class. 10.8.Grantng frendshp to a member functon of another cass If 1ou <ant class 5 to grant friendshi$ to one or more indi0idual mem-er functions of class !, then 1ou must code the classes and their mem-er functions in this manner' For<ard declare class 5S :efine class ! and declare (not define) the mem-er functions' :efine class 5 in <hich 1ou declare the friendshi$ for the mem-er functions of class !. 2f course, 1ou must &ualif1 the names of these functions using the class name ! and the sco$e resolution o$erator. :efine the mem-er functions of class !S e.g. class 5class class !class R $u-lic ' ' ' 0oid fn1()S JJ Can=t define here 22
0oid fn3() R ' ' T $ri0ate ' int !0arS TS class 5class R $u-lic ' ' ' 0oid fn1() R ' T friend class!'' fn1()S friend class!'' fn2()S $ri0ate ' int 50arS
TS 0oid class!'' fn1() R !0ar M 50arS T 0oid class!'' fn2() R !0ar M 0aria-le +2"S T 23
10.9.Overoadng the Extracton and Inserton Operators Ue=ll finish this session -1 sho<ing ho< to o0erload the e6traction and insertion o$erators. Bere, 1ou can acce$t the in$ut and out$ut the results of the user;defined 0aria-les or o-3ects 3ust li@e normal 0aria-les. Consider a class Com$le6 that consists of t<o s1stem defined 0aria-les, -oth float to denote the real and com$le6 $art of a com$le6 num-er. In general cases to acce$t these mem-er 0aria-les, <e need to <rite some function sa1 get0al() and in0o@e it using the o-3ect of the class sa1 Como-3.get0al() and similar method <ould -e re&uired to dis$la1 them. 7sing o$erator o0erloading <e can acce$t or dis$la1 the user;defined o-3ect 3ust li@e a normal 0aria-le . i.e. -1 o0erloading the e6traction o$erator DD <e can acce$t the com$le6 o-3ect as, cin DD como-3S Similarl1, -1 o0erloading the insertion o$erator <e can dis$la1 the mem-er 0aria-les of the o-3ect as, cout LL como-3S 3ust as if it <ere a -asic data t1$e. Consider the e6am$le ' cass Compex { pubc: frend stream& operator >> (stream &s, Compex &c2) frend ostream& operator << (ostream &os, Compex &c2) prvate: foat rea, magnary; }; istreamF o$erator DD (istream Fis, Com$le6 Fc2) R cout LL W enter real and imaginar1 W LL endlS is DD c2.real DD c2.imaginar1S return (is)S T 24
istreamF o$erator LL (ostream Fos, Com$le6 Fc2) R os LL W the com$le6 num-er is W LLendlS os LL c2.real LL W+iXLL c2.imaginar1S return (os)S T 0oid main() R Com$le6 c1,c2S cin DD c1S cout LL c1S cin DD c2S cout LL c2S T 4he o$erator functions ha0e to -e declared friends , since the1 ha0e to access the user class and the o-3ects of istream and ostream classes that are s1stem defined. Since these o$erator functions are friend functions, the t<o o-3ects Y cin and cout are $assed as arguments, along <ith the o-3ects of the user;class. 4he1 return the istream and ostream o-3ects so that the o$erator can -e chained. 4hat is the a-o0e t<o in$ut statements can also -e <ritten as, cin DD c1 DD c2S cout LL c1 LL c2S 1..1.. Inline Functions Imagne a c program, whch reads dsk records contanng empoyee nformaton. If ths s a payro appcaton each empoyee record data s probaby processed va a seres of functon cas. These functon cas coud be to prnt the entty data, to compute the saary, to compute the taxes to be wthhed etc,. Each one of these cas nherenty contans overhead that must be part of your overa program. In other words t takes code space and tme to push actua arguments onto the stack, ca the functon, push some return vaue onto the stack and fnay pop a of those vaues . 25
C++ provdes the nne functons, a mechansm by whch these expct functon cas can be avoded. = (n inline function by definition is a function whose code gets substituted in place of the actual call to that function.> Whenever the comper encounters a ca to that functon t merey repaces t wth the code tsef thereby savng you a of the overhead. Such a functon can be ether a member of a cass or a goba functon. Inne functons work best when they are sma, straghtforward bodes of code that are not caed from too many dfferent paces wthn your program. The tme saved w ncrease wth the ncrease n number of cas. Even f you request that the comper make a functon nto an nne functon, the comper may or may not honor that request. It depends on the code of the functon. For exampe, the comper w not nne any functon that contans a oop, statc data member, or aggregate ntazer st. If such cases case, a warnng message w be ssued.
The dsadvantage wth nne functons s that f the code tsef ever needs to be modfed, then a programs that use the these functons woud then have to be recomped. Furthermore, an nne functon s a voaton of mpementaton hdng. 1..11. Bo< to <rite a glo-al inline function Frst, ets get away from member functons for a moment and consder a goba functon. To make a request that ths functon be nne : Precede the return type of the functon wth the keyword nne. Wrte the functon body (the defnton, not |ust the decaraton) before any cas to that functon.
Bere is a $rogram that uses an inline function to com$ute and return the a-solute 0alue of its in$ut argument. # ncude <stdo.h> nne nt abs(nt x) { return x <0? -x : x ; } 26
vod man( ) { for (nt =-2 ; <2 ; ++) { nt vaue = abs() ; prntf ("Absoute vaue of %+d = %+d\n",, vaue); } } The output s: Absoute vaue of 2 =+2 Absoute vaue of 1 =+1 Absoute vaue of +0 =+0 Absoute vaue of +1 =+1 When the ca to the abs ( ) functon s encountered, the comper, nstead of makng a functon ca, generates ths assemby code. 1..12. Bo< to <rite an inline class mem-er function In addton to goba functons, you may request that non-statc member functons of a cass be nned. The norma method of dong ths s to smpy defne the functon wthn the scope of the cass defnton. In ths case the nne request s made automatcay, so the keyword inline does not need to be wrtten. Here the member functon nteger :: store ( ) s an nne member functon because t s competey defned wthn the context of the cass defnton. e.g. cass nteger { pubc : // Ths s an nne functon
vod store (nt n ) { number =n ; } prvate: 27
nt number ; }; Functons nned wthn the cass defnton are not evauated by the comper unt the entre cass scope has been processed. Thats why, f they are defned frst, they can refer to members defned ater, or even compute the sze of the cass. The ony probem wth ths cass s that now t has been " cuttered up" wth the actua defnton of the nteger::store() functon. A better approach s to move the functon defnton outsde the cass and use the scope resouton operator to gve t cass scope. In order to make the nne request to the comper, you must wrte the keyword nne n front of both the functon decaraton and ts defnton. e.g. cass nteger { pubc: nne vod store (nt) ; prvate: nt number ; } ;
// Ths s an nne functon nne vod nteger :: store (nt n ) { number = n; } The above exampe shows the correct way to defne an nne functon, the usage of the keyword nne n front of the decaraton ( wthn the cass defnton ) s not aways necessary. Ths s the case when the defnton ( st preceded by the keyword nne) s encountered by the comper before t s ever caed. Now there s no probem because the nnng w st occur. 28
12.1<. The *reprocessor Directives A preprocessor drectve whch begns wth a hash # ,s an nstructon to the preprocessor, whch acts on the source code before the compaton process. The output from the preprocessor becomes the nput to the comper and s aso caed as etended source code. It performs fe ncusons, macro substtuton and condtona compaton etc. 12.1<.1.The @define Directive The #defne drectve defnes a macro whch s a text strng represented by a name. Whenever the preprocessor fnds ths name n the program, t s repaced by the text strng t represents. The s an foowng exampe whch defnes a vaue and gves t a name PI. #defne PI 3.14285 // no semcoon gven vod man() { cout << PI; } Ths program s equvaent to : vod man() { cout << 3.14285; } The # defne drectve works strcty on the bass of substtuton of a text strng for the macro names. 1..13.2. 4he [undef :irecti0e Ths drectve undefnes a prevousy defned macro. For, exampe the foowng w gve an error snce PI s undefned. #defne PI 3.14285 vod man() { 29
cout<< PI; // no error here # undef PI;
cout << PI; // error after undef. } 1..13.3. 4he [ifdef, [elif, [else and [endif :irecti0es 4hese directi0es are used for conditional com$ilation. 4he1 are used in the follo<ing <a1s. [ifdef condition statementsS [endifS [ifdef condition statementsS [else statementsS #endf; [ifdef condition1 statementsS [elif condition2 statementsS #endf; [ifdef condition1 statementsS [elif condition2 statementsS #ese statementsS #endf; \ust li@e [ifdef there is also [ifndef <hich negates the condition. 4hese directi0es control <hich $ortions of the code <ill -e $assed to the com$iler. For e6am$le, these directi0es can -e used for com$iling the $rogram <ritten for t<o different machines. 2n 8S:2S machines, the $rogram can ma@e use of certain 8S:2S features. 2ther<ise, some other code de$ending on the machine is e6ecuted. 30
e.g. 0oid main() R [ifdef ZZ8S:2SZZ :2S;fn()S [else 79I]Zfn()S [endifS T 10.13.4. The #error drectve 4his directi0e facilitates $utting diagnostic messages into the $re$rocessor statements. Sometimes, <or@ing <ith conditional com$ilation, error messages need to -e dis$la1ed. In this case the [error directi0e is 0er1 useful. 4he follo<ing e6am$le illustrates the usage of this directi0e. [ifndefZZL5/V%ZZ [error Com$ile this $rogram in the large model onl1 [endif 4he e6am$le sho<s a $rogram, <hich has to -e com$iled onl1 in the large model. If the com$iler s<itch for a large model is not on, the $re$rocessor $rints the gi0en error message and sto$s com$ilation. 10.14. Input Output 8ost languages ha0e WstatementsX to $erform IJ2 . Bo<e0er in C and C++ <e use WfunctionsX to $erform IJ2. C++ also has its o<n IJ2 mechanism Y the cin and cout o-3ects, declared in the header file iostream.h. 2n including iostream.h , the $rogram gets the follo<ing o-3ects automaticall1' cn 4his o-3ect corres$onds to the standard in$ut Stream, <hich -1 default is the @e1-oard. 31
cout 4his o-3ect corres$onds to the standard out$ut stream ,<hich -1 default is the screen. cerr 4his o-3ect corres$onds to the standard error & cog Stream, <hich -1 default is the screen. 10.15. The overoaded Inserton Operator and Extracton Operator 2ut$ut on the standard screen is done -1 using the cout o-3ect of the ostream class. cout LL 0aria-le S 0aria-le can -e an1 -asic data t1$e. In other <ords, the o$erator function for insertion o$erator is alread1 o0erloaded for each of data t1$es. 4hus, if the 0aria-le is an integer, then the function <ith the corres$onding signature is in0o@ed. 4he $rotot1$e of this function <ould -e ' ostream Fo$erator LL (int n)S Since <e ha0e -een using this througout, no further discussion is needed on this to$ic. 4he follo<ing e6am$le sho<s 0arious formats ' 0oid main() R char fnH1..I M W 9ara1anXS char A ln M W8urth1XS int age M ""S float salar1 M 1........S cout LL W 9ame MX LL fnS cout LL W Sirname MX LL lnS cout LL endlS
cout LL X^n 5ge M W LLageS coutLL endl LL W Salar1 is W LL salar1S T 2ut$ut ' 32
9ame M 9ara1an SirnameM 8urth1 5ge M "" Salar1 M1.....
Similarl1 e0en cin is a o-3ect that acce$ts data in an1 data form and can -e cascaded as <ell. 10.16. Other ostream Functons 5$art from the Ccout=, the ostream class $ro0ides some other functions for out$ut. 2ne of them is $ut(). It has the follo<ing $rotot1$e ' ostream F$ut(char)S 4his function $rints onl1 characters. e.g. cout.$ut(C,=)S JJPrints the character , It can also -e used li@e ' cout.$ut(CI=).$ut(C9=).$ut(C:=).$ut(CI=).$ut(C5=)S 4here is another function <rite() in this class. 4his function $rints an entire string and has the $rotot1$e ' ostream F<rite(char A,int)S 4he first argument gi0es the address of the character string to -e $rinted. 4his function does not recogni?e the null character. 4herefore if the second argument is more than the length of the string then the com$iler raises an error. e.g. [include L iostream.hD [include L string.h D 0oid main() R char Amagic M W5!/5C5:5!/5XS int len M strlen(magic)S 33
for( int su- M .S su- L M len S ++su-) R cout.<rite(magic,su-)LLX^nXS T 2ut$ut ' 5 5! 5!/ 5!/5 5!/5C 5!/5C5 5!/5C5: 5!/5C5:5 5!/5C5:5! 5!/5C5:5!/ 5!/5C5:5!/5 5 function flush() can -e used to flush the out$ut -uffer. sometimes it is necessar1. _et another function endl() $rints a ne< line character. coutLL XtttttX LL endlS coutLL XIJ2 of the C++ is to -e flushed W LLflushS 4he1 can -e used <ith the insertion o$erator. 4he1 can also -e used as follo<s' flush(cout)S endl(cout)S 10.17.Formattng the Output wth cout 4he o0erloaded function for insertion o$erator LL of the ostream class format the 0aria-les -efore dis$la1ing. 4he default formats are as follo<s' char dis$la1ed as a character, uses one $osition. nt dis$la1ed as a decimal integer uses s$ace 3ust enough for the num-er and a minus sign if the 34
num-er is negati0e. foat dis$la1ed <ith # decimal $laces, e6ce$t for the & doubetrailing ?eroes. 4he field is 3ust <ide enough for the num-er and a minus sign if num-er is negati0e. 4he num-er is in fi6ed;$oint notation or normali?ed form, <hiche0er ta@es less s$ace. Character dis$la1ed in a field e&ual to the length of the Strngs string. e.g. [ include L iostream.h D 0oid main() R char nameH1..I M WIVL22C585L22XS char h M C0=S int $osnum M 123S int negnum M ;123S dou-le d M 123"#().123"##S float f M 123.123S cout LL W 4his is string ' H W LL name LL WI^nXS cout LL W 4his is character ' HW LL ch LL WI^nXS cout LL W Positi0e integer 'HWS coutLL $osnum LL W I^nXS cout LL W 9egati0e Integer 'HWS coutLL negnum LL W I^nXS coutLL W Float 'HW LL f LL XI^nWS cout LL W :ou-le ' HW LL d LL XI^nWS cout LL W integer di0ision 1.J3 M HWS cout LL 1.J3 LL W I^nXS cout LL Wfloating :i0ision 1... J3..M HWS cout LL 1...J3.. LL W I^nXS T 2ut$ut ' 4his is string ' H IVL22C585L22I 4his is character ' H,I 35
Positi0e integer 'H123I 9egati0e Integer 'H;123I Float 'H123.123...I :ou-le ' H123"#().123"(I integer di0ision 1.J3 M H3I floating :i0ision 1... J3..M H3.333333I 10.18. Manpuators 5s discussed earlier, there are se0eral classes in the iostream.h header file. 2ne of them is ios class. 4his class stores the format state. For instance, some -its define the -ase in <hich the num-ers <ill -e $rinted, some -its define the field <idth. 4his header file has functions called mani$ulators, using <hich the out$ut format can -e controlled. 4here are 3 mani$ulators dec(), oct(), he6() to set the -ase in <hich a gi0en num-er <ill -e $rinted. 4hese mani$ulators are called in t<o <a1s ' he6(cout)S JJ Pass the o-3ect name coutLL he6S JJ use the insertion o$erator . !ut since these mani$ulators are not mem-er functions of the class , it cannot -e used as follo<s ' cout.he6()S JJ 9ot allo<ed. e.g. 0oid main(0oid) R int i M11.S cout LL W :efault !ase :ecimal 'W LL i LL endlS cout LL he6S JJ Print in he6adecimal cout LL W Be6adecimal 'W LL i LL endlS cout LL octS JJ Print in 2ctal cout LL W 2ctal 'W LL i LL endlS 36
dec(cout)S JJ !ac@ to decimal cout LL W :ecimal ' W LL iS T 2ut$ut ' :efault !ase :ecimal ' 11. Be6adecimal '#e 2ctal '1"# :ecimal '11. 10.18.1. Changng Fed wdth 4he $rintf() and scanf() functions from the standard li-rar1, use <idth s$ecifier for controlling the <idth of its out$ut . similarl1, the ostream class also has a mem-er function <idth() for the same. 4his function has the follo<ing $rotot1$e. int <idth(0oid)S int <idth(int ne<si?e)S 4he first form returns the current field <idth. 4he default is al<a1s ?ero. 4hat is -ecause , the cout o-3ect al<a1s uses s$ace 3ust <ide enough to out$ut the 0alues and a default si?e if ?ero matches all. 4he second form can -e used to change the current <idth setting. 4he argument $assed to it is the ne< <idth to -e set. It also returns the $re0ious <idth. 4he <idth() function affects onl1 the ne6t item dis$la1ed. 4he filed <idth re0erts to default after<ards. e.g. 0oid main() R coutLLX default <idthMXLL cout.<idth()LLendlS coutLLXHWS cout.<idth(1.)S Set <idth to 1. coutLLX5XS coutLLXIXS T 37
2ut$ut' :efault <idth M .S H 5I 4his is 0er1 useful in $re$aring re$orts. 10.18.2. Paddng the Extra Paces !1 default, C++ $ads s$aces to e6tra $laces, if the <idth s$ecified is more than the actual out$ut . ostream contains a function fill() to set a ne< fill character. 4he function $rotot1$es are ' char fill(0oid) JJ/eturns current fill character char fill(char c)JJSet a ne< fill character. e.g. 0oid main() R int amt1 M 1.., amt2M 123"S cout.fill(CA=)S cout LL W 5mount1 ' HWS cout.<idth(")S cout LL amt1 LLXI^nXS cout LL W5mount 2 ' HWS cout.<idth(")S cout LL amt2 LL WI^nXS T 2ut$ut ' 5mount 1 ' HAA1..I 5mount 2 ' H123"I 10.18.3. Settng a precson !1 default, C++ $rints si6 decimal $laces after the decimal $oint, e6ce$t for trailing ?eroes. 4he function $recision() can -e used to change this default -eha0ior. 4he 38
function does not merel1 truncate the trailing digits, it rounds them u$. 4his function has the follo<ing $rotot1$e ' int $recision(0oid)S JJ /eturns a Current ,alue int $recision(int $)S JJ set a ne< $recision e.g. 0oid main() R float f1 M 123.3S float f2 M 1... J 3..S float f3 M 1... J #..S cout LL W :efault f1 M H WLL f1 LLXI^nXS cout LL W :efault f2 M H WLL f2 LLXI^nXS cout LL W :efault f1 M H WLL f3 LLXI^nXS cout.$recision(2)S cout LL W f1 M H WLL f1 LLXI^nXS cout LL W f2 M H WLL f2 LLXI^nXS cout LL W f3 M H WLL f3 LLXI^nXS T 2ut$ut ' :efault f1 M H123.3I :efault f2 M H3.333333I :efault f3 M H1.#####(I f1 M H123.3I f2 M H3.33I f3 M H1.#(I 10.18.4. The setf() Functon 39
4he ios contains a function setf() for controlling se0eral formatting features. 4his class defines a set of enumerated constants that can -e used as arguments to the setf() function. 4his function has the follo<ing $rotot1$es ' long setf(long flag-it)S long setf(long flag-it, int field)S 4he first $rotot1$e has onl1 one argument. It can -e an1 one of the follo<ing ' %numerated Constant 8eaning Sho<-ase 7se -ase $refi6es( ., .6) for out$ut Sho<$oint Sho< decimal $oint and trailing ?eros 7$$ercase 7se u$$ercase letters for he6 out$ut (5;F) sho<$os 7se + for $ositi0e num-ers 4hese constants are enumerated constants, defined in the ios class definition and therefore ha0e a class sco$e. 4he1 ha0e to -e $refi6ed -1 the name of the class <ith the sco$e resolution o$erator(''). e.g. cout.setf(ios''sho<$oint)S 4he a-o0e e6am$le sho<s the trailing ?eros and decimal $oint. 4he second $rotot1$e has t<o arguments. 4he first argument defines the -it settings that ha0e to -e changed. 4hese arguments can -e an1 of the follo<ing ' 40
%numerated Constants 8eaning First 5rgument Second argument !ase field dec oct he6 7se :ecimal -ase 7se 2ctal -ase 7se Be6adecimal -ase Float field Fi6ed Scientific 7se fi6ed $oint notation use scientific notation 5d3ustfield Left /ight Internal Left 3ustified for out$ut. /ight 3ustified for 2ut$ut. Left 3ustif1 the sign and -ase $refi6, -ut right 3ustif1 the 0alue e.g. 0oid main() R int inum M 11.S cout.setf(ios''sho<$os)S JJ sho< $lus sign cout LL Wsho<$os ' H W LL inum LL W I^nXS cout LL Be6 ' HW LL he6 LL inum LL WI^nXS cout.setf(ios''sho<-ase)S JJ sho< -ase $refi6. cout LL X!ase $refi6 'HWLL inum LL WI^nXS cout.setf(ios''u$$ercaseTS JJ u$$ercase he6. cout LL X7$$ercase he6 'HWLL inum LL WI^nXS 41
3ustified. cout LL X/ight 3ustified 'HWS cout.<idth(#)S cout LL inum LL WI^nXS T 2ut$ut' Sho<$os ' H+11.I Be6 ' H#eI !ase $refi6 ' H.6#eI 7$$ercase he6 ' H.6#eI Left 3ustified' H+11.I /ight 3ustified' H+11.I e.g. 0oid main() R float f M 1...S cout LL WFloat 'HW LL f LL WI^nXS cout.setf(ios''sho<$oint)S JJ sho< trailing .s and $oint cout LL Wsho< $oint ' H W LL f LL WI^nXS cout.$recision(2)S cout LL W2 decimals 'HWLLfLLXI^nXS 42
cout.setf(ios''scientific, ios '' floatfield)S cout LL WScientific ' H W LL f LL WI^nXS T out$ut' Float ' H+1.I Sho<$oint ' H+1........I 2decimals ' H+1....I scientific ' H+1...e+.1I 10.19. Other stream Functons. 5$art from the o0erloaded function for the e6traction o$erator, the istream class also has some other function. 2ne of them is get() <ith the follo<ing $rotot1$e ' istream Fget( char Fch)S int get(0oid)S 4hese functions acce$t a character. 4he first form stores the character entered in ch and returns a reference to the istream o-3ect. 4he second form returns -ac@ the character entered. e.g. 0oid main() R char ch1,ch2S cout LL W%nter a String ' WS cin DD chS <hile(ch EM C^n=) R cout LL chS cin DD chS T T 4he $rogram gi0en a-o0e <ill not <or@, since cin does not recogni?e <hite s$ace characters and hence , <ill ignore the LreturnD character resulting in an infinite loo$. 4he solution is to use get() as -elo<' 43
e.g. 0oid main() R char ch1,ch2S cout L, W%nter a String ' WS cin.get(ch)S <hile(ch EM C^n=) R cout LLchS cin.get(ch)S T T 4he istream class defines t<o other functions getline() and an o0erloaded get() function for acce$ting strings. 4heir function $rotot1$es are ' istream Fgetline(cahr As, int si?e, char ch M=^n=)S istream Fget(cahr As, int si?e, char ch M=^n=)S 4he first argument is the address of the location <here the in$ut string is to -e $laced. 4he second argument is the num-er of ma6imum characters to -e read $lus num-er. 4he third argument is the terminating character,. If omitted the function reads u$ to ma6imum characters s$ecified or until ne< line character <hiche0er is encountered first. e.g. char stringH1..IS cin.get(string,".)S this function reads u$ to + characters or until ne< line character <hiche0er is encountered first. e.g. 0oid main() R 44
char Astr M ne< charH1..IS cout LL Wenter a stringXS cin.get(str,",=^n=)S cout LLstrS T 4he difference -et<een get() and getline() is that get() lea0es the ne< line character in the in$ut s1stem, <hereas getline() e6tracts it from the stream. 1..2..Function 4em$lates Functon tempates provde you wth the capabty to wrte a snge functon that s a skeeton, or tempate, for a famy of smar functons. In functon overoadng technque t reeves someone who s usng your functons from havng to know about dfferent names for varous functons that essentay do the same task. Unfortunatey, overoaded functons are not the utmate souton to the probem that s nherent when wrtng functons that are smar n ther behavor. Consder the foowng exampe: nt max(nt x, nt y) { return ( x > y) ? x : y ; } foat max(foat x, foat y) { return ( x > y) ? x : y ; } ong max( ong x, ong y) { return ( x > y) ? x : y ; } char max(char x, char y) { return ( x > y) ? x : y ; } 45
vod man() { cout << max( 1,2) << end; cout << max( 4L,3L) << end; cout << max( 5.62,3.48) << end; cout << max(A,a) << end; } The output s : 2 4 5.62 a Even though functon overoadng s used, the probem wth ths exampe s that there s st too much repettous codng. In other words, each functon s essentay dong the same task. Now, nstead of you havng to wrte many functons, t woud be nce f were to wrte ony one functon and can accommodate amost any type of nput argument. Bo< a Function 4em$late sol0es this $ro-lem A functon tempate soves the probem by aowng you to wrte |ust one functon that serves as a skeeton, or, tempate, for a famy of functons whose tasks are a smar. Ths functon tempate does not specfy the actua types of the arguments that the functon accepts; nstead , t uses a generc, or parameterzed type, as a " pace hoder", unt you determne the specfc types. The process of nvocaton of these functons wth actua parameter types s caed the tempate nstantaton. Bo< to <rite a function tem$late A functon tempate shoud be wrtten at the start of the program n the goba area, or you may pace t nto a header fe. A functon tempates start wth a tempate decaraton. The syntax s : The C++ keyword template A eft ange bracket ( < ) 46
A comma separates a st of generc types, each one. A generc type conssts of two parts 1. the keyword class ( ths usage of cass has nothng to do wth the key word cass used to create user-defned type.) 2. a varabe that represents some generc type, and w be used whenever ths type needs to be wrtten n the functon defnton. Typcay the name T s used, but any vad C++ name w do. A rght ange bracket ( > ). e.g. tempate < cass T> T max(char x, char y) { return ( x > y) ? x : y ; } vod man() { cout << max( 1,2) << end; cout << max( 5.62,3.48) << end; cout << max(A,a) << end; cout << max( 4,3) << end; } The output s : 2 5.62 a 6 Each of frst three max () functon cass causes a tempate functon to be nstantated, frst wth an nt, then wth a doube and then wth a char. The ast ca usng two ntegers does not cause another nstantaton to occur because ths ca can use the nstantated functon that was generated as a resut of the frst cass that aso uses two ntegers. The tempate needs to have parameters, ether a tempate type representng a type or a tempate non-type parameter representng a constant expresson. e.g. 47
} return ( mn_va); } where Heo can be but n or user defned type and sze s aways constant and nteger. A tempate type specfer can be used for varabe decaraton ( n the above exampe , t s used to decare mn_va), casts etc., |ust ke norma varabe. we can have more than one tempate parameter type n the same tempate . e.g. tempate < cass T1, cass T2, cass T3> T3 mn (T1 a , T2 b); We can even overoad functon tempates. e.g. tempate <cass T> T mn ( T *, nt); tempate <cass T> T mn ( T , nt); tempate <cass T> T mn ( T , T); 48
1..21 Class 4em$lates. In addition to function templates !"" also supports the concept of class templates. #y definition a class template is a class definition that describes a family of related classes. $he philosophy is essentially the same as that of function templates i.e. the ability to create a class %or structure& that contains one or more types that are generic or parameterized. A cass tempate s defned n a manner smar to that of a functon tempate. You start by wrtng a tempate decaraton foowed by the cass defnton: e.g. Tempate <cass T> cass test { prvate : T tem; // data and functons }; The generaton of a cass from cass defnton s caed template instantiation. We can decare varabes of ths cass as foows: vod man() { test<nt> ntob|; test<doube> doubeob|; } In the first instantiation the entire tem$late t1$es i.e. 0aria-les of t1$e 4 <ill -e con0erted as integers. In the second case the1 are con0erted as dou-le 0aria-les. Of course, you may have more than one parameterzed type between the ange brackets. Tempate < cass T1, cass T2, cass T3> cass cassname; Each parameter shoud be preceded wth the keyword cass. 49
Tempate < cass T, U > // Error Tempate < cass T, cass U> // O.K. In ths sesson we have seen how a statc varabe and statc functon combnaton can be used for varabes, whch are shared by a the ob|ects and hence can be gven a snge memory ocaton and how ob|ects are not requred to nvoke them. We aso earnt how to share our prvate detas wth frends, whch though shoud not be overused, but becomes extremey necessary sometmes. Usng the manpuators and ostream ob|ects we can enhance the way our output appears on the screen. Functons can be made as nne functons f they are sma. These are substtuted n pace of functon cas and are faster compared to cang and returnng as compared to norma functons. We aso earnt how the shortcomngs of functon overoadng coud be overcome usng tempate functons. A non-type parameter represents a constant vaue. Tempate < cass T, const nt buffer > cass cassname; The functons of the tempate casses obey the rues of the functon tempates. 4his session co0ered the su-tle as$ects of C++, <hich could not -e classified under an1 of the $re0ious sessions. Ue discussed a-out friend functions, <hich though are 0er1 tem$ting, should not -e o0erused. 4he conce$t of tem$lates gi0es another dimension to o0erloading and reusa-ilit1. Ue sa< ho< friend functions along <ith o$erator o0erloading can ma@e the o-3ects loo@ li@e normal 0aria-les and thus gi0ing the language a more natural loo@. Ue also co0ered ho< to enhance the out$ut of the $rogram. Exercses: 1. Urite am $rogram to acce$t details of 9 students. Venerate the register num-er for them using the static 0aria-le and static functions. 50
2. 5n airlines com$an1 recruits female candidates for the $ost of airhostess. U5P to create a class named C59:I54% . 4he class should contain the candidate=s name, age, se6, <eight, height and &ualification. Include a constructor and a destructor for this class. Include a mem-er function to acce$t the data and dis$la1 the data. Create a class named P%/F%C4 to acce$t the e6act re&uirements in terms of age, <eight, height, and &ualification from the com$an1. 4he follo<ing chec@s should -e $erformed' ;;se6 and &ualification should -e same as that of P%/F%C4. 20erload the M o$erator for this chec@. ;;age ,<eight and height should -e less than or e&ual to the P%/F%C4. 20erload the o$erator LM for this chec@. !ased on the return t1$e of the a-o0e $erform the follo<ing o$erations. ; if the first condition is ;0e, then dis$la1 the message ,`re3ected`. ; if the first condition is +0e -ut the second is ;0e , then dis$la1, `<ill -e called later`. - if -oth the conditions are +0e ,the candidate is called for the first inter0ie< and dis$la1 `called for the first inter0ie<. 51