Sei sulla pagina 1di 146

C

#include <stdio.h> Function <printf Scanf

C++
#include <iostream.h> cout. in are objects cout << Hello; Insertion operator Or Insertors cout << alue ! <<a; "o need of format specefiers In #$$ cin >>a; *+traction operator Or *+tractor cin >>a >>b; #ascadin, of e+tractor; cout << Hello .n /ser; Or cout << Hello <<end<</ser; in #$$ default return t0pe is an inte,er

Scanf % &d' (a);

for ne+t line -rintf % Hello .n user);

In #' default return t0pe is oid

HISTORY OF C++

1ear 2345 6e eloped 70 7jarne stroustrap 8ab 7ell 8abs #ompan0 9t ( :

# is procedure oriented lan,ua,e *as0 ( fast pro,rammin, in #. 8o,ics can be easil0 de eloped

# is object oriented lan,ua,e #$$ closel0 models rear ;orld problem sol in, approach.

CLASSES AND OBJECTS


In structure of # <= onl0 data can be member of structure and not functions 9ll member of structure of are public b0 default In class of #$$ data $ functions accessin, those data are member of class and 9ll member of class are pri ate b0 default class stud > int roll; char ,rade; float par; public< oid ,et% ); oid sho;% ); ?; oid stud < < ,et% ) > cout << enter roll. @rade and per; cin>>roll>> ,rade >> per; ? oid stud < < sho; > cout <<roll << << ,rade << <<per<< end2; ? oid main% ) > stud s; s. ,et % ); s. sho;% ); ? -er s ,et sho; ,rade roll

Function are ne er seplicated there is onl0 one cop0 of function no matter no; man0 objects are created onl0 once memor0 is allocated to functions for all objects ;here as multiple copies of data are created for multiple objects. < < Scope resolution operator helps compiler to identif0 functions of ;hich class if t;o classes ha e the same name. A. 2 ;ap to add t;o numbers ,i e b0 user class add > int a' b' c; public < oid ,et% ); oid sum% ); oid sho;% ); ?; oid add < < ,et % ) > cout << *nter no; cin >> a >>b; ? oid add < < sum% ) > c! a$b; ? oid add < < sho;% ) > cout << "umbers are ! << a << << b; cout << sum ! <<c; ? oid main% ) > add obj; obj. ,et% ); obj.sum% ); obj. sho;% ); ,etch% );

#$$ %:erminolo,0) 2. objects 5. data members B. member function C. function call

OO-s %:erminolo,0) instances properties ( attributes methods ( beha iors messa,e passin,

BASIC PRINCIPLES OF OOP


ENCAPSULATION Dord has been deri ed from a ;ord capsule ;hich means multiple medicines pacEed in one sin,le unit. Similarl0 in a soft;are there are t;o major unit data ( functions actin, on that data since functions and data are related entities it is ad isable to score them ;ithin a sin,le unit. :hus accordin, to oopFs *ncapsulation means buildin, or ;rappin, up of data members and f n actin, on those data members ;ith in a sin,le unit. Since a class allo;s us to hold data ( functions ;ithin it are sa0 that it supports the principle of encapsulation. POLYMORPHISM :he ;ord pol0morphism is deri ed from combination of t;o ;ords pol0 meanin, multiple and morph means the abilit0 to ha e multiple forms. In other ;ords if an entit0 can acGuire multiple forms in different situation ;e sa0 that its beha iors is pol0morphic for e, in c$$ it is possible for pro,rammer to redife operator H$F in such a ;a0 that it can be used to add t;o inte,ers as ;ell as at the same time it can add t;o abject or t;o strin,s. So it a pro,rammer define $ to beha e in abo e mentioned member ;e sa0 that $ beha es pol0morphicall0 . In #$$' pol0morphism is implemented in t;o ;a0<= (1). Compile ime pol!mo"p#i$m <= function o erloadin, and operator O erloadin, (%). R&'Time pol!mo"p#i$m<= Iirtual functions' pure irtual functions 9bstract classes (iii). I'#e"i (')e <= to inherit means to acGuire properties and features of an e+istin, entit0 into a ne;l0 created entit0 8iEe a child acGuires properties of his or her parents' similar0 ;hen desi,nin, soft;are if a pro,rammer ;ishes then he can acGuire the data member and

member function of an e+istin, class in his o;n class ;ith the help of inheritance. :he class ;hich ,ets inherited is Eno;n as base class and the class ;hich inherits is Eno;n as deri ed class. :hus b0 inheritin, the members of base class it becomes possible to access them throu,h the objects of deri e class. :he major ad anta,e offered b0 principle of Inheritance is reusabilit0 and reliabilit0 CREATIN* PARAMETERI+ED FUNCTIONS ,ITHIN CLASSES class *mp > int a,e; char nameJ5KL; float salar0; public< oid set %int ' char M' float); oid sho;% ); ?; oid *mp< < set %int I' char Mj' float N) > a,e !I; strcp0%name' j); salar0 !E; ? oid *mp < < sho;% ) > cout <<a,e << <<name << salar0; ? ASSI*NMENT Dap to create a class cOa strin,. :he class must contain a character arra0 of siPe 5K. class should ha e follo;in, fucnitons< %2). *e $ "i'-( ) ;hich accept strin, as parameter $ stores it in arra0 str. %5). S#o. $ "i'-( ) ;hich displa0 the strin, stored in strJL. %B). Re/e"$e$ "i'- ( ) ;hich re erses the strin, stored in strJL. %C). A00 $ "i'-( ) ;hich accepts strin, as parameter and if possible #oncatenates in str.

Drite an object oriented pro,ram to calculate the factorial of a ,i en b0 user. -ro ide separated function for initialiPation' inputtin,' calculatin, and displa0. class Fact > lon, int f; int n; public< oid init% ); oid ,etno% ); oid calculate% ); oid displa0% ); ?; oid Fact < < init% ) > f!2; ? oid Fact < < ,etno% ) > cout << *nter a number; cin >> n; ? oid Fact < < calculate% ) > int i; for %i!2; i<!n; i$$) f!f M i; ? oid Fact < < displa0% ) > cout << "umber ! << n; cout << factorial! <<f; ? oid main% ) > Fact obj ; obj. init% ); obj.,etno% ); obj.,et calculate% );

obj. displa0% ); ?

CONTRUCTOR
Co'$ "&) o" <= constructor are special member f n of a class ;ith the follo;in, properties 2. :he0 ha e the same name as that of the class 5. :he0 donFt ha e an0 return t0pe not e en oid B. :he0 are automaticall0 called as soon as the object of class is created i.e. their callin, is implicit. C. :he0 canFt be declared as static Q. :he0 canFt be declared as irtual 9n0 class ;hich does not contain an0 constructor then compiler from itself supplier a constructor but it is hidden. for pro,rammer these constructors are default class fact > ?; #onstructors are automaticall0 called e en ;hen not declared' at that time default constructors are called. 6efault contructors are destro0ed as soon as ;e declare constructor E1(mple 23 class fact > int n; lon, int f; public< fact% ) > f!2; ? oid ,etno% ); oid calculate% ); oid displa0% );

?; oid fact < < ,etno% ) > cout << enter a no; cin >> n; ? oid fact < < calculate% ) > int i; for %i!2; i<!n; i$$) f! f M i; ? oid fact < < displa0 % ) > cout << no! <<n<<end2; cout << factorial! <<f; ? oid main% ) > fact obj; obj.,etno% ); obj.calculate% ); obj.displa0% ); ?

PARAMETERI+ED CONSTRUCTOR
class *mp > int a,e; char nameJ5KL; float sal; public< *mp %int' char M' float); oid sho;% ); ?; *mp < < *mp %int i' char Mj' float E) > a,e !i; strcp0 %name' j);

sal!E; ? oid *mp < < sho;% ) > cout << a,e << << name<< H H <<sal; ? oid main% ) > *mp e%2K2'9mit'RKKK.KK) ; e.sho;% ); ,etch% ); ?

FUNCTION O4ERLOADIN*
2. "o. of 9r,uments 5. :0pe of 9r,ument B. Order of ar,ument oid sho; %int' int' int) oid sho; %int) oid sho; %double) oid sho; %int' double) oid sho; %double' int)

int sho; % ) "ot allo;ed %return t0pe differs) oid sho;% ) #ompiler does not consider return t0pe' because it is not compulsor0 to recei e the alue returned b0 the function. :hus compiler ;ill not be able to differentiate for ;hich function the call is bein, made. Function o erloadin, allo;s same function name in same scope but there should be some difference in functions. oid ol %int); oid ol %int' int' int ); oid main % ) > int choice; cout << select a fi,ure; cout << %2) cube .n %5) cuboid; cin >> choice;

s;itch %choice) > case 2< int s; cout << enter side of cube; cin >> s; ol %s); breaE; case 5< int l' b' h; cout << *nter l' b and h of alues ; cin >> l >> b >> h; ol %l'b' h); breaE; default< cout << ;ron, choice; ? ? oid ol %int s) > cout << alue of cube ! << sMsMs; ? oid ol %int l' int b' int h) > cout << alue of cuboard! << lMbMh; ? AD4ANTA*ES OF FUNCTION O4ERLODIN* 2. O erload of rememberin, the name is transformed from pro,rammer to compiler 5. it de elops s0mmetr0 ( incresa,e the readabilit0 of pro,ram CONSTRUCTOR O4ERLOADIN* class 7o+ > int l' b'h; public< 7o+% ); OOconstructor for user defined 7o+

7o+ %int); OOconstructor 7o+%int'int'int); OOconstructor oid sho;% ); ?; 7o+ < < 7o+% ) > cout << enter l' b and h of bo+; cin >> l >> b>> h; ? 7o+ < < 7o+%int s) > l!b!h!s; ? 7o+ < < 7o+ %int i' int j' int E) > l!i; b!j; h!E; ? oid 7o+ < < sho;% ) > cout << l << <<b<< << h; ? oid main % ) > 7o+ 72; 7o+ 75 %Q'S'22); 7o+ 7B %2K); 72. sho;% ); 75. sho; % ); 7B. sho; % ); ?

COPY CONSTRUCTOR
It is a special constructor of a class ;hich accepts the reference of the object of its o;n class as a parameter. It is called b0 c$$ compiler in there situations 2. ;hen e er pro,rammer creates an object and at the same time passes another object of the same class as a parameter

5. ;hene er a f n accepts an object as a parameter b0 alue. B. ;hene er a f n returns an object b0 alue. Re5e"e')e /("i(6le23 S0nta+<= <data t0pe> ( <ref=name> ! < ar=name>; oid main% ) > int a ! 2K; int Mp; p!(a; cout <<Mp <<end2; ? oid main % ) > int a!2K; int (p!a;OOp is reference ar. cout <<a<< <<p; cout << (a << <<(p; ? 6ra;bacEs of pointer 2. ;ill be initialiPed b0 ,arba,e 5. necessar0 to initialiPe before their use B. er0 careful in usin, indirection operator 9d anta,e of Teference ariable 2. ;e can ha e n reference ariables of one ariable 5. both ariables ,et interlocEed on each Other B. does not reGuire an0 memor0 space it Onl0 reuse the memor0 of an0 ariable

Teference ariable is a technolo,0 pro ided b0 c$$ ;hich allo; a pro,rammer to create a ne; ariable ;hich stores %not holds) the memor0 location of an e+istin, ariable. In other ;ords' reference ariable is a techniGue usin, ;hich pro,rammer can allot multiple mames to same memor0 location. POINTS TO REMEMBER 2. int (p ! a; 5. int (p !b; multiple declarations for the ariable p. B. In case of arra0' al;a0s use pointer. Teference ariable can not ;orE ;ith arra0 C. ;e can not maEe arra0 of reference ariable int (p JCLF

#O#$$

#O#$$

onl0 in #$$ p($$ 6! "e5e"e')e oid s;ap %int('int(); oid main% ) > int a'b; clrscr% ) ; cout << enter5no) cin>>a>>b; s;ap %a'b); cout <<a<< <<b; ? oid s;ap%int(p'int(G) > int temp; temp!p; p!G; G!temp; ?

p($$ 6! /(l&e p($$ 6! (00"e$$ oid s;ap %int' int); oid s;ap %intM' intM); oid main% ) oid main% ) > > int a'b; int a'b; cout << *nter5 number; cout << *nter5no; cin >>a>>b; cin >> a >> b; s;ap %a'b); s;ap %(a' (b) cout << a << <<b; cout <<a<< <<b; ? ? oid s;ap%int p'intG) oid s;ap %intMp' intMG) > > int temp; int temp; temp !p; temp!Mp; p!G; Mp!MG; G!temp; MG! temp; ? ?

A. D9- to use a function call ma+imum ;hich accepts an inte,er arra0 of siPe pure as an ar,ument ( return the lar,est ( smallest element of that arra0 to main. Dithout chan,in, the ori,inal position of element of arra0. oid Ua+imum %int aJL' int (' int(); oid main% ) > int aJQL' i' lar,e' small; for %i!K; i<Q; i$$) > cout << enter elements of arra0; cin >>aJiL; ? Ua+imum %a' lar,e' small); cout << ma+imum element! <<lar,e; cout << smallert element! <<small; ? oid Ua+imum %int aJQL' int (ma+' int ( min) > ma+ ! aJKL; min!aJKL; for%int i!2; i<Q; i$$) > if %M%a$i) >ma+) ma+!M %a$i); else if %M %a$i) <min) min ! M%a$i); ? ? class 7o+ > int l' b' h; public< 7o+% ); 7o+ %int); 7o+ %int' int' int); 7o+ %7o+ (); oid sho;% );

?; 7o+ < < 7o+% ) > cout << enter l' b and h of 7o+; cin >> l >> b >> h; ? 7o+ < < 7o+ %int S) > l!b!h!s; ? 7o+ < < 7o+ %7o+ (p) > l!p.l; b!p.b; h!p.h; ? 7o+ < < 7o+ %int i' int j' int E) > l!i; b!j; h!E; ? oid 7o+ < < sho;% ) > cout << l << << b << << h; ? oid main % ) > 7o+ 72; 7o+ 75 %2K); 7o+ 75 %Q'S'22); 7o+ 7C %72); 72. sho;% ); 75.sho;% ); 7B.sho;% ); 7C.sho;% ); ? 7o+ 75 %2K) 7o+ 7C %72) 7o+ 75 ! 2K; 7o+ 7C ! 7;

#all for cop0 constructor 7o+ 7C; 7C ! 72 "o call for cop0 constructor use of assi,nment operator other destination object is alread0 made

DEFUALT AR*UMENTS
oid printline %char !FMF' int!2); oid main % ) > printline % ); OO printline %HMF' 2) printline %H#F); OO printline % H#F' 2) printline %HVF' 2K) OO printline %HVF' 2K); ? oid printline %char ch' int n) > for %int i!2 i<!n; i$$) cout <<ch; ? No e73 6efault ar,uments must al;a0s be trailin, ar,uments. printline%QK); printline %9S#II of QK' 2); class Stud > int a,e; char ,rade; float per; public< Stud %int' char' float); OO stud %int!o' char! H ; float!K.K); oid ,et% ); oid sho;% ); ?; Stud < < Stud %int I' char j' float E) > a,e !I; ,rade! j;

per !E; ? oid Stud < < ,et% ) > cout << *nter a,e' ,rade ( per H; cin >> a,e >> ,rade >> per; ? oid Stud < < sho;% ) > cout<< a,e ! <<a,e<< .n ,rade! <<,rade<< .n per ! ? oid main% ) > Stud t % 2Q' H9F' SQ); Stud p; p. ,et% ); t. sho;% ); p. sho;% ); ? <<per;

No e<= In class at same time it is not possible to ha e default ar,ument constructor and default constructor.

DESTRUCTOR
9re special member f n of class ;hich ha e same name as that of the class but preceded ;ith the s0mbol of tilde %W). :he0 are automaticall0 called ;hene er an object ,oes out of scope' that is 'it is about to be destro0ed Dhen an object is created first function ;hich is automaticall0 called is constructor ( ;hen object ends its life the last function ;hich is called is destructor ;hich can be used to deallocate the resource occupied b0 the object. class *mp > int a,e; char name J5KL; float sal; public< *mp% );

W*mp% ); oid sho;% ); ?; *mp < < *mp% ) > cout << *nter a,e' name ( sal; cin >> a,e >> name >> sal; ? oid *mp < < sho;% ) No e > 9 class b0 default has B built in cout <<a,e << name <<sal; fucntion ? 2. #onstructor *mp < <W *mp% ) 5. cop0 constructor > B. 6estructor cout << Object destro0ed; ? "ote<= 6estructors are al;a0s called in oid main% ) re erse order. > *mp e' f'; e. sho;% ); f. sho;% ); ? #reate a class cOo student ha in, B data members %i) for storin, Toll no. %ii) for storin, name %iii) for storin, marEs in subjects :he member for storin, name should be char M' member for storin, marEs should be int M; #reate constructor of class ;hich prompts user to enter len,th of name' allocates sufficient memor0 ( accepts the name from user. :he same constructor asEs the user ho; man0 subject he ;ant to enter' a,ainallocate sufficient memor0 for that ( accepts the marEs ,i en b0 user. Finall0 pro ide appropriate member f n ;hich displa0 & ( ,rade of student. 9t the end define the destructor in proper manner to deallocate memor0 allocated b0 constructor. class student > int roll 'n; char M name' ,rade;

int MmarEs; float per; public< student % ); oid ,et%); oid calculate% ); oid sho;% ); Wstudent% ); ? student < < student % ) > cout << ho; man0 letters; cin >>n; name ! %char M) malloc %%n$2) M siPeof %char)); if %name! ! "/88) e+it%2); ,et% ); ? oid student < < ,et% ) > cout << enter roll no; cin >> roll ; cout << enter name; cin >> name; cout << ho; man0 subject are there enter ; cin >>n; marEs!%intM)malloc%nM5); for %i!K; i<n; i$$) > cout << *nter marEs; cin >> M %marEs$i); ? ? oid student < < calculate % ) > per!K; for %int i!K; i<n; i$$) per$! M %marEs$i)

per !perOn; if %per >!SQ) ,rade ! H9F; else if %per >!RK) ,rade ! H7F; else ,rade ! HfF; ? student < <W student % ) > free %name); free%marEs); ? oid student < < sho;% ) > cout<< "ame ! <<name<<.n roll number ! <<roll; cout<< per!<<per<< .n ,rade!<<,rade; for%int i!K;i<n;i$$) cout<<.n <<marEsJiL; ? oid main% ) > sudent s; s. calculate% ); s. sho;% ); ? "ote In #$$' cin donFt accepts the space oid main% ) > char strJ5KL; cout << enter name; cin >> str; ? cin.,etline %str' 4K); OO*nter Ne0 O3. -rotot0pe of ,et line % ) oid ,et line %char M' int ); Uember of istream header file COMPARISION BET,EEN

CONSTRUCTOR 8 DESTRUCTOR CONSTRUCTOR 2. are special member f n of a class ha in, same name as that of the class. 5. constructors are automaticall0 called as soon as object of class is created i.e. their callin, is implicit B. constructors can be parameteriPed. C. since constructors accepts parameters the0 can be o erloaded ( thus a class can ha e multiple constructors. Q. constructors are called in the orders in ;hich objects are created. R. constructors can not be inherited. S. constructors can not be declared as irtual. DESTRUCTOR 2. are special member fn of class ha in, same name as that of the class but preceded ;ith the s0mbol of tilde 5. a destructor is also automaticall0 called but ;hene er an object is about to be destructor or ,oes out of scope thus these callin, is implicit. B. ;e can not pass parameters to a destructor. C. as the0 donFt accept parameters ;e can not o erload then' thus a class can not ha e multiple destructor Q. callin, of destructor is al;a0s done in re erse or des of the creation of objects. R. inheritin, of destructor is also not possible S. ;e can ha e irtual destructor in a class.

INLINE FUCNTIONS
I'li'e 5&') io'$ 9re those fn ;hose call is replaced b0 their bod0 durin, compilation. 6eclarin, a fn as inline has t;o major ad anta,es. 2. compiler does not has to lea e the callin, fn as it finds definition of fn bein, called their it self. 5. :he o erhead of maintain, the stacE in bet;een function call is reduced :hus declarin, a function as inline increases the e+ecution Speed' s.reuces e+ecution time ( thus enhances the o erall efficienc0 of pro,ram. 7ut t;o ptr must be considered before declarin, a fn as inline

2. :he definition of inline function must appear before its call i.e. if a non member fn is to be made inline then its declaration ( definition must appear about main as a sin,le unit. 5. the bod0 of inline fn must be short ( small B. it should not contain an0 comple+ Ee0;ords or Ee0;ord or statement liEe for' if' ;hile' do;hile do' if an0 of the aboul sules are iolated then compiler i,nores the Ee0;ord inline an treats the fn as offline or normal one. Uoreo er a class can ha e t;o Einds of inline functions 1.Impli)i I'li'e <= fn efined ;ithin the bod0 of class %. E1pli)i I'li'e <= fn declared ;ithin the class but defined outside the class preceded ;ith the Ee0;ord inline. :hus at the end ;e can sa0' that declarin, a fn as line is a reGuest made b0 pro,rammer ;hich the later ma0 a,rel or den0. class *mp > char name J5KL; int a,e; float sal; public < oid ,et% ) Impli)i > I'li'e cout << enter a,e' name and sal; cin >> a,e >> name >> sal; ? oid sho;% ); ?; E1pli)i I'li'e inline oid *mp < < sho;% ) > cout << a,e << <<name << <<sal; ? oid main% ) > *mp *JQL;

int i for %i!K; i<Q; i$$) *JiL. ,et% ); for %i!K; i<Q; i$$) *JiL sho;% ); ?

STORA*E CLASSES
S o"(-e )l($$ 0e)i0e$ #e 5ollo.i'2. 6efault alue 5. life %persistence) B. scope %accessibilit0) $ o"(-e 0e5(&l 2.auto ,arba,e %automatic) 5. static B. re,ister C. ,lobal Xero ,arba,e Pero li5e limited to their 6eclaration 7locE throu,hout :he pro,ram same as auto throu,hout :he pro,ram $)ope limited to declaration blocE

same as auto throu,hout the pro,ram

A& o oid displa0 % ); oid main% ) > displa0% ); displa0 % ); displa0 % ); ? oid displa0% ) > int a; cout <<a<<end2; a$$;

S ( i) oid displa0 % ); oid main % ) > displa0% ); displa0 % ); displa0% ); ? oid displa0% ) > static int a; cout <<a<<end2;

? oOp B ,arba,e alues ;ill be ,enerated

a$$; ? oOp K 2 5

STATIC DATA

Static data members ;ith in the class class data > int a ; Static int b; ?; a int data < < b; d2

K a 65

static ariable donFt ;ait for creation of object' before object creation memor0 is allocated for then of class 2. 9 static data member has a sin,le cop0 shared amon,st each object of that class. On other hand if a class has non static data then e er0 object of that class has its o;n cop0 of non static data 5. static data members arri e in memor0 e en before objects of the class ,et created. 7ecause of their feature it becomes necessar0 to redefine them outside the class so that the0 can be ,i en space in T9U ;ithout the help of object. B. since the0 are not related to an0 particular object of the class ( ha e a sin,le cop0 in the entire class' a static data member ne er contributes in the siPe of object. In other ;ords siPe of object is al;a0s calculated b0 summin, up siPes of non static members. D9- to create a class cOo student ha in, t;o data members roll ( count. :he member roll should Eeep the roll no. allocated to e er0 student object ;hile the members count should Eeep tracE of total no. of student objects currentl0 in the

memor0. Finall0 pro ide appropriate members fn to initialiPe ( displa0 the alues of Toll no. ( count. class Student > int roll; static int count; public< Student %int i) > roll!i; $$ count ; ? oid sho;% ) > cout << Toll no! <<roll<<end2; cout << total objects ali e ! <<count; ? WStudent % ) > ==count; ? ?; int student < < count; oid main% ) > Student S!2K; Student -!5K; Student A!BK; S. sho;% ); -. sho;% ); A. sho;% ); > Student Y ! CK; Student 1!QK; Y. sho;% ); 1. sho;% ); ? ?

STATIC FUCNITON
S!' (1 <class=name> < < <function=name>%list of ar,uments);

RESTRICTIONS ON STATIC FUNCTIONS 2. static f n can ne er access non Zstatic data numbers. 7ut re erse is true. 5. #onstructor ( 6estructor can ne er be made or declared as static. B. If a static function is defined outside the class the Ee0;ord static cannot be used. class student > int roll; static int count; public < student %int i) > roll !i; $$count; ? oid sho;% ) > cout<<roll; ? static oid total[student%) > cout << total objects ali e ! <<count; ? Wstudent % ) > ==count; ? ?; int student < < count; oid main% )

> student S%2K). -%5K)' A%BK); S.sho;%); -.sho;%); A.sho;%); student < < total[student% ); > student Y%CK)' 1%QK); Y. sho;% ); 1.sho;%); student<<total[student%); ? student<<total[student%); ? student<<total[student%); ,etch% ); ? P"o-"(m <= #reate a class cOa emplo0a ha in, data members for storin, a,e' name ( id. 9lso pro ide another member ;hich stores the ne+t id ;hich ;ill be allocated to ne+t incomin, object. -ro ide a member f n to initialiPe this ariable ;ith its initial alue ( also pro ide appropriate constructor ( member f n for initialiPed all other members of class. class *mp > int a,e; char name J5KL; int id; static int nid; public< static oid init% ) > id!nid; ? *mp% ) > cout << enter a,e' name;

cin >> a,e >> name; id!nid; $$nid; ? oid sho;% ) > cout <<a,e<<name<<id; ? ?; Sol& io' 23 class *mplo0ee > int a,e; char nameJ5KL; int id; Static int ne+tid; public< *mplo0ee %int' char M); static oid initid% ); oid sho;% ); static oid ,etne+tid% ); W*mplo0ee% ); ?; int *mplo0ee << ne+tid; *mplo0ee < < *mplo0ee %int I' char M j) > a,e !I; strcp0 %name'j); id ! ne+tid$$; ? oid *mplo0ee < < initid% ) > ne+tid!2; ? oid *mplo0ee << sho;% ) > cout <<a,e<< <name << << id<<end2;

? oid *mplo0ce < < ,etne+tid% ) > cout << ne+t emplo0ee ;ill be ,i en id! <<ne+tid; ? *mplo0ce < < W*mplo0ee% ) > ==ne+tid; ? oid main% ) > *mplo0ee < < initid% ); *mplo0ee < < ,etne+tid% ); > *mplo0ee e %5Q' Tahul); *mplo0ee f %BK' ipin); e. sho;% ); f. sho;% ); *mplo0ee < < ,etne+tid% ); ? *mplo0ee < < ,etne+tid% ); ? ?

9 #i$: POINTER
class *mp > int a,e; char nameJ5KL; float sal; public < oid ,et% ) > cout << enter a,e' name ( sal< cin >> a,e>> name>>sal;

cout << 9ddress of callin, object ! <<this; ? oid sho;% ) > cout <<a,e<<name<<sal; cout << 9ddress of callin, object! <<this; ? ?; oid main% ) > *mp *' F; *.,et% ); F.,et% ); *.sho;% ); F.sho;% );F ? 2. * er0 member f n of class has this pointer. 5. "o need to declare ( initialiPe this pointer. #ompiler initialiPe it ;ith base address of callin, object.

9 #i$: POINTER
:his is a special pointer a ailable in e er0 member foundation of a class e+cept static member f n of a class. Dhene er the object of a class puts a call to an0 non static member f n of that class' the this pointer a ailable in that member f n implicitl0 starts pointin, to the address of callin, object. :hus ;e can sa0 that a this pointer al;a0s points or referr to the aurrent object. 70 default class has B this pointer. #onstructor cop0 constructor 6estructor A))e$$i'- D( ( Mem6e" U$i'- ; #i$: class 7o+ > int l' b' h;

public< 7o+% ); 7o+ %int' int' int ); 7o+ %7o+ (); oid sho;% ); ?; 7o+ < < 7o+% ) > cout << *nter l' b' and h; cin >> l >> b >> h; ? 7o+ < < 7o+ %int I' int j' int E) > l!i; <= )(' (l$o 6e ."i e' ($ thisl!l; b!j; thisb!b; h!E; thish!h;=< ?

7o+ < < 7o+ %7o+ (p) > l!p.l; b!p.b; h!p.h <= )(' (l$o 6e ."i e' ($ = #i$>p;MO ? oid 7o+ < < sho;% ) > cout << l << <<b<< <<h; cout << this l << thisb << this h; ? oid main% ) > 7o+ 72;

7o+ 75 %Q' S' 22); 7o+ 7B ! 72; 72. sho;% ); 75. sho;% ); 7B. sho;% ); ?

LIMITATIONS OF THIS
:his pointer al;a0s points to callin, object thus it can not be incremented or decremented. It is a constant pointer. Bo1 > =?7 @ > #i$+1 << /(li0 @>++ #i$ << 'o /(li0

USIN* THE 9)o'$ : AEY,ORD 2. 5. B. C. Q. R. S. #onst ariable pointer to const const pointer const pointer to const ariable const parameters data members of class member f n of a class

9)o'$ : 4("i(6le$ oid main % ) > const float pi!B.2C; ?

#onst ariable are initialiPed at the pt of declaration menns the0 are read onl0 ariables ( their alues can not be manipulated. cout <<pi$$ ; OO not alid.

9)o'$ : Poi' e" const int Mp;OO read as p is a pointer to a const int oid main% ) > int b!QK; int a !2K; const int Mp; OO can also be ;ritten as int const Mp p! (a; Mp!5K;OO in alid operation p!(b;OO alid operation ? i' = )o'$ P 23 is a const pointer to an inte,er means - canFt be incremented or decremented. :hus the0 are initialiPed at the time of declaration. %this pointer comes in the abo e cate,or0.) oid main% ) > int b!QK; int a!2K; int M const p!(a; Mp!5K; p!(b 9)o'$ : p("(me e"2 Dhen the const modifier is used ;ith a pointer parameter in a function\s parameter list' the function cannot modif0 the ariable that the pointer points to. For e+ample' int strlen%const char Mp)

Here the strlen function is pre ented from modif0in, the strin, that p points to. DorEin, on the same theme the protot0pe of a cop0 constructor is actuall0 <classname>%<classname> (<referencename>) For e+ample< 7o+ %const 7o+ (p) OO protot0pe of default cop0 constructor > 8!p.l; 7!p.b H!p.h ? Co'$ 0( ( mem6e"$ o5 )l($$ Uan0 times ;e ha e some data members in a class ;hose alues should remain unaltered after the0 are initialiPed. :o create such members ;e can use the const Ee0;ord in front of their declaration and such members are called const members. 7ut the0 must be initialiPed usin, initialiPers. For e+ample class circle > int rad; const float pi; OO :his is in alid ?; Tather the class should ha e a constructor to initialiPe pi usin, initialiPers. class circle > int rad; const float pi; OO :his is in alid public< circle %int r) < pie %B.2C) > rad!r; ?

?; Co'$ Mem6e" F&') io'23 if ;e ;ant that a f n that should not be allo;ed tochan,e alue of class member than ;e maEe them const. class circle > int r; float a; public< oid ,et %int +) > r!+; ? oid cal[area % ) > a!r M r M B.2C; ? oid sho; % ) const > count << Tad! <<r << .t 9rea! <<a; ? if const is there then alue of r ;ill not be chan,ed other ;ise at last it ;ill be incremented.

INITIALI+ERS
I'i(liBe"$ It is a special s0nta+ allotted b0 #$$ used to initialiPe there thin, . 2. const data members ;ith in the class. 5. reference ariables B. callin, parameteriPed constructor of the base class from deri ed class. :he0 are al;a0s ;ritten in front of the constructors Orders of initialiPes must be same as that of the order of data members

class 6ata > int +' 0; public< 6ata %int I' int j)< +%i)' 0%j) > ? 6ata %int I' int j)< +%i$j)' 0%+$i) > ? ?; Ist case 6ata 6%Q'2K) Y!Q 1!2K 6ata 6%S'2C) Y!52 1!54 PASSIN* OBEJCTS USIN* POINTER class 7o+ > int l' b' h; public< oid ,et% ) > OO same as pre ious ? int compare %7o+ M); ?; int 7o+ < < compare %7o+ Mp) > int +' 0; +! lMbMh; 0!- lM pbM ph; if %+! ! 0) return %K);

if %+>0) return %2); else return %=2); ? oid main% ) > 7o+ 72' 75; 72. ,et% ); 75. ,et% ); 72. sho;% ); 75. sho;% ); int ans ; ans ! 72. compare %(75); if %ans! !K) cout<< both are eGual ; else if %ans!!2) cout<<b2 is ,reater than b5; else cout<<b5 is ,reat0er than b2; ? P($$i'- O6Ce) $ 6! Re5e"e')e U$i'- Re5e"e')e 4("i(6le class 7o+ > int l' b' h; public< oid ,et% ) > OO same as pre ious; ? oid sho;% ) > OO same as pre ious; ? int compare %7o+ (); ?; int 7o+ < < compare %const 7o+ (-) >

int +' 0; + ! lMbMh; 0 ! p.lMp.bMp.h; if %+!!0) return %K); else if %+ > 0) return %2); else return %=2); ? oid main% ) > 7o+ 72' 75; 72.,et% ); 75.,et% ); 72.sho;% ); 75.sho;% ); int ans; ans!72. compare %75); if %ans! !K) cout<< both are eGual ; else if %ans!!2) cout<<b2 is ,reater than b5; else cout<<b5 is ,reat0er than b2; ?

FRIEND FUNCTIONS
9 friend function is a special function ;hich despite of not bein, member f n of class has full access to the pri ate' protected members of the class.

ATTRIBUTES OF FRIEND FUNCTIONS


2. if a Function is to be made friend of a class then it has to be declared ;ithin the bod0 of the class preceded ;ith the Ee0;ord friend.

5. ;hene er a friend f n is defined neither' the name of class nor scope resolution operator appears in its definition. Uoreour the Ee0;ord friend also does not appear. B. ;hene er a friend fn is called' neither the name of the object nor dot operator appears to;ard its left. It ma0 ho;e er accept Z the object as a C. Q. R. parameter ;hose members it ;ants to access. S. It does not matter in ;hich diction of class ;e declare a friend function as ;e can al;a0s access it from an0 portion of pro,ram 4. if a friend fn ;ant to manipulate the alues of data members of an object it eds the reference of object to be passed as parameter E1(mple23 OO 6emonstratin, the use of friend function class student > int roll; char ,rade; float per; public< oid ,et% ); friend oid sho; %student); ?; oid student < < ,et% ) > cout << enter roll. @rade ( per; cin >> roll>> ,rade>>per; ? oid sho; %student -) > cout << p.roll<< << p.,rade<< <<-.per; ? oid main% ) > student S; S. ,et% ); sho;%S); ?

Demo'$ "( i'- #e &$e o5 5"ie'0 5&') io' class student > int roll; char ,rade; float per; public< friend oid ,et %student (); oid sho;% ); ?; oid ,et %student ( -) > cout << enter roll' ,rade ( per; cin >> -.roll >> -.,rade >> -.per; ? oid student < < sho;% ) > cout << roll << ,rade << per; ? oid main% ) > Student S; oid ,et%S); s. sho;% ); ? class student > int roll; char ,rade; float per; public< friend oid ,et %student M-); oid sho;% ); ?; oid ,et %student MG) > cout << enter roll' ,rade ( per; cin >>G roll >> G ,rade >> G per;

? oid student < < sho; % ) > cout << roll << ,rade << per; ? oid main% ) > Student s; @et %(s); s.sho;% ); ? A FUNCTION BEIN* FRIEND OF T,O CLASSES class 7eta; OO for;ard declaration class 9lpha > int +; public< oid ,et% ) > cout << enter +!; cin >> +; ? friend oid compare %9lpha' 7eta); ?; class 7eta > int 0; public< oid set% ) > cout << enter 0!; cin >>0; ? friend oid compare %9lpha' 7eta); ? oid compare %9lpha 9' 7eta 7) >

if %9' Y > 7. 1) cout << ,reater! << 9' Y; else if %7.1> 9.Y) cout << @reater! << 7.1; else cout << eGual; ? oid main% ) > 9lpha Obj2; 7eta Obj5; Obj2. ,et% ); Obj5. set% ); #ompare %obj2' obj5); ?
ADDIN* T,O OBJECTS OF A CLASS USIN* MEMEBR FUCNTIONS

class 6istance > int feet; int in cher; public< oid ,et% ) > cout << enter feet ( inches; cin >> feet >> inches; ? 6istance add %6istance () oid sho;% ) > cout << feet! << feet<< inches! <<inches; ? ?; 6istance 6istance < < add %6istance (-) > 6istance temp; :emp. feet ! feet $-. feet; :emp.inches! inches $ -.inches; if %temp. inches>!25)

> temp. feer $! temp. inchesO25; temp. inches & !25 ? Teturn %temp); ? oid main% ) > 6istance 62' 65' 6B; 62. ,et% ); 65' ,et% ); 6B ! 62. add %d5); 6B. sho;% ); ? class 6istance > int feet' inches; public< oid ,et% K > OO same as pre ious ? oid add %distance (' distance (); oid sho;% ) > OO same as pre ious; ? ?; oid distance < < add %distance (d2' distance (d5) > Feet ! d2. feet $ d5' feet; Inches ! d2. inches $ d5' inches if %inches >25) > Feet ! feet $ inches O25; Inches & ! 25; ? ? oid main% )

> 6istance d2' d5' dB; d2.,et% );' d5.,et% ); 6B' add %d2' d5); 6B. sho;% ); ?

ADDIN* T,O AF CLASS UISN* PRIED FUNCTION class distance > int feet; int inches; public< oid ,et% ) > oid << enter feet ( inches; cin >>feet >> inches; ? oid sho;% ) > OOsame ? friend distance add %distance' distance )< ?; distance add %distance -' distance A) > distance temp; temp. feet ! -.feet $A.feet; temp. inches! -.inches $ A.inches; if %temp. inches>!25) > temp.feet $! temp. inchesO25; temp. inches & ! 25; ? return %temp); ? oid main% ) >

distance 62' 65' 6B; 62.,et% ); 65.,et% ); 6B ! add %62' 65) 6B.sho;% ); ?

OPERATOR O4ERLOADIN*
It is a mechanism usin, ;hich a pro,rammer can maEe built in operator of #$$ act on objects of user defined classes much in the same ;a0 liEe the0 act on ariables of primiti e data t0pe. :hus ;e can sa0 b0 usin, operator o erloadin, a pro,rammer can enhance the ;orEin, ran,e of built in operator from primiti e t0pe to non primiti e t0pe also. :he major ad anta,e offered b0 operator o erloadin, is the simplicit0 in readabilit0 of the call i.e. f n call ;hich are ,i en usin, operator o erloadin, are much more eas0 to interpret as compared to con entional function calls. Operator O erloadin, can be done 2. UaEin, use of member function 5. maEin, use of friend function. S!' (123 <ret=t0pe> operator <op=s0mbol> %ar,uments); friend %ret=t0pe> operator <op=s0mbol> %<ar,uments>); O erloadin, Of /nar0 Operator 9s Uember Function Of :he class %-re Increment) class counter > int count; public< counter% ) > count !K;

? counter %int c) > count ! c ? oid operator $$% ); oid sho;% ) > cout << count <<end2; ? ?; oid counter < < operator $$ % ) > $$ count; ? oid main% ) > counter a ! 2K; OO Sin,le parameteriPe constractor a.sho;% ); $$ a; OO a. operator $ $% ); a. sho;% ); ? class #ounter > int count; public< #ounter% ) > #ount ! K; ? #ounter %int c) > count ! c; ? #ounter operator $$ % ); oid sho;% ) > cout << count; ?

?; #ounter ( Or #ounter #ounter < < operator $$ % ) > #ounter temp; $$ count; or temp. count ! count; $$ count return %temp); return %M this); ? oid main% ) > #ounter c2 ! 2K' c5; #2. sho;% ); #5 ! $$ c2; #2. sho;% ); #5. sho; % ); ? O erloadin, Of -ost Increment Operator /sin, Uember Function Of this class class #ounter > int count; public< #ounter% ) > count!K; ? #ounter%int #) > count ! c; ? #ounter operator $$ %int); oid sho;% ) > cout << count; ? ?; #ounter #ounter < < operator $$ %int)

> #ounter temp; :emp. count ! count$$; return %temp); ? oid main% ) > #ounter c2 ! 2K' c5; #5 ! c2$$; #2. sho;% ); #5. sho;% ); ? O erloadin, /nar0 Operator 9s friend Of :he class class counter > int count; public< counter% K > count!K; ? counter %int i) > count ! I; ? oid sho;% ) > cout << count << end2; ? friend oid operator $$ %counter (); ?; oid operator $$ %counter (#) > $$ c.count return %#); ? Or counter temp; temp. count ! c.count$$; return %temp);

oid main % ) > counter #2 ! 2K' #5; #2. sho; % ); #5. ! $$#5; #2. sho; % ); #5. sho;% ); ? No e23 ;hen unar0 operators are o erloadin, usin, member function then donFt accept an0 ar,ument but ;hen the0 are o erloaded usin, friend fn then the0 ha e one ar,ument of t0pe object %class). class counter > int count; public< friend counter operator $$ %counter (); counter > count !K; ? counter %int i) > count ! i; > oid sho;% ) > cout << count << end2; ? ?; counter operator $$%counter (c) > counter temp; temp.count!$$c.ount; return%temp); ?

oid main%) > counter c2!2K'c5; c2.sho;%); c5!$$c2; c2.sho;%); c5.sho;%); ,etch%); ? O/e"lo(0i'- Bi'("! Ope"( o"$ A$ Mem6e" F&') io'$ O5 T#e )l($$ 6B ! 62 $ 65; 6B ! 62. operator $ %65); class 6istance > int feet' inches; public< oid ,et% ) > #ount << enter feet and inches; cin >> feet >> inches; ? oid sho;% ) > cout << feet << inches; ? 6istance operator $ %6istance); ?; 6istance 6isttacne < < operator $ %6istance -) > 6istance t; t.feet ! feet $ -. feet t. inches ! inches $ -. inches; if %t.inches>! O25) > t.feet $ ! t.inchesO25;

t.inches & ! 25; ? Teturn %t); ? oid main % ) > 6istance 62' 65' 6B; 62' ,et% ); 65' ,et% ); 6B ! 62$65; 6B. sho;% ); @etch% ); ? O/e"lo(0i'- Bi'("! Ope"( o" U$i'- 5"ie'0 F&') io' class 6istance > int feet' inches; public< oid ,et% ) > cout << enter feet and inches< cin >> feet>> inches; ? oid sho;% ) > cout << feet<< inches; ? friend 6istance operator $ %6istance' 6istance); ?; 6istance Operator $ %6istance p' 6istance A) > 6istance t; t.feet ! -.feet $A.feet; t.inches ! -.inches$ A.inches; if %t. feet>!25) > t.feet ! t.feet $t.inchesO25; t.inches & ! 25;

? Teturn %t); ? oid main % ) > 6istance 62' 65' 6B; 62.,et% ); 65.,et% ); 6B!62$d5; 6B.sho;% ); ? A$$i-'me' 23 65 ! 62$n 6B ! n $ 62 class 6istance > int feet' inches; public< oid ,et% ) > OO same as pre ious ? oid sho;% ) > OO same as pre ious ? 6istance 6istance < < operator $ %int n) > 6istance temp; :emp feet ! feet $ n; :emp. inches ! inches $ n; if %temp. inches > ! 25) > :emp. feet $ ! temp. inches O 25; :emp. inches & ! 25; ? Teturn %temp); ?

6istance operator $ %int -' 6istance A) > 6istance temp; :emp.feet ! -$A.feet; :emp. inches! -$A. inches; if %temp. inches> ! 25) > :emp.feet ! temp. feet $ temp. inchesO25; :emp. inches & ! 25; ? Teturn %temp); ? oid main% ) > 6istance 62' 65' 6B; int n; cout << enter an inte,er; cin >> n; 62. ,et % ); I 65 ! 62$n; OO can be done usin, member fn ( friend fn 65. sho;% ); cout << *nter an inte,er; cin >>n; 6B ! n$62; OO not possible throu,h member fn 6B. sho;% );

II ?

No e23 II can not be done usin, member function becoP n is an inte,er and onl0 an object can call function not inte,er. So I call can be made usin, member function as ;ell as friend function but II can be done onl0 friend function A$$i-'me' 23 62$!65 usin, member fn ( friend fn

O erloadin, Telational Operators if %62! ! 65) #ompiler if %62.operator ! ! %65) )

class 6istance > int feet' inches; public< oid ,et% ) > cout << enter feet ( inches; cin >> feet >> inches; ? oid sho;% ) > cout << feet << << inches; ? int operator ! ! %distance 6); ?; int 6istance < < operator ! ! %6istance 6) > int +' 0; Y! feet (25 $ inches; 1 ! 6. feet M25 $ 6.inches; if %+! ! 0) Teturn %2); else Teturn %K); ? oid main% K > 6istance 62' 65; 62. ,et% ); 65. ,et% ); 62. sho;% ); 65.sho;% ); if %62! ! 65) cout << eGual; else cout << not eGual; ? A$$i-'me' 23

Uodif0 the abo e pro,ram so that no; 0our cosle prents either of there messa,e i. Object are eGual. ii. 6l is ,reater. iii. 65 is ,reater U$e mi'im&m po$$i6le ope"( o" O erloadin, 7inar0 Operator On strin, class strin, > char strJ5KL; public< strin, % ) > strJKL ! H.KF; ? strin, %char M-); > strcp0 %str' -); ? oid sho;% ) > cout << str; ? strin, operator $ %strin, S) ?; strin, strin, < < operator $ %strin, S) > strin, t; int i' j; for %i!K; strJiL; i$$) t.strJiL ! strJiL; for %j!K; s.strJjL; i$$' j$$) t.strJiL ! s.strJjL; return %t); ? oid main% ) >

strin, s2! Hello; strin, s5 ! Ho; are 0ou ]; strin, sB; sB ! s2 $s5; s2. sho;% ); s5. sho;% ); sB. sho;% ); ? A$$i-'me' 23 D9- ;hich compares t;o strin, objects ( checEs ;hich one is ,reater. Ope"( o"$ ,#i)# C(' No Be O/e"lo(0e0 2> .%dot operator) member access operator %alread0 o erloaded) 5> << %scope resolution operator) it alread0 ;orEs on classes ;e o erload onl0 those operators ;hich ;orEs on primitine and not on non prin B> ]< %conditional Operator) It reGuires there ar,uments o erloadin, of operators atmost can taEe 5 ar,ument C> M. -ointer to member operator Q> SiPe of operator

DYNAMIC MEMORY ALLOCATION (DMA)


MALLOC 2. It is a function 5. "ecessar0 to include the header file B. It taEes no' of b0tes as parameter C. brin,s memor0 from local heap Q. Ua+imum memor0 that malloc can allocate ! RCN7 R. Ualloc retirens the address of 9llocate blocE in from of % oidM) :hus its return alue has to be t0pe #asted accordin,l0 NE, It is a operator header file not reGuired It taEes no. of elements TeGuired as parameter brin, has no such memor0 store "e; has no such memor0 limitation "e; automaticall0 con erts accordin, to the datat0pe ,i en thus no need to e+plicitl0 t0pe cast its return alue.

S. ;hen malloc fails it returns null ;hen ne; fails it returns Pero 4. Ualloc onl0 creates a ne; blocE on the other hand operator ne; 7ut not call the constructor of the can allocate memor0 as ;ell as class for initialiPed the data member call the class for initialiPin, the Of that blocE members of blocE created. Such #onstructors are called d0namic #onstructors.

S!' (1 5o" 'e.73 %i) %ii) ne; <data Z t0pe> ne; <data=t0pe> JintL;

Allo)( io'$ O5 Ne. 23 2. int M -; -! ne; int %2K); cout << M-; delete -; ne; allo;s pro,rammer to initialiPe the memor0 allocated but malloc does not pro ide na0 such feature

5KKK 5. int M-; -!ne; int J2KL; delete J L -; BKKK S!' (1 5o" 0ele e .. BKKK 5KKK

2K 5KK5

Here alue 2K denotes that pro,rammer is interested in creatin, memor0 for elements

2. 5. *,<=

delete <ptr=name>; delete J L <ptr=name>; float M-; delete -;

OO deletes one blocE of data t0pe OO deletes ;hole allocated memor0

OO four b0tes free

6elete is a reGuest to OS it does not ;orE immediatel0 ;here as ne; creates memor0 immediatel0 D9- ;hich creates a d0namic arra0 of user defined siPe 9ccept alues from user in that arra0 ( then find lar,est element in that arra0 alon, ;ith its position. Finall0 it should displa0 the lar,est element ( delete the arra0. oid main % ) > int n; cout << Ho; man0 inte,ers; cin >> n; int Mp; p! ne; int JnL; if %p! ! K) > cout << Insufficient memor0; ,etch% ); e+it%2); ? for %int i!K; i<n; i$$) > cout << enter element; cin >> M %p$i); ? int ma+ ! Mp; int pos ! K; for %i!2; i<n; i$$) > if %M%p$i) > ma+) > ma+ ! M%p$i); pos ! i; ?

? cout << lar,est element! << ma+; cout << -osition ! << pos; ,etch% ); delete J L p; ? D9- to create a class cOa strin, ha in, a character pointer -. pro ide constructor in the class ;hich accept int as parameter and allocates d0namic arra0 of characters of special siPe. "o; pro ide follo;in, member fn in the class. 2. ,et strin, ;hich prompts users to enter strin, in d0namic arra0. 5. sho; strin, ;hich displa0 the strin, B. Te erse strin, ;hich accept an object as parameter and copies the Te erse of strin, stored in callin, object in object -assed as parameter. class strin, > char Mp; int n; public < strin, %int); strin, % ); oid sho;str% ); oid re ersestr % strin, (); oid ,etstr% ); ?; strin, < < strin, %int siPe) > p ! ne; char JsiPe $2L; if %p! !K) e+it %2); n ! siPe $2; ? oid strin, < < ,etstr% ) > cout << enter strin,; cin. ,etline %p'n);

? oid strin, < < re ersestr %strin, (s) > int i' j; for %i!K' j!strlen %p)=2;j>!K; j==' i$$) > s.pJiL ! pJjL; ? s. pJiL ! H.KF; ? oid strin, < < sho;str% ) > cout << p << end2; ? strin, < < W strin, % ) > delete J Lp; cout << 9rra0 destro0ed; ? oid main % ) > int n; cout << Ho; ma0 character; cin >> n strin, S2 !n; strin, S5 !n; S2. ,etstr % ); S2. re erse str%S5); S2. sho; str% ); S5. sho; str% ); ?

DYNAMIC OBJECTS
Allo)( i'- memo"! 5o" )l($$ .i # #e #elp o5 'e.. class *mp > int a,e;

char nameJ5KL; float sal; public< oid ,et% ) > cout << enter a,e' name ( sal; cin >> a,e >> name >> sal; ? oid sho;% ) > cout << a,e << << name<< <<sal; ? ?; oid main% ) > *mp M-; -!ne; *mp%); if %-! !K) > cout << Uemor0 Insufficient; e+it %2); ? - ,et% ); - sho;% ); ,etch % ); delete p; ?

a,e name sal

ARRAY OF DYNAMIC OBJECTS


Uodif0 the pre ious code so that no; 0our pro,ram creates an arra0 of a objects ;here n is ,i en b0 user. :hen it should accept alues for each object and finall0 displa0 them.

class *mp > int a,e; char nameJ5KL; float sal; oid ,et% ) > cout << enter are' name and sal; cin >> a,e>> name>> sal; ? oid sho;% ) > cout <<a,e<< name<<sal<<end2; ? ?; oid main% ) > *mp Mp; int i' n; cout << ho; man0 emplo0ees]; cin >> n; p!ne; *mpJnL; if % p ! !K) > cout << error in cratin, objects; e+it %2); ? for %i!K; i<n; i$$) %p$i) ,et% ); or for %i!K; i<n; i$$) %p$i) sho;% ); or ,etch% ); deleteJ Lp; ?

pJiL. ,et% ); pJiL. sho;% );

*nhance the abo e pro,ram so that after acceptin, records of n emplo0ees. 1our pro,ram prompts the user to enter another name ( displa0 the record of that emplo0ee onl0. if emplo0ee name is not a ailable then pro,ram should displa0 the messa,e record not found.

class *mp > int a,e; char name J5KL; float sal; public< oid ,et% ) > cout << enter a,e' name and sal; cin >> a,e>> name>> sal; ? oid sho;% ) > cout << a,e<< name << sal; ? int compare %char M); ?; oid main % ) > *mp Mp; int n; cout << ho; man0 emplo0ees]; cin >> n; -! ne; emp JnL; if %p ! !K) > cout << Insufficient Uemor0; e+it %2); ? for %i!K; i<n; i$$K %p$i) ,et% ); or pJiL. ,et% ); cout << enter name to search; char str J5KL; cin. i,nore% ); cin.,etline %str' 5K); for %i!K; i<n; i$$) > if % %p$i) compare %str) ! ! K)

> %p$i) sho; % ); breaE; ? ? if %i ! ! n) cout << Tecord not found; ,etch % ); delete J L p; ? int compare %char Mp) > return %strcmp % name.p) ); ?

DYNAMIC COSNTRUCTORS
class *mp > int a,e; char a,e; char name J5KL; float sal; public; *mp% ) > cout << enter a,e' name and sal; cin >> a,e >> name >> sal; ? *mp %int I' char Mj ' float E) > 9,e ! I; Strcp0 %name' j); Sal ! E; ? oid sho;% ) > cout << a,e << name << sal; ? W*mp% )

> cout << Object destro0ed; ? ?; oid main % ) > *mp M-' MG; -!ne; *mp; A!ne; *mp %BK' ineet' 5KKKKK); p sho;% ); G sho;% ); delete G; delete p; ? No e2= :he abo e -ro,ram ;ill not call the destructor of the class e en at the termination. :his is because in #$$ memor0 ;hich is allocated usin, ne; can onl0 be deal located usin, delete and callin, of destructor is onl0 made ;hen memor0 ,ets deallocated. Since in abo e code' call for delete is not present so memor0 blocE still remains in T9U ( mi,ht be collected in future throu,h ,arba,e collection. :hus if memor0 is freed for a d0namic object it can onl0 be done throu,h delete operator.

INHERITANCE
1. Si'-le I'#e"i (')e 9 7ase class %. M&l i le/el I'#e"i (')e 9 indirect base class of #

6eri ed class

base class of #

c B. M&l iple I'#e"i (')e 9 # 7 7 D. Hie"(")#i(l I'#e"i (')e 9 #

E. H!6"i0 I'#e"i (')e o" M&l ip( # I'#e"i (')e 9 7 #

6 S!' (1 5o" I'#e"i (')e<= class <class Zname>< public O pri ate O protected < clas=name> 6eri ed class Uode of Inheritance class 7o+ > int l' b' h; public< oid ,et% ) > cout << enter l' band; cin >> l>>b>>h; ? oid sho;% ) > cout <<l<< << b<< << h; 7ase class

? ?; class carton < public 7o+ > char t0peJ5KL; public< oid set% ) > cout << enter material name; cin.,etline %t0pe' 5K); ? oid displa0 % ) > cout << material ! << t0pe; ? ?; oid main% ) > carton obj; obj. ,et% ); obj. set% ); obj. sho;% ); obj. displa0% ); ? A))e$$(6ili ! R&le$ ,#e' Mo0e O5 I'#e"i (')e I$ p&6li) Dhen a base class is inheritance in public mode then <= 2. 9ll the public members of base class become public members of deri ed class i.e. the0 can be accessed throu,h the function of deri ed class as ;ell as b0 objects of deri ed class. 5. 9ll the protected members of base class become protected members of deri e class ( thus can onl0 be accessed throu,h functions of deri ed class but not b0 the object %main) of deri ed class. B. 9ll pri ate members of base remain pri ate to their o;n class ( thus can neither be accessed throu,h functions of deri e class nor b0 object of deri e class. EARLY BINDIN*23

It is a prours ;hich is e+ecuted durin, compilation in ;hich compiler binar0 the fn bod0 ;ith the fn call i.e. e en before pro,ram starts e+ecutin, decision re,ardin, the fn call and fn bod0 to be e+ecuted are taEen b0 the compiler since this happens before e+ecution' ;e can sa0 it is earl0 bindin,. *arl0 bindin, is al;a0s an action until ( unless Ee0;ord irtual is used infront of the fn return t0pe. It is done on the basis of there criterias<= %i) %ii) %iii) function name or callin, object t0pe or function parameter t0pe in other ;ords earl0 bindin, is al;a0s in action in normal fn calls' o erloaded fn calls and o erloaded operators :he major benefit of earl0 bindin, is speed of e+ecution i.e. function calls ;hich are bound usin, earl0 bindin, ,et e+ecuted at a fastest speed as compared to late bindin, fn calls. O4ERRIDIN* :he function o erridin, is a term ;hich is used ;hen a deri e class contains a function ;ith the same protot0pe as its bass class. In other ;ords' fn pro ided b0 base class has same protot0pe in deri e class but in different bod0. O/e""i0i'Scope must be different 70 the classes related b0 Inheritance -rotot0pe of functions Uust be same . O/e"lo(0i'al;a0s in same class means at sin,le le el protot0pe must be different

,#e' Mo0e O5 I'#e"i (')e I$ P"o e) e0 Dhen base class is inheritance in protected mode then<= 2. 9ll public members of base class becomes protected member of deri e class i.e. the0 can be accessed onl0 throu,h function of deri ed class but not b0 object of deri e class.

5. 9ll protected members of base class become protected members of deri e class i.e. the0 t;o can onl0 be accessed throu,h functions of deri ed class but not b0 object of deri e class. B. 9ll pri ate members of base class remains pri ate to their o;n class ( thus neither accessible throu,h the object nor throu,h functions of deri e class. class "um > protected< int a' b; public< oid ,et% ) > cout << enter t;o numbers; cin >> a >> b; ? oid sho;% ) > cout << "umbers are !; cout <<a << << b; ? ?; class 9dd"um < protected "um > -rotected < int c; public< oid set% ) > ,et% ); ? oid add% ) > c!a$b; ? oid displa0% ) > sho;% ); cout << sum! <<c;

? ?; oid main % ) > 9dd"um obj; obj. set% ); obj.add% ); obj. displa0% ); ?

PRI4ATE MODE OF INHERITANCE


Dhen a base class is inheritance in pri ate mode then<= 2. 9ll the public members of base class become pri ate members of deri e class i.e. the0 can be onl0 accessed throu,h fn of deri e class but not b0 the objects of deri e class. 5. 9ll the protected members of base become pri ate members of deri e class i.e. the0 t;o can onl0 be accessed throu,h the function of deri e class but not b0 objects of deri e class. B. 9ll pri ate members of base class remain pri ate to their o;n class ( thus can neither be accessed b0 fn nor b0 objects of deri es class. class "um > protected < int a' b; public< oid ,et% ) > cout << enter a and b; cin >> a >> b; ? oid sho;% ) > cout << a ! <<a<<end2; cout << b! << b<< end2; ? ?;

class 9dd"um< pri ate "um > protected < int c; public< oid set% ) > ,et% ); ? oid add% ) > c!a$b; ? oid displa0 % ) > sho;% ); cout << sum ! <<c; ? ?; oid main% ) > 9dd"um Obj; Obj.set% ); Obj. add% ); Obj. displa0% ); ? No e2= 9t sin,le le el Inheritance pri ate ( protected inheritance seems to be similar.

MULTILE4EL INHERITANCE
class "um > protected< int a' b; public< oid ,et% ) > cout << enter a nad b<

cin >> a >> b; ? oid sho;% ) > cout << a! <<a<<end2; cout << b! <<b<<end2; ? ?; class 9dd"um < public "um > protected < int c; public < oid set% ) > ,et% ); ? oid displa0% ) > sho;% ); cout << sum! <<c; ? oid add% ) > c!a$b; ? ?; class 6iff"um < public 9dd"um > int d; public< oid accept% ) > set% ); ? oid diff% ) > d! a Z b; ?

oid print% ) > displa0 % ); cout << 6ifference! <<d; ? ?; oid main% ) > 6iff"um obj; obj. accept% ); obj. add% ); obj. diff% ); obj. print% ); ? P"o-"(m class counter > protected< int count; public< oid init %int a) > count !a; ? oid operator $$% ) > count $$; ? oid sho;% ) > cout << count! <<count; ? ?; class 6ec#ounter < public counter > public< oid operator = =% ) >

= = count; ? ?; oid main% ) > 6eccounter 6; 6.int%2K); 6.sho;% ); $$6; 6.sho;% ); = = 6; 6. sho;% ); ? A$$i-'me' 23 #reate a class cOa arra0 ;hich contains an inte,er arra0 of siPe 2K. :he class should ha e t;o member functions called ,et arr and sho;arr' ;hich should accept alues in the arra0 ( displa0 its alues respecti el0. "o; create a deri e class of arra0 cOa sortarr' the class should accept a strin, as parameter if strin, contains HascF then sortin, should be done in ascendin, order ( if it contains desc sortin, should be done in descendin, order. Finall0 create the function main ;hich should contain menu dri e interface for the user ha in, Q options<= %i) %ii) %iii) %i ) % ) input displa0 sort in ascendin, sort in descendin, Guit

Sol& io' #include <iostream.h> #include <stdlib.h> class 9rra0 > protected< int aJQL; public< oid ,et% ); oid displa0% );

?; oid 9rra0 < < ,et% ) > int i; cout << enter arra0 elements; for %i!K; i<Q; i$$) cin >>aJiL; ? oid 9rra0 < < displa0 % ) > for %int i!K; i<Q; i$$) cout << .n elements are ! << aJiL; ? class sortarr < public 9rra0 > public< oid ascsort% ); oid descsort% ); ?; oid sortarr < < ascsort % ) > int i' j' t; for %i!K; i<Q; i$$) > for %j!K; j<C; j$$) > if %a JjL > a Jj$2L) > t ! a JjL; a JjL ! a Jj$2L; a Jj$2L ! t; ? ? ? ? oid sortarr < < descsort% ) > int i' j' t; for %i!K; i<Q; i$$)

> for %j!K; j<C; j$$) > if %aJjL <a Jj$2L) > t!aJjL; aJjL!aJj$2L aJj$2L ! t; ? ? ? ? oid main% ) > clrscr% ); sortarr sr; int ch!K; do > cout << .n .t *nter %2) for Input data; cout << .n .t *nter %5) for 6ispla0 6ata; cout << .n .t *nter %B) sort in 9scendin, order; cout << .n .t *nter %C) sort in 6escendin, order; cout << .n .t *nter %Q) for Guit; cout << enter choice; cin >> ch; clrscr% ); s;itch %ch) > case 2< sr.,et% ); breaE; case 5< sr.displa0% ); breaE; case B< sr.ascsort% ); breaE; case C< sr.descsort% );

breaE; case Q< e+it%2) ? ? ;hile %ch V!Q) ,etch% ); ?

MULTIPLE INHERITANCE
class base2 > protected< int a; public< oid ,et% ) > cout << enter a !; cin >>a; ? oid sho;% ) > cout <<a << end2; ? ?; class base5 > protected< int b; public< oid set% ) > cout << enter b!; cin >> b; ? oid displa0% ) > cout <<b << end2; ?

?; class dr < public base2' public base5 > int c; public < oid accept % ) > ,et% ); set% ); ? oid add % ) > c ! a$b; ? oid print% ) > sho;% ); displa0% ); cout << sem ! <<c; ? ?; oid main% ) > dr obj; obj. accept% ); obj. add% ); obj. print% ); ? P"o-"(m 23 7ase ( deri e ha in, the function ;ith same name ( ar,uments. class base2 > protected< int a; public< oid ,et% ) >

cout << enter a!; cin >>a; ? oid sho;% ) > cout << a << end2; ? ?; class base5 > protected< int b; public< oid set% ) > cout << enter b!; cin >> b; ? oid sho;% ) > cout <<b<<end2; ? ?; class dr < public base2' public base5 > int c; public< oid accept% ) > ,et% ); set% ); ? oid add% ) > c! a$b; ? oid print% ) > Dill sho; sho;% ); base2< < sho;% );

*rror ambi,uit0 error ? ?; oid main% ) > 6r obj; obj. accept% ); obj. add% ); obj. print% ); ?

base5< < sho;% );

Role O5 Co'$ "&) o" 8 De$ "&) o" I' I'#e"i (')e 9s a basic rule in inheritance' it a base class contains a constructor and destructor as ;ell as deri e class also contains constructor ( destructor' then ;hen object of deri e class is created' constructor of base class ,ets e+ecuted first follo;ed b0 constructor of deri e class and the destructor is called in re erse order i.e. the destructor of deri e class is called first follo;ed b0 the destructor of base class. :hus ;e can sa0 constructor are al;a0s called in the order of inheritance and destructor are called in re erse order. class 7ase > public < 7ase % ) > cout << In baseFs constructor <<end2; ? F7ase% ) > cout << In baseFs destructor <<end2; ? ?; class dr < public 7ase > public<

dr % ) > cout << In deri eFs const <<end2; ? Wdr % ) > cout << In deri es destructor <<end2< ? ?; oid main% ) > > dr obj; ? ,etch% ); ? PARAMETERIES CONSTRUCTOR class 7ase > -rotected< int a' b; public< 7ase %int I' int j) > a ! I; b ! j; ? oid sho;% ) > cout << a << << b; ? ?; class dr < public base > int c; public< dr % )< 7ase %2K' 5K)

> c!a$b; ? oid sho;% ) > 7ase < < sho;% ); cout << sum ! << c; ? ?; oid main% ) > dr obj2 dr obj5 obj2. sho;% ); obj5. sho;% ); ?

Co'$ "&) o" C(lli'- I' M&l iple I'#e"i (')e 7ase 2 int a; 7ase2 %int); oid sho;% ); class 7ase2 > protected< int a; public< 7ase %int i) > a ! i; ? oid sho;% ) > base5 int b; base5 %int); oid displa0%); dr int c;

cout << a; ? ?; class 7ase5 > protected < int b; public< 7ase5 %int j) > b ! j; ? oid displa0% ) > cout << b; ? ?; class dr < public 7ase2' public 7ase5 > protected < int c; public< dr %int p' int G) < 7ase2 %p)' 7ase5%G) > c!a$b; ? oid print % ) > sho; % ); displa0% ); cout << their sum ! << c; ? ?; oid main% ) > dr obj2 %2K' 5K); dr obj5 %5K' SK); obj2. print % ); obj5. print% );

? No e 23 if the constructor of base class is parameteriPed then %i) %ii) %iii) deri e class must ha e constructor 7ase class constructor should be called in deri es constructor.

Co'$ "&) o" C(lli'- I' M&l ile/el I'#e"i (')e class 7ase2 > protected< int a ; public< 7ase2%int i) > a!i; ? oid sho;% ) > cout << a << end2; ? ?; class 7ase5< public 7ase2 > protected< int b; public< 7ase5 %int i' int j)< 7ase2%i) > b!j; ? oid displa0% ) > cout << b << end2; ? ?; class dr < public 7ase2' public 7ase5

> protected< int c; public< dr %int +' int 0) < base5 %+' 0) > c!a$b; ? oid print % ) > sho;% ); displa0 % ); cout << their sum! << c; ? ?; oid main % ) > dr obj%2K' 5K); dr obj %QK' RK); obj2. print% ); obj5. print% ); ? No e #onstructors can not be inherited <= #onstructors are special member fn ;hich are e+clusi el0 used for initialin, pri ate data members of class. "o; since the pri ate data of class is not passed on to its deri e classes' so the functions ;hich e+plicitl0 initialiPe then %constructor) are not inherited. Same is the case ;ith destructor'

HIERARCHIAL INHERITANCE
class "um > protected < int a' b< public < "um %int i' int j) >

a ! i; b ! j; ? oid sho;% ) > cout << a ! << a; cout << b! << b; ? ?; class 9dd"um < public "um > int c; public< 9dd"um %int i' int j) < "um %i' j) > c!a$b; > oid sho;% ) > "um < < sho;% ); cout << sum ! <<c; ? ?; class 6iffnum < public "um > int d; public < 6iff"um %int +' int 0) < "um %+' 0) > d! a Z b; ? oid sho;% ) > "um < < sho;% ); cout << 6ifference ! << d; ? ?; oid main% ) >

9dd"um addobj %2K' 5K); 6iff"/m diffobj %BK' SK); addobj. sho;% ); diffobj. Sho;% ); ?

HYBRID INHERITANCE
class 7ase > public< int a; ?; class dr 2 < irtual public 7ase > public< int b; ?; class dr 5< irtual pubic 7ase > public< int c; ?; class dr B < public dr 2' public dr 5 > public< int d; ?; oid main% ) > dr B obj; obj. a !2K; obj. b ! 5K obj. c !BK; obj.d! obj a $ obj.b $ obj. c; cout << sum ! << obj'd; ?

*RANTIN* ACCESS
class 6ata > pri ate < int a; -rotected < int b; public < int c; ?; class dr < protected 6ata > public< 6ata < < # OO brin, # in public mode instead of protected ?; Fore,<= class 7anE > public < oid deposit% ); oid ;ithdra;% ); oid int=cal% ); ?; class sa in, Z acct< -ri ate 7anE > public < 7anE < < deposit; 7anE < < ;ith dra;; ?;

POLYMORPHISM
class 7ase > public<

oid sho;% ) > cout << In base H( sho;; ? ?; class dr < public 7ase > public < oid sho;% ) > cout << In dr Fs sho;; ? ?; oid main% ) > 7ase b' Mptr; dr d; ptr ! ( b; ptr sho;% ); ptr ! ( d; ptr sho;% ); ? 4IRTUAL FUNCTION 8 MULTILE4EL INHERITANCE class 7ase > public< irtual oid sho;% ) > cout << In baseFs sho;; ? ?; class dr 2 < public 7ase > public < oid sho;% ) > cout << In dr 2Fs sho;; ?

?; class dr 5< public dr 2 > public< oid sho;% ) > cout << In dr 5Fs sho;; ? ?; oid main% ) > 7ase M ptr' b; dr 2 d2; dr 5 d5; ptr ! ( b; ptr sho;% ); ptr ! ( d2; ptr sho;% ); ptr ! (d5; ptr sho;% ); ? No e 23 :op le el class ptr can access member of lo;er le el class. Iirtual is mandarot0 in base sho; as function is ori,inall0 from base. Iirtual functions are those functions for ;hich no decision re,ardin, the call and the definition to be e+ecuted is toEen b0 the compiler durin, compilation. In other ;ords' if a fn is preceded ;ith Ee0;ord irtual then if ne er become the past of earl0 bindin, ( compiler dela0s its bindin, until runtime. :hus all the decisions re,ardin, the call and the bod0 to be e+ecuted are taEen at runtime. :hese decisions are not based on the t0pe of caller %as ;as the case ;ith earl0 bindin,) but on the bases of contents of the caller. if the callin, pointer is storin, the address of base class object then baseFs ersion of irtual function ;ill be e+ecuted ( if it pointin, to an object of deri e class then deri e ersion of irtual fn is e+ecuted. 7ut to full0 uses the potential of irtual function the deri e class ;hile ,i in, its o;n bod0 Odefinition for irtual fn must Eeep its protot0pe same as the base class i.e. deri e should o erride the irtual function of base class if it ;ants to place its o;n definition of irtual function.

:his is because pointer of base class can access onl0 those function of deri e class ;hich are o erridden in the deri e class but not those ;hich are hidden or added b0 deri e class.

I' e"'(l ,o"Gi'- O5 4i" &(l F&') io' class 9 > int a; public< oid f2% ) > ? irtual oid f5% ) obj2 I-:T a > ? ?; class 7 < public 9 > int +; public< oid fB% ); oid f5% ); obj5 I-:T ?; oid main% )F > 9 obj2; 9 Mptr; ptr ! ( obj2; ptr f5% ); ptr ! ( obj5; ptr fB% ); siPe of class 9 ! C b0tes 5 b0tes for ariable a 5 b0tes for I-:T 4TABLE FOR A (9 < < f5% ) (9 < < fB% )

4TABLE FOR B (7 < < f5% ) (9 < fB% )

ptr fC% ); ? :his ;ill not be e+ecuted since this is not irtual ( compiler ;ill ,o to *arl0 bindin, table for base class 9 ;here there is no function fC. 4TABLE23 for e er0 class in #$$ ;hich contains at least one irtual function a special looE up table for storin, addresses of there irtual function is created ;hich is Eno;n as I:978* or irtual :able. :hus in short I:978* is a table containin, addresses of irtual functions of the class as ;ell as irtual function of base class if the0 are not o erridden. :his table is then consulted b0 the compiler ;hen a call for irtual function is encountered durin, runtime. 44PTR23 (4i" &(l /oi0 Poi' e") for e er0 class ;hich contains a irtual function special pointer is created b0 the compiler Eno;n as II-:T' ;hich is used for pointin, to the irtual table. :hus e er0 object of class containin, irtual function has its siPe incremented b05. "o; ;hene er compiler encounters call for irtual function throu,h a pointer' it first refers to the address of object to ;hich pointer is pointin, from their it reads the address contained in II-:T of the object the ;hich is the address of I:978* of class. 8astl0 ;ithin the I9:78* it e+ecutes the irtual function called. :hus irtual function enhances the siPe of code as reduces the e+ecution speed but pro ides a fle+ible ;a0 of desi,nin, pro,ram ;hich can respond to the chan,es ;hich accur at run time. class 6ata > int a ; 6ata %int ); public< static 6ata ,etObject% ); oid sho;% ); ?; 6ata < < 6ata %int i) > a ! i; ? 6ata 6ata < < ,etobject% ) > 6ata 6%2K); return %6);

? oid 6ata < < sho;% ) > cout << a; ? oid main% ) > 6ata 6 ! 6ata. ,etobject% ); 6. sho;% ); ? No e Dhen onl0 one object of class is created then that t0pe of class is cOa sin,le to n class. Pol!mo"p#i$m Compile Time Pol!mo"p#i$m 2. Function O erloadin, 5. Operator O erloadin, B. *arl0 7indin, R&' Time Pol!mo"p#i$m 2. Function O erridin, 5. Iirtual Function B. 8ate 7indin,

4i" &(l I'#e"i (')e

a oids multiple copies -ol0morphism %con erts earl0 bindin, to late bindin,)

class Fi,ure > protected< int dim2' dim5; public < oid ,et% ) > cout << enter 2st ( 5nd dimension; cin >> dim2>> dim5; ?

?; class Tectan,le < public Fi,ure > public< oid area% ) > cout << area of Tectan,le!; cout << dim2 M dim5; ? ?; class :rian,le < public Fi,ure > public< oid area% ) > cout << area ! <<FQ M dim2 Mdim5; ? ?; oid main% ) > Fi,ure Mp; Fi,ure F; p ! (F; p ,et% ); p area% ); Tectan,le T; p!(T; p ,et% ); p area% ); :rian,le :; p ! ( :; p ,et% ); p area% ); ?

PURE 4IRTAUL FUNCTIONS

6ef<= if a irtual functions declarations is eGuated ;ith Pero then it is Eno;n as pure irtual fn. In other ;ords' it ;e do not ;ant to pro ide an0 definition for a irtual fn ;ee can eGuate ;ith Pero then it ;ill be Eno;n as pure irtual fn. :hus b0 definition a pure irtual fn is one ;hich has no bod0 define ;ith in its o;n class or base class.

ABSTRACT CLASS
2. if a class contain at least one pure irtual fn than it is Eno;n as abstract 7ase class. 5. ;e can ne er create an0 object of abstract class but ;e can al;a0s create its pointers. :his is because ;hene er an object of a class containin, irtual function is created a I:978* is setup b0 the complete' ;hich stores the address of irtual function has no bod0 it can not ha e memor0 address ( thus it can not places in I:978*. So to pre ent an0 accidental calls to a non=e+istin, pure irtual function compiler prohibits the creation of an object of an abstract class. B. 9n class ;hich e+tends an 9bstract 7ase class must pro ide its o;n definition of pure irtual fn a ailable in its base class other ;ise the class itself ;ould be created as an abstract class ( then it too can not be instantiated. No e2= #onstructors can not be irtual since linE bet;een I-:T I:978* is made b0 constructor Iirtual 6estructor<= class 7ase > protected< public< int Mp; base% ) > p!ne; int J2KL; cout << p constructedV; ? irtual W base

> delete J L p; cout << memor0 deallocated; ? ?; class dr < public 7ase > int MG; public < dr % ) > G ! ne; int J2KL; cout << G constructed; ? Wdr % ) > delete J L G; cout << memor0 deallocated for G; ? ?; oid main% ) > 7ase Mptr; ptr ! ne; dr ; delete ptr; ? 6estructor can not be declared as pure irtual. Since it is not possible to lea e empt0 bod0 of destructor since at the time of call of destructor same acti it0 must be performed.

FILE H HANDLIN* (STREAM I<O)


Flo. o5 0( ( if flo; of data is from pro,ram to;ards de ice then oOp stream e,. cout . is used. if flo; of data is from de ice to pro,ram then iOp stream e, cin is used. Mo'i o" < B&55e" Mo'i o"

Input stream C++ P"o-"(m Input stream

output stream

output stream

H("030i$G Cl($$e$ A/(il(6le I' C++ 5o" File H('0li'-

H("0 0i$G

2. O5 S "e(m23 if a class ;hose objects can be created for ;ritin, data to secondar0 memor0 of file. 5. I5 S "e(m23 B. F$ "e(m 23 is a class ;hose objects can be created for readin, data from file. ;hose object can read O ;rite the data in a file.

Steap TeGuired for Dritin, 6ata In File S ep 1 #reate the object of Of stream class *,<= Of stream obj; S ep % #onnect the object ;ith file on 0our s0stem. S ep I ;rite the data throu,h the object in file. S ep D #lose the file. C++ Impleme' O5 A6o/e S ep$ S ep 1 S ep % S ep I %a) %a) %b) Of stream obj; obj. Open % 6ata. :+t); obj << Hello; obj. put %HHF);

S ep D

obj.close % ); static data File Openin, Uode

2 %a) Of stream Obj % 6ata' t+t); 5%a) Of stream obj; clas 7j.open %6ata. :+t' ios < < app) B Of stream obj % 6ata. :+t' ios < < app)

Step for #reatin, 9 -ro,ram for Teadin, 9 File 2. #reate the object of ifstream class. 5. #onnect the object ;ith the file on 0our s0stem ( checE ;hether file is a ailable or not. B. Tead the data throu,h object from file. C. class file. C++ IMPLEMENTATION 2. if stream obj 5. %a) Obj. Open % 6ata.t+t); Or if stream obj; Obj.open % 6ata. :+t' ios < < in); Or if stream obj %6ata.t+t' ios< < in); C"e( i'- O6Ce) O5 5$ "e(m )l($$ 2. fstream obj; Obj.open % 6ata.te+t' ios < < out ^ ios < < in); 5. /sin, #onstructor Fstream obj % 6ata.t+t' ios < < out ^ ios < < in); D9- to create a file cOa messa,e. te+t 9ccept a line of te+t from user ( ;rite it in file character b0 character #include <stdlib.h> #include <iostream.h> #include <fstream.h>

#include <conio.h> oid main % ) > Of stream out % Uessa,e. :e+t); if %Vout) > cout << file can not be opened; @etch % ); e+it%2); ? char strJ4KL; cout << enter a line of te+t; cin.Getline %str' 4K); int i!K; Dhile %strJiL) > Out.put %strJiL); I$$; ? cout << file ;ritten successfull0; @etch % ); Out. #lose% ); ? 2 "ote<= isopen % ) K 2 Fail% ) K Aue<= D9- to open the file created b0 the pre ious pro,ram. Tead it on character b0 character basic ( displa0 its contents on the screen. Sol& io' 23 oid main % ) > if stream in % messa,e.t+t); if %V in) Tetruns I if not connected Teturns 2 if conceted

> cout << filoe can not be opened; e+it%2); ? char ch; Dhile %V In.enf% ) ) > #h!in.,et% ); cout << ch; ? @etch% ); In.close% ); ? Aue<= D9- to open a file cOa 6ata.t+t. 9ccept a line of te+t from user ( ;rite it on file character b0 character basic and it in the same pro,ram read file and print its content on the screen . oid main% ) > Fstream "isha % 6ata' ios< < out ^ ios< < in); if %V "isha) > cout << error openin, file; e+it%2); ? char str J4KL; cout << enter a line of te+t; cin.,et line %str' 4K); int i!K; char ch; Dhile %str JiL) > #h!strJiL; Obj.put %ch); I$$; ? Obj.seeE, %K); Dhile %V Obj.eof% ) ) >

#h!obj.,et% ); cout << ch; ? @etch% ); Obj. close% ); ? Aue 9ssume there is a file cOa Uessa,e. :+t containin, certain line of t+t. #reate a file cOa Uessa,e5.t+t' and cop0 the contents of messa,es.t+t into it. 7efore copin, the character must be con erted upper to lo;er ( ice ersa ( spaces must be sEipper. Finall0 displa0 the contents of Uessa,e5 t+t. oid main% ) > if stream obj2 % Uessa,es.t+t); Stream obj5 %Uessa,e5. t+t' ios < < out ^ ios < < in); char ch; if %V Obj2) > cout << sourcl file cant be opened; e+it%2); ? Dhile %V Obj2' eof) > #h ! obj2. ,et% ); if %chV ! B5) > if %ch>!RQ ( ( ch<!3K) #h!ch$B5; else if %ch > !3S (( ch <!255) #h!ch=B5; ? Obj5.put%ch); ? Obj5.seeE,%K); Dhile % V obj5. eof% ) ) > #h!obj5. ,et% ); cout << ch; ?

@etch% ); Obj5.closs% ); Obj2. close% ); ? READIN* AND ,RITIN* STRIN*S oid main % ) > Fstream obj % 6ata.t+t' ios < < out ^ ios < < in); if V%Vobj) > cout << error; e+it %2); ? char te+t J4KL; cout << ho; man0 lines; int n; cin >> n; cout << *nter << n<< lines each terminated b0 enter < <<end2; for %in i!2; i<!n; i$$) > cin.,et line %te+t' 4K); Obj << te+t << end2; ? Obj. seeE, %K); cout << File ;ritten press na0 Ee0 to read; @ecth% K; Dhile %Vobj.eof% ) ) > Obj.,etline %te+t'4K); cout << te+t << end2; ? @ecth% ); Obj.close% ); ? oid main% ) > Fstream obj % 6ata.t+t' ios < < out ^ ios < < in); if %Vobj)

> cout << error; e+it%2); ? char te+t J4KL; cout << enter lines and press enter on ne; line to stop; Dhile %2) > cin.,etline %te+t' 4K); if %strlen %te+t) ! !K) 7reaE; Obj << te+t << end2; ? ? FILE OPENIN* MODES 2. ios < < out %6efault mode of ofstream) if file is not e+istin, then it is created. Other;ise data ,ets *rased and pointer is placed at the be,innin,. if file is e+istin,' pointer is placed a the be,innin, other;ise error is ,enerated. B. ios < < app It can not alter pre ious contents but can add ne; content at the *nd of file. C. ios < < ate %ate stands for at the end) 9llo;s updations as ;ell as addin, of ne; data. In this pointer can mo e for;ard and bacE;ard.

5. ios < < in

Q. ios < < trunc "eeded onl0 in fstream. /sed ;ith ios < < out :runcate pre ious data ( brin,s pointer to be,innin,. R. ios < < nerplace /sed ;ith ios < < out if file is e+istin, do not replace it other;ise create it.

S. ios < < nocreate /sed ;ith ios < < out if file is e+istin, o er;rite it other;ise do not create it. 4. ios < < binar0 if ;e ;ant to ;rite data in binar0 form.

BINARY I <O
oid ;rite Of stream Uember %char M' address of ariable ;hose data is to be Dritten int ) no of b0tes to be ;ritten

int a ! 5BK32 ; Obj' ;rite %% char M) (a' siPe of %int) ); char b ! H+F; Obj.seeE,%K); int c; Obj. read % %char M) (c' siPe of %int ) ); cout << c; char d; Obj. read %(d' siPe of %char) ); cout <<d; int read %char M' int) 9ddress of ariable ;hose data is to be stored after readin, From file On successfull0 readin, from file it returns 2 on error it return K. Teadin, and ;ritin, class objects class *mp > int a,e; char name J5KL; float sal; public<

oid ,et% ) > cout << enter a,e' name and sal; cin >> a,e >> name>> sal; ? oid sho;% ) > cout << a,e << ? ?; oid main % ) > *mp *; Fstream obj % Tecords.dat' ios < < out ^ ios < < in ^ ios < < trunc^ ios < < 7inar0 ); if %V Obj) > cout << error in openin, file; e+it %2); ? *.,et% ); Obj.;rite %%char M) (*' siPe of %*mp) ); Obj.seeE,%K); *mp F; Obj.read %%char M) (F' siPe of %*mp)); F.sho;% ); @etch% ); Obj.close% ); ? Re(0i'- A'0 ,"i i'- M&l iple O6Ce) $ oid main % ) > *mp *; Fstream obj % Tecord.datF' ios< < out^ ios < < in ^ ios < < trunc ^ ios < < 7inar0); if %V Obj) > <<name << sal <<end2;

Out << error in openin, file; e+it %2); ? char choice; > e.,et% ); obj.;rite %%char M) (*' siPe of %*mp)); cout << 9n0 Uore %1O"); cin.i,nore% ); cin >> choice; ? ;hile % ch ! ! H0F); Obj. seeE, %K); Dhile %opj.read %char M) (*' siPe of %emp)) *.sho;% ); ,etch% ); obj.close% ); ? T!pi)(l Fe( &"e O5 Re(023 No e <= if in an0 ane pro,ram' ;e ;ant to read file successi el0 to eof ;e must clear the fla, Obj. seeE, %K); Obj. clear% );

A. D9- to ;rite multiple records of t0pe emp in a file. 9ccept a name from user ( displa0 the record of the emplo0ee b0 searchin, it ;ith in the file and displa0 the appropriate messa,e oid main% ) > int flat ! K *mp *; Fstream obj2 % *Eta' t+t' ios < < out ^ ios < < in ^ ios < < trunc ^ Ios < ; binar0); if %V Obj) > cout << error; e+it%2);

? char ch; 6o > *.,et% ); Obj.;rite % % char M) (*' siPe of %*mp)); cout << 9nt more %0On); cin . i,nore % ); ? ;hile %ch ! ! H1F); char name J5KL; cout << enter name to search; cin >> name; Obj. seeE,%K); Dhile %obj.read %char M) (*' siPe of %emp)) > if % V % * ! ! name) ) > *. sho;% ); Fla, !2; 7reaE; ? ? if % V fla,) or if %fla, ! !K) > cout << Tecord not found; Obj2. close% ); ? int operator ! ! %char M ptr) > Teturn %strcmp %name' ptr) ); ? ? RANDOM I<O A. 9ssume there is a file cOa Tecord.dat ;hich contains se eral records of t0pe emp. D9- to open this file ( read the last record.

oid main % ) > ifstream in % Tecords.dal' ios < < in ^ ios < < binar0); if % V in) > cout << error; e+it %2); ? In.seeE, %=2 M siPe of %emp)' ios < < end); *mp *; In. read % % char M) (*' siPe of %emp)); *.sho;% ); In.close% ); @etch% ); ? No e23 -rotot0pe of seeE,% ) oid seeE, %int' int) "o' of position of mo ement 70tes to ios < < be, Uo e ios < < cur Ios < < end

D9- to accept a name from user. Search the record of that emplo0ee in Tecords.dat ( 9dd a ne; record at its position b0 acceptin, it from user oid main% ) > char tempJ5KL; *mp *; Fstream in % Tecords.dat' ios < < in ^ ios < < ate^ ios < < binar0); cout << enter name to update; cin >> temp; In.seeE,%K); Dhile %in.read % %char M) (*' siPe of %emp) ) > if % % * ! !temp) ! !K) > *.,et% );

In.seeE, %=2 M siPe of %*mp)' ios < < cur); In.;rite % % char M) (*' siPe of %emp)); 7reacE; ? ? In.clear% ); In.seeE,%K); Dhile %in.read % % char M) (*' siPe of %*mp) ) *.sho;% ); int operator ! !%char Mn) > Teturn %strcmp %temp' ptr) ); ? ? A$$i-'me' 23 2. D9- to delete record ,i en b0 user from file. 5. D9- to update just the salar0 of emplo0ee ;hose name ,i en b0 user.

TEMPLATES
:emplates are a techniGue pro ide b0 #$$ usin, ;hich a pro,rammer can define a sin,le function in ;hich last to be carried out is mentioned but the datat0pe is not mentioned. 6urin, runtime b0 looEin, at the call of the function ( its parameter t0pe the compiler ,enerates specific ersion of that function to act accordin, to parameter passed. :hus in other ;ords' ;e can sa0 templates are ,eneric functions ;hich at the time of creation are onl0 told ;hat to do ( durin, run time the0 become a;are on ;hat t0pe of ar,ument it has to be done. Templ( e$ ("e o5 .o !pe %i) Function :emplate %ii) class :emplate

S!' (1 F&') io' Templ( e :emplate <class <t0pe=name> > <return Z t0pe> < function=name> %< t0pe=name> <ar,=name>) E1(mple :emplate <class :> oid displa0 % : n) > cout << n << end2; ? oid main % ) > int a !2K; char b ! H+F; float c! 22.Q; 6ispla0 %a); 6ispla0 %b); 6ispla0 %c); ? Drite a function template cOa s;ap ;hich accepts t;o parameters ( s;aps then. -arameters passed can be t;o inte,er' t;o floats t;o class. Finall0 t;o s;apped alues must be displa0ed in the function main :emplate <class :> oid s;ap % : (a' : (b) > : temp; :emp ! a; 9! b; 7 ! temp; ? oid main % ) > int a' b; cout << enter t;o inte,ers; cin >> a >> b; S;ap %a' b); cout << Ha! <<a<< b! <<b<<end2;

cout << enter t;o character; char p' G; cin >> p >>G; S;ap %p' G); cout << p! <<p<<FG ! <<G <<end2; float +' 0; cout << enter t;o float numbers; cin >> +>>0; S;ap %+' 0); cout << +! <<+<< 0! <<0 << end2; ? A. ;rite a function template ;hich accepts t;o alues as an ar,ument ( return ma+imum amon,st then. :emplate <class :> : ,reater % : (-' : SG) > if % p > G) Teturn %p); else Teturn %G); ? oid main % ) > int a' b; cout << enter t;o inte,ers<; cin >> a >> b; cout << ma+imum ! << ,reater %a' b); cout << *nter t;o charr< char +' 0; cin >> + >>0; cout << ma+imum ! << ,reater %+' 0); ? Drite a function template cOa ,reatest ;hich accepts an arra0 as an ar,ument ( returns the lar,est element of that arra0. :he arra0 passed can be of different t0pe and different siPe.

:emplate <class :> : ,reatest % : Ma' int n) > int I; : ma+ ! Ma; for %i!2; i<n ; i$$) > if % M %a$i) > ma+) Ua+ ! M %a$i); ? Teturn %ma+); ? oid main % ) > int arrJ L ! >S' 22' 5' B' C' 4?; float brrJ L ! > 2K.C' 22.B' R.Q' 4.5?; cout << ma+ int ! << ma+ %arr' R); cout ma+ float! << ma+ %brr' C); ?

CLASS TEMPLATE
:emplate <class :> class 6ata > : a; : b; : c; public< oid ,et% ) > cin >> a >> b; ? oid add % ) > # ! a$b; ?

oid sho;% ) > cout << alues are ! << a << end2; cout << b; cout << sum! <<c; ? ?; oid main % ) > 6ata <int> obj2; 6ata 'double> bj5; cout << enter t;o int; Obj2.add% ); cout << enter t;o doubles; Obj2' ,et% ); Obj5. add% ); Obj2. sho;% ); Obj5. sho;% ); ? )l($$ Templ( e ,i # Di55e"e' *e'e"i) T!pe :emplate <class :2' class :5> class 6ata > :2 a; :5 b; public< oid ,et% ) > cin >> a >>b; ? oid sho;% ) > cout << alues are ! << a << and << b<< end2; ? ?; oid main% ) >

6ata <int' float> obj2; 6ata <double' char> obj5; cout << enter an int and float; Obj2.,et% ); Obj2.sho;% ); cout << enter double and char; Obj5.,et% ) Obj5.sho;% ); ? A. ;rite a class template for a class called stacE and implement three basic operations of stacE push' pop and peeE. :he stacE can be of int' char and flots. :emplate <class> class stacE > : arr JSL; int tos; public< StacE % ) > :os ! =2; ? : pop % ); ?; :emplate <class :> oid stacE <:> < < push %: n) > if %tos ! ! C) > cout << stacE o erflo;; Teturn; ? $$ tos 9rr JtosL ! n; ? :emplate <class :> : stacE <:> < < pop % ) > if %tos ! ! =2)

> cout << stacE under floa;; Teturn%=2) ? Teturn %arr Jtos = =L); ? oid main % ) > StacE <int> sa; int n; StacE <char> s5; char ch; for %int i!2; i<!R; i$$) > cout << enter int to be pushed; cin >> n; S2.push%n); ? for %int i!2; I'R; i$$) cout << element popped ! << s2.pop% ); ? O/e"lo(0i'- O5 A$$i-'me' Ope"( o" class strin, > char Mp; public< strin, %int); oid set strin, %char M); oid resetstri,n % char M); oid displa0 % ); strin,% ); ?; strin, < < strin, %int n) > -!ne; int Jn$2L; ? oid strin, < < setstrin, %char Mstr)

> Strcp0 %p' str); ? oid strin, < < resetstrin, %char Ms) > Strcp0 %p' s); ? oid strin, < < displa0 % ) > cout << p <<end2; ? strin, < < strin,% ) > 6elete J L p; cout << Uemor0 deallocated; ? oid main % ) > strin, s2 ! 5K; strin, s5 ! 5K; S22. setstrin, % Hello /ser); S5!s2; S2. displa0 % ); S5. displa0 % ); S2. resetstrin, % Delcome); S2. displa0 % ); S5. displa0% ); ? No e23 ;hen e er the class is containin, d0namic pointer then it is necessar0 to o erload assi,nment operator 9t the time of o erloadin, ! it is necessar0 to pass parameter b0 reference. % e, % strin, ( s) ). No e 23 for cascadin, of assi,nment operator it is necessar0 that return t0pe must be strin,

oid strin, < < operator !%strin, (s) > strcp0 3p' s.p); +!s.+; ?

strin, strin, < < operator ! %strin, (s) > strin, %p' s' p); Y! s'+; Teturn %M this); ? No e 23 A. ;h0 do ;e o erload assi,nment operator] 9ns<= :he default assi,nment operator pro ided b0 #$$ is used for cop0in, one object of class to another but it copies the alue bit b0 bit i.e. the alue contained in e er0 bit of source object are copied in e er0 bit of destination object. :his beha iour is perfect if source cosle is not containin, an0 pointer to d0namicall0 allo eated blocE' but if it is so then the default eGul to %!) operator ;ill simpl0 cop0 the address stored in the pointer ;ith in source object to pointer in the destination object. :his ;ill maEe t;o the defferent pointers point to same location ;hich ma0 cause multiple problems liEe the destructor callin, delete operator for the same memor0 to o ercome this' a pro,rammer should o erload the eGual %!) operator ( pro ide his o;n definition for cop0in, the data pointer b0 pointer of source object rather than address. O/e"lo(0i'- O5 I'$e" io' A'0 E1 "() io' Ope"( o" -rotot0 Of << operator<= friend ostream ( operator << %ostream ( cout' strudent (p); class *mp > int a,e; char name J5KL; float sal; public< friend istream ( operator >> %istream S' *mp(); friend ostream ( operator << %ostream (' *mp (); ?; Istream ( operator >> %istream ( in' *mp ( p) > In >> -.a,e >> -.sal >> -.name;

Teturn %in); ? Ostream ( operator << %ostream ( out' *mp (-) > Out << -.a,e << << -.name<< << p.sal; Teturn out; ? oid main% ) > *mp *' F; cout << *nter a,e' name and sal; cin >> *; cout << *nter a,e' name ( sal; cin >> F; cout << * << end2; cout << F <<end2; A. Dhat is the need of o erloadin, insertion and e+traction operator] 9ns<= In #$$' all primiti e t0pes liEe int' float' char etc. are displa0 on console usin, predefined object cout alon, ;ith insertion operator %<<). "o; if pro,rammer ;ishes to use the same ;a0 of displa0in, objects of his class on screen then he has to o erload insertion and e+traction operator so that the0 can be derictl0 used ;ith user defined objects. A. Dh0 donFt ;e o erload insertion and e+traction operator as member function] 9ns<= Insertion and *+traction operator are binar0 operator and if binar0 operator is o erloaded as member function of class then a compulsion is their to Eeep the object of same class to;ards left of operator ;hile callin,. :hus if it is done then ;ll ;ould become - << cout ;here - is object af class. "o; this iolotes the re,ular s0mmetr0 of insertion operator and so it must be o erloaded as friend function. A. *Gual Operator can ne er be o erloaded as friend function. 9ns<= Since eGual operator should return the reference of callin, object %to support coscadin,). It has to be o erloaded as member function as friend function do not ha e an0 callin, object No e23

*Gual operator if defined b0 base class ne er inherited b0 deri e class because it needs the same members in source as ;ell as destination object.

TYPE CON4ERSION
:0pe con ersion is the process usin, a pro,rammer can con ert alue from primiti e to non primiti e and ice ersa as ;ell as from one object of class to another object of different class. :hus t0pe con ersion falls in three cate,ories<= 2> 7asic to /ser 6efined 5> /ser 6efined to 7asic %-rimiti e ) B> /ser 6efined to /ser 6efined #on ersion 7et;een 7asic :O /ser 6efined #onstructor %7asic t0pe > OO steps to con ert basic to user defined ? #on ersion 7et;een /ser 6efined :O 7asic Operator primiti e t0pe of #$$ % ) return t0pe > OO steps to con ert basic to user defined Teturn %<basic Z al>); ? E1(mple /ser :o 7asic ( 7asic :o /ser class Ueter > float len,th; public < Ueter % ) > 8en,th ! K.K; ?

Ueter %float cm) > 8en,th ! #UO2KK; ? Operator float% ) > Flaot ans! len,th M 2KK.K; Teturn %ans); ? oid accept meters% ) > cout << enter len,th in %int meters); cin >> len,th ; ? oid sho; meter% ) > cout << In meter ! << len,th ; ? ?; oid main % ) > Ueter U2 ! 5QK; Ueter U5; U5.accept Ueter% ); float cm ! m5; OO float #U! U5. operator float% ); cout << 5QK Ueters ;hen con erted; U2. sho; Ueter% ); U5. sho; Ueter% ); cout ;hen con erted to cms ! << cm ? P"o-"(m 23 A$i-'me' class strin, > char str J2KL; public< strin, %int n) > Itoa %n' str' 2K); ?

strin,% ) > Str JKL! H.KF; ? Operator int% ) > N!2; I! strlen %str); Dhile %i>!K) > Sum ! sum $ %str JiL =C4)M E N M ! 2K; I = =; ? Co'/e"$io' F"om U$e" De5i'e0 To U$e" De5i'e0 2. #on ersion Toutine In Source Object<= Operator <destination[class=name> % ) > OOroutines to con ert source to destination Teturn % <destination Z object>); ? 5. #on ersion Toutine In 6estination Object<= #onstructor % <source Z class Z name>) > OOroutines to con ert source to diction ? #on ersion From /ser 6efined :o /ser 6efined 70 -lacin, #on ersion Toutine In Source Object class Tadian > float rad; public< Tadian % ) > Tad ! K.K;

? Tadian %float r) > Tad ! r; ? oid sho;% ) > cout << Tadian ! << rad << end2; ? ?; class 6e,ree > float de,; public< 6e,ree% ) > 7e, ! K.K; ? Operator Tadian % ) > float + ! de, M -IO24K; Tadian obj ! +; Teturn %obj ); ? oid sho;% ) > cout << 6e,ree! << de,; ? oid ,etda,ree% ) > cout << enter an,le in de,ree!; cin >> de,; ? ?; oid main % ) > 6e,ree 6; d. ,etde,ree% ); Tadian T; T!6;

6. sho;% ); T. sho;% ); ? class 6e,ree > float de,; public< 6e,ree% ) > 6e, !K.K; ? oid sho;% )[ > cout << 6e,rees! << de,; ? oid ,etdata% ) > cout << enter an,le in de,rees; cin >> de,; ? Flaot ,et6ree% ) > Teturn %de,); ? ?; class Tadian > float rad; public< Tadian %6e,ree Obj) > Tad ! obj.,et 6ece % ) M -IO24K; ? Tadian % ) > Tad!K.K; ? oid sho;% ) >

cout << Tadian $ << rad; ? ?; oid main% ) > 6e,ree 6; 6.,et6ata% ); Tadian T ! 6; 6. sho;% ); T.sho;% ); ? A$$i-'me' 23 #include <iostream.h> #include <conio.h> class hour > float time; public< Hour% ) > :ime ! K.K; ? Hour %double +) > :ime !+OBRKK; ? Operator float% ) > float + ! time M BRKK; Teturn%+); ? oid accept% ) > cout << enter time in hours; cin >> time; ? oid sho;% ) >

OO Tadian T %6);

cout << in hour ! << time; ? ?; oid main% ) > Hour t2!BRKK; Hour t5; :5. accept% ); float + ! t5; cout << BRKK ;hen con erted to hours!; :2.sho;% ); :5.shjo;% ); cout << ;hen con erted to sconds ! <<+; @etch% ); ?

CONSOLE I<O OPERATIONS U'5o"m( e0 1. U'5o"m( e0 I<O %a) istream ( ,et %char () %b) int ,et% ) %c) istream ( ,et %char M' int) E1(mple 2= cin.,et%ch); #an read onl0 characters cin!cin.,et% ); Istream ( ,etline %char M' int num' char delimiter); Istream ( ,etline %char M' int num); E1(mple 23 oid main % ) > char ch; Fo"m( e0 can be called b0 cin

cout << enter te+t and press enter to stop; cin. @et %ch); Dhile %ch V !F.nF) > cout << ch; cin.,et%ch); ? @etch% ); ? oid main % ) > char countr0 J5KL' capital J5KL; cout << enter countr0 name<; cin.,et %countr0'5K); cin.,etline %countr0' 5K); cout << enter capital; cin.,etline %capital' 5K); cout << contr0 is << countr0 << end2; cout << its capital ! << capital << end2; ? No e2= cin.,etline %countr0' 5K' M)

:his ;ill terminate after 23 character or on pressin, M' nothin, ;ill happen on pressin, enter re0. Functions Of Ostream class %a) ostream ( put %char) %b) ostream ( ;rite %char M' int) :his ;ill start from base add upto no. of inte,ers ,i en. E1(mple 23 oid main% ) > char strJ L ! > pro,rammin, ?; int I; for %i!K; i<strlen %str); i$$) > cout.put %str JiL); cout << end2;

? for %i!2; i<!strlen%str); i$$) > cout.;rite %str' i); cout << end2; ? for %i!strlen %str) ; i>!2; i==) > cout.;rite %str' i); cout << end2; ? ?

FORMATTED I<O
F&') io' %i);idth% ) %ii) precision% ) %iii) fill% ) %i ) setf% ) % ) unsetf% ) De$)"ip io' specifies reGuired no of fields to be used for displa0in, the output. :his fn is used for ali,nment. specifies the no of alues to be displa0ed after decimal pt specifies a character to be used to fill the unused area of field. 70 default the fullin, is done usin, spaces. sets the format fla, to be used ;hile displa0in, the output. clears the flo,s set usin, setf ( restones the default settlin,.

De5i'i'- 5iel0 ,i0 # -rotot0pe<= int ;idth% ) Teturns the current ;idth. int ;idth %int) Old ;idth aurrent ;idth oid main% ) >

cout. Didth%C); cout << 25B; cout.;idth%C); cout. << B3; cout.;idth%5); cout << 5BCQ ? Settin, -recision P"o o !pe <=int precision % ) 70 default int precision %int) precision is of R pt. oid main % ) > cout precision %5); cout << 5.5B << end2; cout << Q. 2R3 << end2; cout << C.KKB << end2; ? O& p& 5'5B Q.2S C Filli'- <= int fill% ) int fill %char) oid main% ) > cout.file % HMF); cout.precision%5); cout.;idth%R); cout << 25.QB; cout.;idth%R); cout << 5K.Q; cout. ;idth%R); cout << 5; ? oOp M 25.QBM M M 5K.Q M M M M M 5

No e :here is no need to set fill and precision a,ain and a,ain ;hile ;idth fla, must be set a,ain and a,ain. Formattin, Dith Fla,s ( 7it Fields 2> setf lon, self %lo,=setbits' lon, Z field) Fla,= alue %2st ar,ument) 7it field %5nd 9r,uments 6escription Ios < < left ios < < adjust field justifies the output on left side. Ios < < ri,ht ios < < adjeist field justifies the output in si,ht ali,n mennes. Ios < < internal ios < < adjust field passin, accurs bet;een the si,n or base indicator ( the alue ;hen the alue fails to fill the entire ;idth ios < < dec ios < < base field displa0 the data in decimal con ersion ios < < oct displa0 the data in actor ios < < ha+ displa0 the data in he+adecimal ios < < scientific ios < < float field user e+ponential floatin, notation ios < < fi+ed user normal floatin, notation E1(mple 23 oid main % ) > cout.self %ios < ; left' ios < < adjust field); cout.fill %HMF); cout. precision %5); cout.;idth %R); cout << 25.QB; cout.;idth %R); cout << 5K.Q; cout.;itdth %R);

cout <<5; ? 25.QB M 5K.Q M M 5 M M M M M oid main % ) > cout.self %ios < < internal ^ ios < < adjust field ); cout.field %HM); cout. precision %5); cout. ;idth %2K); cout << =C5K.QB; ? O& p& 2 = = M M M C 5 K . Q B 6ispla0in, :railin, Xeros ( -lus Si,n 8on, self %lon, Z setbits) %i) ios < < sho; pint %for trailin, Peros) %ii) ios < < sho; pos %for plus si,n) oid main % ) > cout.setf %ios < < sho; point); cout.precision %5); cout << 5K.QQ << end2; cout << QQ.QQ << end2; cout << 5K.CK << end2; ? E1(mple 23 oid main % ) > cout.setf %ios < < sho;point); cout.setf %ios < < sho; pos); cout.setf %ios < < internal' ios < < adjust field); cout.precison%B); cout.;idth %2K); cout << C5K.QB; ? O& p& output 5K.QQ QQ.QQ 5K.CK

Formattin, 6ata /sin, Uanipulators "on -arameterised Uanipulators M('ip&l( o" 2. end2 5. dec B. be+ C. oct Q. flush De$)"ip io'

terminates the line and transfers the cursor to ne+t ro;. set con ersion base to 2K. set the con ersion field to 2R. set the con ersion field to 4 flushes the output screen

E1(mple 23 2. D9- to read a number in decimal and displa0 it in h+adecimal. oid main % ) > cout << enter number; cin a; cin >> a; cout << no is ! << n << end; cout << ItFs he+adecimal alue! << he+<<n; cout. self %ios < < sho; base); cout << a; ? O& p& <= E1(mple <= > int n; cout << enter number; cin >> ne+>> n; cout << number! << n; ? no is ! RC Its he+aslccimal alue ! CK K+ CK oid main % )

P("(me e"i$e0 M('ip&l( o"$ M('ip&l( o" 2. set; %int) 5. setprecision %int) B. setfil %char) C. setbase %int) Q. setiosfla, %lon,) R. resetiosfla, %lon,) De$)"ip io' sets the field ;idth sets number of di,its to be displa0ed after decimal pint sets the character to be field set the con ersion base. Here possible alue of int are 4.2K and 2R. sets the format fla,. resets the format fla,.

E1(mple 2= oid main % ) > int n ! 2KK; cout << he+ <<n << << dec <<n << end2; float f ! 255.BCBC; cout << f << end2; cout << setprecision %B); cout << f << end2; cout << setiosfla, %ios < < internal ? ios < < sho; base); cout << he+ << n << end2; cout << setiosfloa, %ios < < scientifie) << f << end2; ? O& p& <= RC 2KK 255.BCBB3 3 255. BCB K+KKRC 2. 5 5 B c $ K. 5

O erloadin, J L Operator class 9rra0

> int M-; int n; public < 9rra0 %int siPe) > -!ne; int JsiPeL; "!siPe; ? int ( operator J L %int i) > Teturn %M %p$i) ); ? oid fil %int pos' int alue) > M %p$pos) ! alue; ? 9rra0 % ) > 6elete J Lp; ? ?; oid main % ) > 9rra0 obj%Q); int +; for %int i!K; i<Q; i$$) > cin >> +; Obj.fill %I' +); or obj JiL ! + ? for %I ! K; i<Q; i$$) > cout << obj JiL; ? ? O erloadin, Of Operator % ) class 7o+

> int l' b' h; public< 7o+ operator % ) %int' int' int); oid ,et% ) > cout << enter l' b and h; cin >> l >> b >> h; ? oid sho;% ) > cout << l' << << b << << h; ? ?; 7o+ 7o+ < < Operator %int l' int b' int h) > 7o+ temp; :emp.l ! l $ this l; :emp.b ! b $ this b; :emp.h ! h $ this h; Teturn %temp); ? oid main % ) > 7o+ 72; 72.,et% ); 7o+ 75; 75 ! 72 %Q' B' 3); OO 75 ! 72. operator % ) %Q' B' 3); 72. sho;% ); 75. sho;% K; ?

*RAPHICS MODE PRO*RAMMIN*


Steps TeGuired for 6esi,nin, @raphics Uode -ro,ram 2> #oncert the displa0 monitor from te+t mode to ,raphics mode. 5> -erform the reGuired ,raphics operation liEe fillin, colorin,' dra;in, etc.

B> Finall0 close the ,raphics mode and restore character mode. #on ertin, #haracter :o -i+els 2. oid init ,ra,raph %int M' int M' char M) 6ri er resolution path of 7@I file Or Uode 5. 6ra;in, usin, built in functions. B. oid close ,raph% ); oid restorecrtmode% ); P"o-"(m<= D9- to cou ert monitor displa0 mode from char to pi+el and print ;elcome messa,e. #include <,raphics.h> #include <conio.h> #include <stdlib.h> oid main% ) > int ,d' ,m' ec; @d! 6*:*#:; Intt,raph %(,d' (,m' #<..:#..7@I); *c! ,raphresult% ); if %ecV!,rOE) or %ecV!K) > -rintf %error in initialisin,); e+it%2); ? #learde ice Outte+t % ;elcome to ,raphics); @etch% ); #lose,raph% ); Testarectmode% ); ? No e23 int ,etma++% ); int ,etma+0% )<= returns the ma+imum alue of + Z coordinate. returns the minimum alue of if Z coordinate.

9ssi,nment<= oid main % ) >

Uodif0 the abo e code so that no; code displa0 the Uessa,e at the necter of screen.

int ,d' ,m' ec; @d ! 6*:*#:; Init,raph %(,d' ( ,m' #<..:#..7@I); *c!,raphresult% ); if %ec V ! ,rOE) > -rintf % error); e+it%2); ? #learde ice% ); int a ! ,etma++% ); int b ! ,etma+0% ); Outte+tr0 % % aO5)' %bO5)' ;elcome to ,raphics); @etch% ); #lose,raph% ); Testorecrtmode% ); ? A. D9- to accept user name ( then con ert screen to ,raphics mode ( displa0 the name ,i en b0 user at the center of the screen on char at a time. oid main % ) > char strJ5KL int ,d' ,m' ec; @d ! 6*:*#:; Init,raph %(,d' (,m' c<..:#..7@I); *c ! ,raphresult% ); if %ecV!,rOE) > -rintf % error); e+it%2); ? #learde icl % ); printf %enter name); Uo e to %,etma++% ) O5' ,etma+0% )O5);

for %i!K; strJiL; i$$) > Spritf %ms,' &c' strJiL); Out te+t %ms,); 6ela0 %2KKK); ? ? #han,in, the font st0le and siPe 2. oid sette+tst0le %int font' int dir' int charsiPe) description of parameters 5o' default Z FO": %K) :TI-8*Y Z FO": %2) SU988 Z FO": %5) S9"S Z S*TI: Z FO": %B) @O:HI# Z FO": %C) S#TI-: Z FO": %Q) SIU-8*Y Z FO": %R) -TI-8*Y Z S#TI-: Z FO": %S) #OU-8*Y Z FO": %4) */TO-*9" Z FO": %3) 7O86 Z FO": %2K) horiP Z dir %K) Iert Z dir %2)

Di"

C#("$iBe 2= 2 to 2K 2 bein, siPe of 4 + 4 pi+el. P"o-"(m23 oid main% ) > char M font Z st0le J L ! > 6efualt Z font ====' 7O86= FO":); int ,d' ,m' ec; char ms,J5KL; @d ! 6*:*#:; Init,raph %(,d' (,m' #< .. :#.. 7@I); *c ! ,raphresult % ); if %ec V ! K)

> -rintf % error); e+it %2); ? #learde icl % ) Uo e to %,etma++% )O5' ,etma+0% )O5); for %2!K; i<!2K; i$$) > -rintf %ms, ! shi = &s' font=st0le JiL); Sette+t st0le %I' K' 2); Outte+tr0 %,etma++% )O5' ,etma+0% )O5' ms,); @etch% ); #learde icl % ); ? #learde icl% ); Testorecrtde icl % ); ?

DRA,IN* IN *RAPHICS
2. 5o" D"(.i'- Li'e<= a. b. c. oid line %int +2' int 02' int +5' int 05) oid linerel %int' int) oid line to %int' int)

E1(mple <= oid mai" % ) > int ,d' ,m' ec' +' 0; @d ! 6*:*#:; Init,raph % (,d' (,m' c< ..:#..7@I); *c ! ,raphresult% ); if %ec V ! K) > -rintf % error); e+it %2); ? #learde icl % );

Y!,etma++% )O5; 8ine %K' K' +' 0); @etch % ); #lose,raph% ); Testorertmode% );

0!,etma+0% )O5

A.D9- ;hich dra;s a line from 5K' BK to 2KK pi+els further ( displa0 the ;ordinate of line at its end point. oid main % ) > int ,d' ,m' ec' +' 0; @d ! 6*:*#:; Init,raph %(,d' ( ,m' c< ..:#..7@I); *c ! ,raphresult % ); if %ecV ! K) > -rintf % error); e+it %2); ? #leardericl % ); Uo e to %5K' BK); Sprintf %ms,' &d &d' ,et +% )' ,et0% ) ); Outte+t %ms,); 8inerel %2KK' 2KK); Sprintf %ms,' &d &d' ,et+% )' ,et 0% ) ); Outte+t %ms,); ? D"(.i'- Li'ee I' Spe)i5i) ,i0 # 8 S !le oid setline st0le %int st0le' int pattern' int thicEness) S !le<= "o K 2 5 B C #onstant SO8I6=8I"* 6O::*6 Z8I"* #*":*T=8I"* 69SH*6=8I"* /S*T7I:=8I"* meanin, solid line line ;ithdot ( dash line ;ith dashes

P( e"'23 T#i)G'e"$23 oid main% ) >

It is al;a0s Pero e+cept ;hen first parameter is userbit line. 2 Z :HI#N=DI6:H B Z "OTU=DI6:H

int ,d' ,m' ec' I; char M st0le J L ! > solidline?' 6otted=line'====' 6ashedline?; @d ! 6*:*#:; Init,raph % (,d' ( ,m' #< ..:#..7@I); *c!,raphresult% ); if %ec V! ,roE) > -rintf % error); e+it%2); ? 6eard ice% ); for %i!K; i<C; i$$) > Spritf %ms,' &s in normal ;idth' st0leJiL); Outte+t %,etma++% )O5=5K' ,etma+0% )O5=2K' ms,); Setlinest0le %I'K' "OTU=DI6:H); 8ine %,etma++% )O5=QK' ,etma+0% )O5 $5K' ,etma++% )O5 $QK' @etma+0% )O5 $2KK); @etch% ); #learde icl% ); ? Testorectde icl% ); ? De5i'i'- P( e'$ i' U$e" De5i'e0 ,(! Io define a user bit line ;ee ha e to build a si+bit pattern. In this pattern ;hee er a bit is one the curresposin, pi+el in the line is dra;n in the current dra;in, colour. for e,<= RQQBQ or setline st0le %C' OYFFFF' "OTU=DI6:H); this ;ill dra; a solid line' setlinest0le %C' O+BBBB' "OTU=DI6:H)

this ;ill dra; a dashed line. D"(.i'- A")$ O" Ci")le$ O" Re) ('-le$ 2. oid arc %int +' int 0' intstan,le' int endan,le' int rad) 5. oid piesline %int +' int 0' int stan,le' int endan,le' int rad)

B. oid circle %int +' int 0' int rad) C. oid rectan,le %int left' int top' int ri,ht' int bottom) Q. oid bar %int left' in top' int ri,ht' int bottom) Filli'- Im(-e ,i # Di55e"e' P( e"'$ oid set color %int) oid setfillst0le %int pattern' int st0le) P( e"'2= :he pattern parameter si,nifies the pattern in ;hich filin, is to be made. /(l&e K 2 5 B Re$&l 7acE,round color Solid Fillin, ============== =============

N(me 2. *mpt0 Fill 5. SO8I6=FI88 B. 8I"*=FI8* C. 8IS89SH[FI8*

Q. S89SH=FI88

R 7N89SH=FI8* S. 8:7NS89SH=FI8* H9:#H=FI8* YH9:#H=FI8* I":*T8*9I*=FI8* DI6*=6O:=FI8* #8OS*=6O:=FI8*

Q R S 4 3 2K 22

D9- ;hich dra;s a sectan,le ;ith ;hite outline ( red fill color ( should displa0 the fitlin, in all of the t;el e patterns one at a time. 9lso name of pattern should be displa0ed ;ith in the rectan,le. oid main % ) > int ,d' ,m' ec' left' ri,ht' top' bottom' I; char M st0le J L ! > *U-:1=FI8*' SO8I6=FI8*' ====' #8OS*6=6O:=FI8*?; @d!6*:*#: Init,raph %(,d' (,m' #<..:#..7@I); *c!,rap,result% ); if %ec V!K) > -rintf %error); e+it %2); ? #learde icl % ); 8eft ! ,etma++% )O5=2KK; :op!,etma+0% )O5=2KK Ti,ht Z ,etma++% )O5$2KK; 7ottom!,etma+0% )O5; for%i!K; i<25; i$$) > Setfill st0le %I' T*6);

7ar%left' top' ri,ht bottom); Tectan,le %left' top' ri,ht' bottom); Outte+t+0 %left$QK' top$QK' st0leJiL); ? ?

FILLIN* CIRCLES 8 TRIAN*LESS


2. oid floodfill %int +' int 0' int boundar0) %+' 0) a point ;ith in the fi,ure ;hich has to be filled usin, flodfill also Eno;n as sad. 7oundar0 color<= #olor at ;hich fillin, should stop. Fillin, #ircles Dith 6ifferent -attern oid main % ) > char M pattern ! > *U-:1=FI8*' ========' #8OS*=6O:=FI8*?; int ,d' ,m' ec' +' 0' K; @d!6*:*#:; Init,raph %(,d' (,m' #<..:#..7@I); *c!,raphresult% ); if %ecV ! ,rOE) > -rintf % error); e+it%2); ? #learde ice% ); Y!,etma++% )O5; 0!,etma+0% )O5; for %i!K; i<25; i$$) > Setcolor %@T**"); #ircle %+' 0' 2KK); Setfill st0le %I' T*6); Floodfill %+' 0' @T**T); Setcolor %DHI:*); Outte+t+0 %+=QK' 0=QK' patterJiL); @etch% ); #leardi ice% );

? @etch % ); Testorecrtde ice% ); ? S o"i'- ('0 D"(.i'- Im(-e$ O' S)"ee' 2. oid ,etline %int' int' int' int' oid M) 5. int ima,esiPe %int' int' int' int) B. oid putima,e %int' int' oid M' int option) oid ,etima,e %int' int' int' int' oid M) copies the bit ima,e of specified postion in memoer0 2st parameter indicates left coordinates 5nd parameterer to rd B parameter ri,ht th C parameter bottom th Q parameter pointer to an arra0 lar,e enou,h to store bit pattern. oid putima,e Jint +' int 0' oid M are' int iption) #opies or outputs the ima,e pattern form memoer0 to the specified portion on the screen. Y ! startin, left coordinate 1 ! startin, top coordinate 9rr ! maner un ;hich color of the resultant pi+el is to be decided' taEin, into consideration the pi+els stored in memor0 ( the pi+els stores on screen. int ima,e siPe %int' int' int' int);= Teturns no. of b0tes reGuired to store the ima,e' on an0 Eind of error return =2 oid main % ) > int ,d' ,m' ec; char M buffer' ms, J5KL; int siPe =Kf=ima,e;

@d ! 6*:*#:; Init,raph % (,d' (,m' #<..:#..7@I); *c ! ,raphresult% ); if %ec V !K) > -rintf %error); e+it %2); ? Tectan,le %2QK' 2QK' 5KK' 5KK); SiPe=of=ima,e ! ima,e siPe %2QK' 2QK' 5KK' 5KK); if %siPe=of=ima,e ! ! =2) > Outte+t+0 %,etma++% )O5' ,etma+0% )O5' *rror); @etch% ); #lose ,raph% ); e+it%2); ? 7uffer ! %char M) malloc %siPe=of=ima,e M siPe of %char) ); if %buffer ! ! "/88) > Outte+t+0 %,etma++% )O5' ,etma+0% )O5' #an not allocate memor0); @ecth% ); e+it%2); #lose ,raph% ); ? @etima,e %2QK' 2QK' 5KK' 5KK' buffer); 8ine %5KK' 55K' 55K' 55K); -utima,e %2SQ' 5KK' buffer' #O-1=-/:); @etch% ); #lose,raph% ); Testore crtde ice% ); ? 4ALUES COPY3PUT CREEN O" OFF O" OFF EMORY O" O" OFF OFF OUTPUT O" O" OFF OFF

JOR3PUT

O" OFF O" OFF O" OFF O" OFF O" OFF O" OFF THE END

O" O" OFF OFF O" O" OFF OFF O" O" OFF OFF

OFF O" O" OFF O" O" O" OFF O" OFF OFF OFF

OR3PUT

AND3PUT

Potrebbero piacerti anche