Download as pdf
Download as pdf
You are on page 1of 55
er Y | Savrmmipat PuvLe PUNE Usivenssry - 2019 SYLLABUS | | SE (ET x) Seer OBJECT ORIENTED PROGRAMMING (For END SEM Exom - 70 Marks) ‘Mes. Anuradha A. Puntombekar Me. (Compe Forme Aide Proecarin ES. Moda Clogs Einar FEATURES Wan by opiate Bat Tecan, coven synes Quon Ane Format 1 faa Aros alone 1 capri Ses PPL Geran Dn 0%6 16 Da-2022 (CR ar aetna) —— ( 1ey-2017 + Des -2017 +o “2018 «De. 2018 | ite: 2019 Dee: 2019 Se 2022 +e. 2022 TABLE OF CONTENTS Ce ‘Operator Ox ter 3 tor Overloading Operator Fans 3 ns 25 Clase Members vs at Friend Functions 3 (overloading Unary Operators 3 Overcading of Operators using Friend Functions vnssnnnnn 3°44 pera Tnheritance and Polymorphiom (4-1) to 4-32) opier 4 ose and Derived Classes an Friend Classes. an Types of Inheritance 43 Hybrid Inheritance 4-10 Member Access Control aed Multiple tnheritance ennnnnnnnsnn ent 212 Ambiguity 4.13 Virtual B88@ Cat seven venus 38 410 au 42 aas 436 4a7 429 Chapter 5 sa 52 53 54 ss 56 57 58 Introduction to Polymorshism Pointers to Objects Virtual Functions Pure Virtual Functions Abstract Bate Class. Polymorphic Cass. Virtual Destructors. Early and Late Binsin. Container Classes afd Contained Classes “Templates, Namespaces and Handling (Parts Temeiates | Introduction to Templates Singleton Class. Function Template and Class Template Funetion Overloading vs. Function Templates. Introduction to Namespaces..en mn Rules of Namespaces. (Par Bxception Handling Basics of Exception Handling. Exception Handling Mecanism, Throwing and Catching Mechanism... 425 an 4-30 a ‘Exception (6-1) to -27) 5-10 ne 518 5-13 om o 33 _ Specifying Exceptions sons 538 5.10. Muttle exceptions s-1s sar Exceptions with Arguments 5-17 512. Ces streams 5-19 5.23, Stream Classes, 5-20 5.14 Unformatted /0 5-28 5.18, Formatted /0 and /0 Manipulate 5-22 ‘Chapter 6 Working with Fes Tey Te“ Cee wa {lasses fr File stream Operations 6-2 6.2. Opening and Closing ies a en 5.3. . Detecting End_Of File (EOF) 6-4 5:4 File Pointers and Manipulators 5-13 65 Updating File ou 56 Error Handling During Fle Operations, 16-20 ‘Solved SPPU Question Papers Sis S7Hy ro) (Moe | Operator Overloading | nF overloading ? Why I & necessary to overload SSP{SPPU : June-22, Dee-22, Marks 6 ‘Ans. + Operstor overloading can be defined st an ability to define ‘ew meaning fr an Existing (balla) “opertor. + Various pes of operators are - © Mathematical operators such ag + = 7 1 4. © Relational operators such as < > == Logical operators such as && © Access operators (> © Assignment operator = © Stream VO operttors << >> © ‘Type conversion operators and several others. All of these operators have a predefined and unchangeable mes! fr the builtin pes. All of these operators can be gives 4 lterpretation for diffrent classes or combination of ease ¢ Drovides the flexibility to the programiners in extending these bo operator 32 : Restrictions on Operators Overloading! 2 Discuss the usage ofthe operators that can aot be overall cr. aFTSPPU : ay 8, ee 4. peratrOvroaing possible © change an operator's precedence + tes uot possible €@ create mew operators, For example * which ‘ied in soe languages for exponentiation = You can not redefine, sieof, 7 oF « (0. +=... and -> most be member fuetons if they are overloaded, + and ~ = nest sposial tetment because they are prefix oF postfix 1+ Assigamest (=) should always be overioaded ‘mmamicaly alloctes memory 1k can not change the mamber of required operand(unary, binary, i an object + Overloaded operator must be either, © Non state member function of class oF At lest one parameter should be class or enumeration, + Makes no atsumptions about similar operators. For example, he fact fou cvetioaded » does not mean that you have also defined = for your class pe 3. What are the roles for over loading operators ? TSPISPPU + June.22, Marks 6, Doc.-22, Marke 4] (Only existing operators can be overloaded ‘The basle meaning of the opersor can not be changed. Overloaded operators must follow the syatax of original operator. For example for binary operior operand! operator operand? is the ‘yuan and thie can not be changed during overloading. ‘operand that is of user ‘Binary arithmetic operators, , "and /) must return a value . When binary operators overloaded through # member function, the left hand operand must bean object of relevant css, ae “sd for Engng Ses net Oremtrarmming 1-1 ovens Binary operators overloaded trough a member fnetion mast ake fone expliit argument | Binary operators overloaded through friend function takes two arguments 9. Una operator everlonded through # member fonction rust ss explicit argument and a0 return value Lo. Unary operators overloaded through friend function takes one explicit argument. ‘3.3: Operator Functions as Class ‘Members vs. as Friend Functions 24 Compare operator overloading using operator function as cass ‘member with operstor overlosdlg a fieid fanctio ‘Ans : Opert'or overloading can be achloved in two ways, 1) By an operator veroading by member fonction 2) By an oper oveouding non-member fiend function Sr.No: ]Operator facto as class | Operator factions frend Tmember function. function | ‘An overloaded opetor _[vAn-owroned operon tend ‘Bnetion should be declared in| could be declared iether ‘he publ section oft cis. | poate of able seon of « 2 | When an operator overionied | When an operator overloaded ‘action ise member Ri te, | fiction is end Hci, ‘takes one operand of | ker te operands of sweedefned die 9pe serdeiced data yee 1 Guia vaerng Ses = Diet Oriented Programming Declaration: Soppote Test a ass name, then | tas ame, then Test operator +(Tess ‘end Tex operate +(Tes Tes); | Betiation Definition: Test operator +(Test aby ‘Test opeator+(Tet ej, Test ‘ ic) | Te tome ‘ fempa= a= 4+ oj Test ea, retum temp; | tempe ~ obj + obs D recom te ) Warloading Unary Operators QS Explain operator overoadiog'of unary operator ‘Ans : + The umry operators reuite only one opin. In CH te aay operators ae Hb d ina + +. Ht can besdsclired as member functions taking 0 arguments, That ‘means forany operator -y- obj i interpreted as abjaperator-Q ‘+R sin'te deotaed as nom member functions taking one argument tnt Ist be the variable of class type (ie. Object) st reference, Tht meas, for aly operator - the «gh i, iterpreted as operatorsob). I bot Wy of definitions are present then, the funtion declared 3s ‘member takes the precedence. ‘Syntax : Function definition for operator overloading 4 Gee for Eincring Sue (lass name ory Peet es symbol ke functon boy Int x 11 // coordinate vatuos publi ola) x = 0: = 0; eonstructor Polenta) = y= ji} fester void gor xvi AD Ci ej ys) ointeperatr:// oporatarovetlad for unary Meise k Polat pointsoperatr ) ‘ tum “this // Use ofthis pointer Se _ Aue fr Egeing ea cen ray je ented Programming Operate Ovevioating | et Oren Prowraming , coordline nt) (= 47 = leaneesctar yeh peace ‘old got xy 8 By) (Se) 9) tne met) | (oord pperator’++( )//snary operator overloading point obf0, 19) user t 2219082 Yl! Negation cae operator = ae ob) = obi | Tetum “thie; //etuming the cwrent instance ob get er 9 , oute <7 The use of unary operator ie .' output “The ute of unary operator is %6 10, ¥: -20 Program explanation + Note that in above code the unary minus operstor function is overloaded by passing no argument toi bj = -ob: “+ When this statement occurs the call to operator -() function is given. ‘Thereby negated values of x and y are obtained. 7 Write a C+ program for overloading « increment operator +4. As ‘include ‘using namespace std: clase coord private Int x 9 //covrdinae values ube: coord) (x = 0: 9; //oonetrvctor for ab) = “A Guile for Enginearing Suse fot main) ‘ ex ¥ cout <"\n Kater che co-orcinas coord objoey): f.'<- ‘ing namespace ee clase wactor ‘ publi: a bs vector VP conetrsoter without 1 parameters vector, nt /leonstrator with parameters pera Oras One argomea: ‘Yeotor vectooperstor+ (vactor ob] Definition of ‘ operator tempa = «+ obja: temp = b + obj. rerum (temp) : old mand ‘ vector vitt0, 20); ‘vector vatt 2 vom at + v0 out << "Wn The Addition of two vectors i." cout << waa ce" and! << van, Output ‘The Addition of Two vectors is..1t and 22 et ene Progra 2.10 Which operators can eee ood + operator so that It ean add two complex numbers FSr[SPPU : June-22, Dec-22, Marks 6) ‘Ans. + Operators that can not be overloaded : Refer Q2. Overloading of + operator for adding two complex numbers ‘Pinciude Gace complex ‘ publ: complen()(eal=img=03) complen(fostsloet;—// parameterized constructor ‘complex operetor+ (complex): >: ‘complexcomplox(doat soa 9) ¢ > ‘complex complexoperator-+ (complex obi) ‘ complex romp: femptealereal+obj-r0al: temp imgimg-+ob) sme setum (temp) > sx mating complex a2. ‘complex bt) complex ¢ cout i mio © sung et Het ae Prana ring! snk eins clas DATE, wwe overioaded + operator ty add eo {at avd dsplay the reatentdnte, Assume noneat een ae ‘Pinctude oning namespace st clase DATE, a ante: DarEog, DATEIint dint mint 9) {damdmmemyy=y} DATE operater+ DATE); void cieplay DATE DATE:operator+ DATE D) ‘ DATE varsp, se day tag=c; Gey=da+ Dae; day>30) ‘ (Pars! days excaeding month “4 Gule forEnpning Sons, fag: 4g 1 me , staage=1) ‘month (month 1-12, one ‘month=month-12; > ‘empmm=month; Strye=Dyy) tempay=Danr tse temporary Dixy: otum temp, > wold DAT dispay( void) « cout for comparing two values include Ainchide ‘using namespace std; clase GrosterOp te tilond int operator >(GreaterOp obj,GrasterOp obi2); » Int operator >(GreaterOp abji,GreaterOp obj) “ Mlobst.a>cbj2.a) zetum 1; “A Gi for Engineering Stents SperatrOvroing GroesorOp val2%0}, svat>val) ‘cout<<"\n The fret value is greeter thatthe second coute<"\n The second alu tz groster than the fst; rota Output "The second value is groatar than the frst “A Gute jor Erneta Sut 41 : Introduction to Inheritance G4 Define the term - FS ISPPU : D4c-22, Mark 6} Inhetitnce is propery ia which data members and Some class are used by sme oes cae, + Inhertance allows the resity ofthe code in Cos Definition: ‘rember functions of faz jase and Derived Classes (G2 Explain the term - Base and derived cue fas 4 Th sits fom which the date members and member fictions ‘5° ied by another classi called the base lam, + The clas which wes the proper. of b ‘8 ads om proper i calles dei ie clas and a he same tine ied clase table example 2Bh st can be deczed ass Sind cass The alow te ‘end clas toasts the pate data members of te anathe ss a t ss B can access the variable data, and vaviahle i prone oer of ete A. ies need or oing r+ Program include fod ae Bie is tnd oie A babe Aenean c na = & , ees 3 t pubic: ins subi x) ‘ A obits objact of lass A ‘ihe private data of clase A i accnesed incase B - 1 data contatna § and x contains 2 retum abate > » se min) ‘ Boba cout << “Recut ie = "<< chia ea: etch ‘Output “tle Eierng bit ened Programming oe 24 Explain diferent pes of inheritance ‘Aas + + Vanous sper of inheritance ate ‘Single inbertance Multilevel inheritance Hybrid inheritance ce with sultable example. ar (SPU : Dec.22, Marks 6) In single inheritance there on ‘Tht is the most common farm of iahertanse arent per detved las Serves Fig. @.8.1 Single Inheritance (c++ Program include uring namespace st clare Base ‘ old set atin 2) 4 2 ‘oid show x() cout <\n\e Base clase." TA Gate for Engnerng Sens | \ | ect Onn Potamnie 1:4 Ines an meron > : ase decved : pubic Base ‘ ub old ot_yine a) ‘ > etd stows 2970 « coutcnlnle Dove lass" couteenniex = ee , d ‘ne mind ‘ ‘orivea ob ceut<"\n Bator the vals of y"; cin > (bjaet xx/inores base clase ‘Sbjaet yh // cess member of derived clase fobjshow x0ji/nhorts base class ‘bj show py) // accuse member of derived cass rerum 0: } output Enter the value of «10 a=S—_oO rere “Tat npr Set jc rene Programming ee Inhertionce and Petymerphiin Eoter the value of y 20 Base class .. Derived cies y= 20 26 Explain multi-tevel iaheritance, ‘Ans. When a derived class is derived from a base clas which itself is Gerived class then at ype of inheritance is called malin Inheritance * Fos example - If clas A is @ base class and class B is another clase shch is desived fom A, similly there is another clas © being derives om class B then such a derivation leads to. mutlerst intentence. ‘+ The implementation of multilevel inheritance is a6 ven below « casa | ease cial telieal Fig. @.6.1 Multiovel inhortance etonentmening _t-f___ ite toys c++ Program nohude using namespace sta clase A, « rotacte: int x: ublie ‘old tate): veld put_a0: » vote Asgot_a(int a) ‘old got_btin) vole put bg); » vole Bgot_btint by > vold Brut 50) { cout<<"\n The value of y ts "<: void Ciena ‘ (Per aUi//member of clas A ‘Pur_bOY/member of caus B Source" Tha value of foe } st main « C obi/fonject of ciage © Heconesing clase A momber via chet of laze © ‘obj. gee_alt0%: ‘Hecoweeing clase B member via object of elast C ob) get B20) Uiassoecing class C manor via object of class C 0b) eplay0: ‘outs endl 2 Output ‘The value of y = 20 ‘The value of i= 30 “+ The implementation of multiple inheritance is as shown in Fig. Q7.1 7 Gee for Engnerng Sens ft rene rogremet [=] c++ Programe leing namespace st ‘lage Operation y » ‘tase Gourput ‘ pane: ‘void alepiay (int vold Coutputsaispiay (iat 8) ‘ cout << 1 << end: “TG or Ecc ts he enn Pgrmnine 11 tet a Pome ‘Operation and Cont ‘ae product: pube Operation. pub Couper ‘SAE eum: pubic Operation, pubic Counput nt fezion () recum o + yy =: main ( roduct ob_pr/ebiet of product class ‘som ob_eumi//abject of eum clans (pe eot values (1020) bi_eum.set_valoes (2020); ‘souk<<"\n The product of 10 and 20 ig “<- Pinclade ing namespace sta: public: // Public access speciior int xg // Public attribute: void funt() 4 cour<<"Public function’: d rorecte: ies rene Programing 4:12 ___ Inherent Pm void font) ‘ > private: // Prvase access epacisir itz) // Pavate eure eid 030 « cout ‘a.12 Discuss the role of access spcifiers in inheritance and show heir visibly when they. are ir‘erted ss public, private snd Protected. ‘BETSPPU : Juno-z2, Marks 6 ‘Ane. + Refer QL : “4.7: Multiple Inheritance suitable example to demonstrate multiple inheritance, 2.13 Gre ‘Ans. + Refer Q7, ern nl —— eS seatemuliple FL SPPU : May, Marks 6 + Multiple inheritance: Refer Q27 Ambigiy + Anna ne he em a re mais asin tis also called as diamond Problem, name + Consider the following Fig, 0.141 Fig. @.14.4 Ambigulty In inheritance ‘+ Now the code forthe above design can be writen as class A { public: oad); write » — es EE tes Olena roaring —_ clase Bpublic A ‘ publ ra rte: » clase Crpublic A ‘ public wrth k ‘lass Dipublc B.publc © q ube: wrt: h + We ty to inherit the write fincton of base els Ai ay CC, which will be alight. Bu if ey to use the wot an D then the compiler will generate enor, betes mes know which writeQ function to choose wheter af ces Bata ‘This ambiguiy occurs because the compiler undead tea Dis derived ffom both class B and class C and bos ef en have the versions of write function. So the A elas pao inside the clase D object + The compiler will complain when compiling he code ent for member "wrte" is ambiguous, becatse Ht cant fig to cll the method write) ffom AZIBED or fom A:sC3D. * That means the programming language doesnot allow 8 the concept as given inthe design + G+ allows the solving of this problem by using vit This proces is also called as diinheritance * fh gtder to prevent the cempllr fom givag era i # of inheritance we use the keyword virtual. Tit ms St rade viral “roe je net Programing 416 inert ot Papi, an |. voi ming function with exampte, t SSPISPPU : June-22, Marks] soriveds obs ‘Ams: Virtual base class: In order to prevent the compiler fom giving obj 10; an error due to ambiguty in sultiple path cr muliple ihertonee oe | obi SUS Ra me eo eee ish cs ey he nah te ea Bate cate a mata eat ere ces rer cumersatal at mane | : ‘lass derivodt-virue! pubite base ‘ ublic: me b Class deriveaz-irwal public hase utc ie 2 ‘1aeriveds is inherited tom derived and derived? ‘Pox oniy one copy of base claea ia snherited. lass derived3:public derived%,public derived? « int eum) ‘ sotam 4445 > SS =< “AG or Engng Sens paves fost" The sum = “a Onna Programming 1 takertance and Prag hts 411 Pointers to Objects Werte 4 +e program fo dem ate polnter to abject cong te 8 same C2 pe stam 1 Wish & poler to objet entents sing the pointor te object b + maint) rest obj(100), “ptk_obj strobj = fob): out <<'Valuo obtained using pointer to object is ."<getVal()< ‘using namespace eta class base t public: nt ‘baso(int x)//eonstructor ‘ = Guide for Ege nec ete Progra 4:19 __Inbertnee nd Petmerpon iran vod function) << Thencton = wn] cout << "Using base version of fineton!) b clues derived? | public bate pute Veonatrsetr for objec cr erivediint x) bawe(n)( ‘void fuetlon() cout < "Using derived’ version of function) cout < 14 een ) »: clase derived? public bate 4 ube: ‘denveda(int xy bawe(x){}//eanstnuctot let cbect creation void fonetont) ‘ cout << “Using derived’ version of function) cout << #4 << “8 ) Se main 7 Guia for Engng Saran ject nent Programming Intend Pobmpin base osu: dared: a_objsum) enved2 a2_objsum petaby base abjecr's address p>functon): age claee function 1p = Aat_objiderivedl object's address ‘pe Rinatoal) derived class function) = Ma2_o5j/dactved2 object's addrars pehincton() /ctved2 class function’) output ates Some combat § Unig base version of function): 8 fog dacoradt’s vcaton of functon(): 10 ning dactreda's version of function’) 25 219 Dittervatiats compile time and ran sme polymorphism. ana, Oe [Se Ne Compie time polymorph | Rua time polymorphism | as cal te tnctons having | The cll othe functions having me ms ame is sctved at | same same i eed aH “Sa fr Engering a ee Orlenes Preramming 4.413 : Pure Virtual Functions 2.20 Write short note on - Pure virtual fanetion. Ans: 6A pure viet! function i a viru fimcton which is © be implemented by derived clase. The clas tht confains he pute viual function is called the abstract clas. + The pure vimual functions are declared using pure specifier ie. = 0 + Following program demonstrate the ute of pure vial function, The class A is an abstract class in which the pure visual funcion Display() ie declared. This function is overridden by the two dered classes = class Band class C. ‘Program for demonstrating the pure virtual function ‘#snciuae susing namespace sta: clace A { ‘pabue virmual void Display()=0: » clase B': public A £ publi: vold Display‘) ‘ cout <"\n In Derived Class B'<Displey0 > output mn Derived Class 8 m Derived Class C Program explanation : The tase class A derived peo sanes rey Band C. In class A, the pure virual fincuon Display is dee! assigning = 0. “The Display function ie overidden in class B and class C “4.14 + Abstract Base Class ‘with sulable xe 2.21 What ie abstract bate class ? Expl Ans. + + Absrac clas i a elas which is mostly uaed as bie ct) Contains atleast one pure virtual fuuction, Abstract clases to specity an interface that aust be implemented by all obelaies See eee eee eee eee tect vented Prgramming___4-28 _teranceandPobmorphim 4+ The virwal function is funtion having nobody but specified by = 0 ‘Tis tlle the compiler that nobody existe for this imction relative to the base class, When a virtua! fiction is made pure, it frees ay erved class to override it. If a derived lass does not an eror osirs, Thus, making a viral function pare is a way Yo guarantee ‘hat a derived elass will provide its own redefinition For example ‘include class ares 4 double dim, ima: public: void setarea(double a1, doube 42) 4 imi = at: ‘m2 = a2; > void gotaim(double &at, double &2) « i = dim; 62 = aim y virtual double getarea() = 0; // pure virtual function bs ccd “A Gul for Engineering Seudents ect nee roaring ou otatenat, 22), return dt * 2 » clase tangle: publi area ‘ ‘double gotaret) ‘ oubte di, 2: ‘getaim(at, 2); rotum 08 * dt * 42 ‘wianglo = sn a2; oout<<"\n Enter The wo dimensions for eaeslating area of square cin>>nuumt>>muid, seetaroa(nam?num2} pee, cout << “Area of oquare ig: " << p->getareal) << ‘\n' cout<<"\a Enter The two dimensions for caleuating area of ‘wiangle in>>mumt>>num2: ‘esetarea(numn? mama); P= et, ‘cout << "Aree of Tangle is: * << p->gotaroal) < Using namespace etd clase Base ‘ ube: Based) ( Virtual destructor. ‘A Guar EginearngSdeas a oo oN renee ee mmm \one<"\n Calling Base clase Destructor’ an Dee publ Base ‘ ptt ered \ couee<"n Galing Derived class Constructor ) paved foetal Calling Derived class Destructor’, , x tne saind t ‘ase “bi=new Desvodo; objec exon dal sur, , Output Calling Base class Constructor Cling Derived class Constructor Calling Derived class Destructor Calling Base class Destructor s jet rete Proranntng 4-27 __tnertance and Pobmarphio Ose Oren Poeramming 4:28 tntartance ond Pemrphion 4.47 : Early and Late Binding Dersend a beepiay 2.24 Explain the following Early binding aad late binding aisplay 4. Early binding : This is + ype of binding in which the fenetion call , 4s associated with the function definition at the compile time cay, ‘Output Hence tis type of binding is also called as carly binding. Folowng 1m base class old disay) ‘ cout <"\n In base ol ? r ‘ ube void aiepiay() ‘ ‘cout<-<"\n In derived clase" <dieplayo: 3 output In base clase In derived clase 2.25 . Give the difference between early binding and late binding. 1 (SPPU : D4c.-22, Marks 5] ‘Late binding ‘Sie binding happens a the | Lae binding happens tran ‘State binding i leo elle as| Late bindng is aio exiled we | cy id sami binding | 3 | There i owe of vant | The via on | scion nis ype of | dynamic Winding binging, 4] te is more fiint dan dn | Te move ibe tan te exly | ne binding as extra level of | binding | inceston i voted in a | | binding. was 14 Gule forEngnerngStudene ier cass and contained cas, dns «+ Wh an cj fon lit presen ie aot cna cer words if he objet of one cist will be « member of see then at Ope of relntip between the casicr called una + The slaionship between these clasts is caled has elatonstip, + Following program ihutates the concept of container cast al contained class = (c+ Program ‘#inctude sing namaepace a lass Engine ‘ ube: void aiapiay) ‘ cout << \oThis is Engine class’ ) »: 1 Container class lass Car { 1/ cresting object of Engine - contained sbiect Engine 0; able: 1/ constructor Cart) ‘ Cout<-<"\n This is Car Class"; edisplay0; "as oan A ‘y y Objet Ortented Programming semen 1) creating abject of Car care Output This te Car Clase This ie Rrgine class 4.19 : Singleton Class 27 Explain the conc program. ‘Ams: « Singleton clas is a type of class that as only one instance and it provides global point of access to it + The concept of singleton class is iustrated by following figure - 3 of singleton class with the help of C++ |__faamere sie enor sk ier Orel Progrmeing a » ube stati Singleton “getnatancat)_ A senance = hew Singlaon ? ‘old goer zn) : = > » ‘isitialie the pointer of natance to 2610 Singleton *Singietonsinstance = 0 a) ‘ Singlaton “obj = ob) >getineancel cout gee: ‘obj > eeetfum(ti) cout <"\nAter:“<-gettu: output Before: 0 ‘Ager: 111 ENDS Templates, Namespaces | and Exception Handling dos 2,1 The everieprogramming is equ ht elows to we ‘the code for any data = a 7 {Ye elements. The semplate ie sed a oo + The above two finetions are scaly Metical but thé function onthe Jef side is for comparing the two integer numbers snd the fonction on the right hand side is for comparing the two double ‘jype mies Now we want the generic programming algeritim which will perf the functionality of both the data ype elements. Hence we can reper lt and double by a type T. Here is an example = inctude ciotream> ‘using namespace eva tompleto //7 holps us to taka any type of data ‘Tmax(T l.T ight) eb Moatsigh) : tun oat ‘ tmx masa { ti coute"inlt Comparison of Two integer mumber Li coute<"\n Enter fer integer number" Pe ‘cout<"\n Rater second integer number" pe eins mince on tor maxl mani in2)//peasng two ncoger veins est" The Maxim integer number i" nat <a2; Aout max2-=man(41,42}i/ peseing two doable van , 5.2 : Function Template and Class Template 22 Write a C++ program involving feaction template, [EIF{SPPU : June22, Dee-22, Marks 6 Ans: «In finction template, the same finctonal code with ons data type elements canbe baled. ‘The syntax of function template isa flows template ‘las cinername 4 ‘dy of clans » fn be of any dan ype. Thon template class ve example Tine member wis dei ug class template is tember finction is defined. The “omplete progras win fe ivan below. “Pincha ing nameapace wd: template clean T> tana Compare { /Pwntng th ‘Ta bff 00 hae He pu ‘Compara (F tet, T wacom) ‘ asta ymecond > °F mas (td th nn in nix function definition ve unt of voanpiat inne tanplaia 4nan 0) et Oot Progen ming ne Bor srr Ser Beamc00.09) = nee mens 9 MNES) w cone Sem (100,60) = 100 Compare 06y1(100,60) 2S S80 integer values wil be compare ine rel values by declaring appropriate cies Fanction template ‘multiple parameters. Write a Cre SSP(SPPU : June-22, Marka 7) Ss —_—_—___ ae fr Exc Son ; sa nti ; Toca eM Paes Sern cone Using class template me can arte 4 clas ong template parameters as pes Pe Ys. Function Temp function ove; ei a #imctude >i; > ‘cout<<\n The minimum element ofan array is “< 1 Gul for Enghecring Sudeos ict rete Programming 5-8 end pinch ‘term egos van n Bota me integer vaboe 5 Enter the itager value 2 ‘he min olen of an ay ie Enter tho soa vier 10:0 ota the soa valine Enter te eal vaues sat Enter 2h oa valves Enter the coal values 27 ‘The minimum element of en acay is = 5.5, 5.4: Introduction to Namespaces QS Explain the concept of mamespaces, E[SPPU : June-22, Dec-22, Marks 8) ‘Ans. : + Namespaces are used to group the entities like cass, variables, objects, finetion under a name ‘+ The namespaces help to divide global scope into sub-scopes, here ‘each sub-scope has + Example : ‘include using namespace sa Gee far gern Ss a Tenneson Rae output 8 Witt ad namespace ? ‘Ans: + All the files in the Co+ sundard library declare all of ts Sites Cathe the atd namespace That ie why in the Cor progam te 2a namespace 1 declared as follows sting namespace st + This stement se uted othe program Which uses any enty declared 5.5 : Rules of Namespaces 2.10 Ralet the rates of namespaces ‘Ama: + Following are the rules of namespaces 1) The namespece must be defined using the Keyword namespace Se dvace nee foepe 2 nde a tanned eamernce 2 2 Ine maracas. Thmy me se mule ls py tee mage dniaton do ot hare me atin gag L_ revvate) — 5.6 : Basics of Exception Handling | 0.11 What s exception handilog 7 Ant: + Definition : When any unavoldable Sxcumtance it ape fer) Setur im our progrem then exceptions we can! bs onto to apecial functions caled handlers. Ths provdne ibe Banding mechanism which is known as exception Baadllog, + The purpoe of exception handling mechanism it © dem me > ‘he exceptional situations so that appropriate action oan be 32 Give the aitference betwe js ree come ae sing cen a: Templates, Namespaces Qietonmed Pepenming 5211 rea tO grmint st reaps | + | Regn cries or saps | Pagan pos ey | voting when nso sous | menage ene a coreme/ Lf fF i Shee | | Berman ve comet ow the geen ear aemnae = | ‘is fixed by the programmer, | using try, catch and throw ioe esta | oa - poe en | «| emee competi er | Haein tn ow or == 3.7 : Exception Handling Mechanism 2.13 Explain the exception handling mechantsm. ‘Ans.: + C++ exception handling aechanison makes use of thee keywords - try, enteh and throw. The try represents the block of SMatements in which there are chances of occuring, some exceptionl conditions. + When exception detected itis down using the throw statement. + There enists @ block of statements in Which the exception thrown ie handled appropriately. This lock is called eatch block. + Following Sgures illustrates the concept of exception handling = Pan Peper |< meee a oer ] career ae < saree Fig, 0.13.1 (a) try-catch mechanism Fig, 421 (b) throw.ry-catch mechanlem + Mainly exe pion haniing is done withthe help of tes keywords 1, cach an tow. The ty and coh block is as shown below = wy « ‘throw exception: WH excoption i some value 1) tho portion ofthe code thet is tobe monitored for exot 17 detection. + catch exgument) { /featch block softy handles the ceception 3 ‘+ The ay’ block contsins the portion of the program that is to be examined for error detection, If an exception (Le. error) occurs in this Dlock then it is throvm using row. Using catch the exception is cemught and processed. If ry Dlock contains all the code inchued in ‘main then effectively the complete program must be scamed for ‘errors. Any exception is eaught by the catch block: This catch block shoul be immediately followed by the ty block. efor Bening Sos oz “Gale or Engncring Studer, Femplt, Nomepaces Seemed roremming __$-1_and xeon Hing handle divide by 2ere exception, yhrowing and Catching Mechanism| sm in Ch, Write a Crt 10 14 Explain exception boriding mech [ar[SPPU : June-2, Marks 7) ‘Ape. : Exception handling mechanism : Refer Q.13, C+ Program for hasidting divide by zero exception ‘Tes purpose of exception handling isto handle abnormal events, The following program illstraies that in division opecation the denominator Value should not be zero and if at alli is zero then how to handle such enor Progtam to Randle divide by sero aor using exception handing mechani double, void divide(double, double); cout << ‘Enter nutnerator: cout << “Enter denominator :% > oe t wy t id divide(douiio a, double b) if =" 0) throw b; // divide-by-20r0 cout <= "Result: << a/b << endl: // or non sere value ——_—_——_—_eeee —- :for Enginering Seana ject Ove > 2a (dui) ‘ ‘cout << "Can't divide by zero.\n"; ) ) output oor mimertor 10 free denominator 8 Gan dnt by tr. 5.9 : Specifying Exceptions Q.18 Write short note on - Exception specification, ‘Ans. «+ Exception specification is used t0 provide i nim the kind of exceptions that can be thrown Fer manpi, vold £1) throw(int,double) Here, the function £0) throws an exception of type ine as theows an exception with a different type(here other tint ‘ype),sither directly or indirectly, it cannot be caught yp ouble type handler. ‘An exception specification with en empty throw, old £0 throw () tcl the compiler that the function does not tow any ese For example - ing exception specifiotion include [is SPet0N0 throw (int double) Program for demonstrat thro w(12. 34), Object Oriented Programming ‘ ) cntentine 9 c cout<'<"Handlng the integer value <1 cena d emtehidouble 1) ‘ cout<.<'Handhing the doubla value “= <.< eaten) ‘ ) output Handing the double value 12:34 —— 5.10 : Multiple Exceptions 2.46 Explain how to ase multiple catch statements ? Give Coe program. Ans. : + The exception handler is declared by the keyword catch which is responsible to handle the exception thrown by the iy Nock Nery the code within the eatch statement attempts to rectify the enor ty aking Appropriate action. When an exception occurs then the contl transferred to the catch block and af that use my block ss temnated There can be multiple exceptions in multiple eateh statements with coe Dy block. Following is a structure of the program when maitple cach Mocks are allowed, ct Oren Programming sue cetoniaatatypet ara) ‘ > ‘he program \lhstrating vuluple cath statements is us shown below - lasing nameepace et void functoelint sum) wy ‘nae ‘hzow num, ise uaows “Vale a nao" Ae fo Bogner Sus Ob Onlented Programming Tents, a Nona TL rd ‘Pop cate for sng yack et Od Peri Topi eatehtint 4) Example a eae tute conan : 800 for munber ie hades * <<“ Poataeceutgne mtehcone chat at sig mnpac : ans Peon cat << ‘ Soi << "cope fo: ing ha roe ; hae } pone ft maing ha eco ; Pernt cout << “Start” < ‘Ans. The fos class declares the values that aze used to sto Yinchudeatring> a = "ts for Exgeg Soe = F rate for Ets ee Fallowing ae the format fags slong with their meaning = Meaning i ering i Nag the ouput becomes et jlied Foe mata [pms se rc at stowtare | Ife hen shows bse indiatnor example OX fore) | sowpet | Tksowe + sign befvepunve number [DOP Sh owe cn ei ad ing ing |[teete on set shows exponen format on Roang pont aumbes See _| On st shows fixed forma! on floating pont tubers [Precise | Bosieas can bea wing pve of [set colans can be 3: woe 2s sting this ing upper cate A‘ are wed for hex vlucs and E| | toe eerie values, + Ths oct, dee and hex felds are collectively refered as batefleld. Tae Jef, right and internal felds can be refered as adjusteld, similary sclentiie and fixed can be referred os lose The setfO function is used to set the fe 1 clear the fg. ‘and unsetfQ finetion is used | Fer cxample, if we want the text to be displayed on the console ould be right justified then - cout eins); cout<-<"Tovinkle Twsnlee Litie Stars ae “A Gul for Enginering Sudo ee ee Following (8 program that shows how several format lags can be te netude output 100.76 noo inaia 100, 20-10 100 41.00750-+02 hello India 64 a ees ++100.000000 0.22 What are VO manipulators ? Wi demonstrate it ie 8 CH programs (0 (E& [SPPU : Dos.-22, Marks 51 ‘Ans. : © Manipulators are the operators in C++ that are used for formatting the output. Various commonly used manipulators are setw, ‘endl and set =a “A Gul for Engineering Seis ‘jet Olen Programming se28 1 The setw is used to set the minimum field with. We justified numbers using setw operator. Note that the defined in file, ++ Program #inctude include using namespace sta: ‘nt main) int amaaas.p e233 cout-<<"Using estiv(30)\n"; ‘cout: fincludeiomanip> ‘sing namespace std; ft main) ‘ ‘out <<"Thls Is frst ne include using namspace sta; ss main) cout< in the pom. 1 defines several classes, including ifstream, ofstream sod- Stream. These classes are derived from ios, so stream, ofstream and Stream Ihave access to all operations defin.a by los. While using file LO we reed to do fllowing tasks - 1. To crete an input steam, declare an objet of type Ustream. 2, To ereate an output stream, declare an object of type ostream, 3, To create an inpuvoupur stream, declare an object of ype fstream, 6.2 + Opening and Closing Files Q2 Write and explain the file open function. cone of the ‘Ans. «The file operations are associated withthe object of Classes ; ream, ofstream of ftream. Hence we need to cree en object of the corresponding clas. SMANNTPIN L T ae 7 retay om ran penne me oe coma ening fp demoyed an tad We con Sn open) fanctin ing the above given yan w= teen ob, 2 epen"sampla ni sono joe binary) Tox means he fle aazple bin t opened for ute operation in ary ede. Thus we can combine the fag ung OR operat) + Tee & open? 6 boolean fanecon tht can be used 10 check whathar the Siew epee of non ‘or exaaipte cout <"Fis ws Succosstly openes fr operations tro eagenng Son, the deren herveen spoming + Me wih conercing pen terion ea (PPL ne, Oe. Ma Ams 1 Opening a fle using constnsctorhineion fe steam constr the fle wtrenm abject n cned Sap ‘aut w open the fl for vending then ot tense ieee Imyhie obect of apt wre ia, + Opening a fe wing Ci single fle to be Opened ing single neon 2. Opening « Mle using open function + The open fnetion of gle LEAD 6 used 10 open She des Sg "Byfle open npr oe tn ‘yaa Sowa) When we want wo open mul open faction, eles one ater the oer en (OF Explain fe functions for txt fe and binary Ae operatnas SGP(SPPU - June-22, Dee, tire Ams 1) Open fle function | Reser Q.2 LEMME Me faction : To cote the fe the mcberfinctan sl ‘ed, The clone fneton "akes no parameter and reruns value Metis ee We can mae ae Meanie IME tye foggy, feo Input ob) waa Hor) Svariab asoartaiey, memory Bock ONDUR_ODI. wre (ctr) & yy * Memmameny Sock mut be ge eat roca Mosk act ne «ter tn wick a Bain ‘be ten inthe Tle can es an Moved or the data to 6.8 : Detecting End OFFite (EOF) Qe aplain how to detect end of de mle ? Ams: + For finding end of the fs we | a member Ainction of jos clase i ay For example 1 weatlo, eet (1! = 0) ‘ ut <<" You are at the end of the fie 20 back "INDIO, m2 of (vaably se e0fl) function. This fanston dof fle Ts encountered ten i Q7 Write a program using the open (), fanctions 10 open and rea Aas. : ‘inchide achude using namespace etd ‘a mainivoid) t sof ( ) and geting () file contents line by line. char Slsname(70}; Tat forEnpnerng Ses et ene Programming 6-4 har Pein) ‘har Second net} ‘Soar ThedLina0 sin >Blenane How are you? Enjoy" LiFel tt \ LAC TO Wadena CRLF) | UIE Ge for Eonaring Stns One Onented Programing 6 Working with Piles Output Fnter the ¥ilenone to be openeds ANput. Ext r roy Soemirarepersies mae 8 Write a C++ program to read the-contents ‘ofa text fl, Ans: ‘#rnctude inctude inelude ‘using namespace std ‘nt main) ra otreat tn ‘char Detal60h; inopont'Semplo dat, ston) t 17 Pest an onc and ext corr << "Sample.dat could not be opened for reading! << endl, exit) y ‘coutc<"The Contante of te file are..< include fetream> #inchude ‘using namespace std: ft maing ‘ ‘bar Datale0} int wo=0; stream i obj {n objopent'Odd.dat’), ‘n_objread((char “)&Date. sooliData)); “A Gn for Erinn So — etinetDatn 8), patie ‘outs "yn Number of Characters un Number of Word "= Wey » 210 Wate ‘sumbers tn another ll, inctude #incude Using namespace ma; ‘at maing ¢ ‘stream snfla ofstream outsie: ‘nile. open'Sampla.dat’ outta. open Mayourput. dat”) ‘char output: Winsie~=NULL) € ‘cout <"Error'< Statement 1 Statement 2 Statement 3 output Following are the contents of Myoutputdat Ale, StatementlStatement2Stsement3 Ser tains fle handling methods of C++ waite © program sid ‘plain how 9 merge the contents of two files lave one fa ‘ABs : Following is simple C++ program in which we have cemed ny fice namely ~ cmp.dat and deptdat. The contents of both the Re ‘ead and merged into the third file named Combined dt, #inchuda- include ‘cout<-<\n The contents of mp dt Se are writen. ‘a ebjaloro0s ‘a sbjopent deptdar; ‘cout<.<"\n The contonts of deptdat fe are vite. ‘went ob) ‘2 ob. gettinetData 80) out obj trelosed: return 8; » Program explanation : 1m shove program, intlly the empudat file i fempalat fle Is opened ina read mode and {Be Combined dat is opened in writing mode. The contents ae read ffom {spdat and written in the Combined.dut. Similarly, the deptdat fle =—— eat “4 Gae for gnering Sane fc rete Prgramming » ering it Fes ‘opened in read mode and welt in Combinedsdat, Al sese Hes are Combineddet file is opened in read mode and ‘he merged contents are displayed on the console [6A : File Pointers and Manipulator ‘he seek and fell operations of file handling'tn deta 1 [SPPU : Dec-22, Maris 6] ‘Ans. : +The file pointers ar uted for locating the positon in the Sie "+ Wit each fle object there are two pointers associated with it.The get Dolnter and put pelater. Thess pointers barcally return.the curent {et posiion and trent put portion. ‘While performing file operaons, we must be able to reach at any desced rositon inside the fle, For thie purpose there are two commonly used Fintions = 1) s00k : ‘The see: operation is using two functions seek and seckp. 4 sea mans get pointer of specific location for reading of record 4 seekp means get pointer of specific location for writing of cecord. ‘The symtae of sek it seek (fet, reference - postion) seek (ole eference - position); whet, offset is any constant speciMing the location reference = poston is for specitjing beginning, end or curent position, ean be specific a, Jos: beg for bepnaing locaton fos: end frend of le 2) toll: This function tells us the curent position, For example safle tel = gives eument postion of get poate (Gor reading the recor), safle whe. O + fieranng ue secon ees “A Gale for Engineering Smdents et orem mening bas — Prien, ay 6.5 : Updating Flie terroam seqhi; seala opon("EMP_DAT"jo:in{iorout|log:bnary, ‘ cout >Recorde name: | ‘cout <"\n Enter Emp_1D:* cen> >Records.emnp ds coute<"\n Enter lary: ‘cin>>Recordawalary: 44 Write a CH pro FAM Tor evfrmn fe handing operations on Employee database, 7 ce organization #inctude ‘#include inctude ‘thon wrt the record co #inckade seataite( (char) Record sano Records) *#ingladu coute<"\abo you want to add more tecrdy? Fiockidesetdlban> ee eo sete lose t : ‘typedef struct EMPLOYEE “This ecm struct i erth aque ‘Yold EMP_CLASS:Diepiay) Fores 4 char ninatoi Cae DC trosam seat; istemp ia 7S em E ase sate ope"BF DAT tories ‘pomtocng tn nes ae Ee ag ni teat soon ou-boa ue tout<<"n Th Conon ot fl te cent; oid Crete tend ta recor questa void Disp ‘whanau har aoord atnoRecota) void Update(); 4 ott Deter Sanilac en void Append(); t Denn cow <"alane:“ cRacods name x void EMP_CLASS::Cr £ cout<<"\nEmp_ID:"< Heateuataottut to locate the dasized record tn the fs Int otfeot=poo"sesot Ree}: sease eeip(otset)//eoeking the desired record for dlation ‘void EMP_CLASS:Upaute0, cout >Recorde name; TEETER coute<"\n Emp 1a: cin>>Racorde omp_la: ate ios:in iossoxt|tosebinary, suqge. cook (0.i5e:b09): out <"\n Salary: cin >Recerdaselary, ‘a io; seqtle write((char")&Rocords eizol(Recorde))<Recorde name, ‘cout<<"\aEp. ID; "cin>>Racordiomp ‘out <"nSaley: in >Racords lary fle. wrto( chat") Racers wieof(Rocoeda)) ‘eaiee(0):/roposttion te waroptions) ect coca) ‘sout<<"\n Tho record ie Appendedits ‘stcoam seafie, tet Spon ‘our<<"\n Enter the Emp_ID for coercing she record cn >ia seafle open(EMP DAT ot:ate|iogsin|ion:outlioe: binary), oat. 200k (0:beq) ‘wile(segie soudl(char *)aRecotds sasotiRecords)) 4 a= =Records amp. ja) ‘ break, > ¥ ew Working we ry coutcen Main Mors "< (66 : Error Handling During File Operations 18 Explain error handling during file operations, S@PISPPU : June-22, Dec.22, Marks 5) aus: + When eror occurs in file handling, flags are set in the state sssrding to the general category of the error. Flags and theit cree segares are summarized in the following table [wae neg seate ing anes [teat | Ts wn ng nest sna ooo port tmopdoleatvtereaiial ‘ack | Tan sf ners a nem bette tewion tesa [tus | ss ug tt ip op | losseofbit | This state flag indicates thatthe input operation resched | cd of input sauencs + When enor occurs while performing file VO operations, the appropriate message is displayed and then the file terminates Following program ilustrates ow to use appropriate eror messages on corresponding read and write error-causing situations, clude Pinctude using namespace std; Praciude ‘const int MAX = 10, SS es “A Gull for Enpincering Soudets Mkt Ore Prpamaing Int arraytIMAx| = ( 1020; int aray2iMAxi; ‘nt main() { tatreem os; //oreate output stream Of.open(ANWest da’ fos:trunc | lo:binary}//Opening fe 1€ (los) ‘ 90.40.50 et << "Could not open output Alen: //Error Handling ext(); > ‘cout << "Witing the contents tothe f.\n\ ‘os. wit((chas")aray!,sizooflarray)}//writing ‘array to fle ‘(os) « csr << "Could net write to fle //Error handing ext); » os-loee(; /Jelose the fle ‘ustream i; //reete input stream for reading the contents from 10 sopent dost dat, tossbinary; ‘(s) { cer << "Could not open input fle\s;/fBrror Handling ox): > ‘cout << "Roading the contents from the fe ‘nsond((char*)Rerray2.sieeof(erray2); //reading the contents in 1) setae array array! ce) { (err << "Could not read fom fa\n';/fBeror Handling oxt(t); “sie Fagen Ses te ne Precram f(a} = 05} < MAK: 12+) /ehocn gana Winting the canteste to the fie sading the conte 10 20 9 40 5% output 8 fom the hte 1 Gn or Engin rng Sons ‘me 2 Hous {Stain Man ? Instructions to the candidates 1D) Answer Q.1 oF Q2, Q3 oF Q4, Q5 oF Q6, 2.7 or Os 2) Neat diagrams must be draun wherever necessary, 3) Figures to the right side indicate full marks. 4) Use of calculator is allowed, 5) Assume suitable data, if necessary G4 a) Whet is operator overloading ? Why if necessary to oe Sn operator ? (Refer Q.4 of Chapter - 3) t 1b) White « program in Cr+ to use scope resolution operete, Giefer 0.28 of Chapter - 1) | fare the merits and demerits of Chapter - 2) oR for over loading operators, ©) What is friend function ? What ‘sing the frend function ? (Refer Qs G2 9) Wht are the rules Mefer Q.3 of Chapter - 3) ca mot be overloaded ? Write ste Gaetan Creme 20 that i cn ad too complex munibon (Refer Q.10 of Chapter - 3) ‘of Chapter - 3) 23 a) Explain virtual base class ond (Refer Q.45 of Chapter - 4) wig Stl erty Qston apes nia ee rts eo ha ae ef eter O.1 and Q. of Chapter &) ‘6 ©) Discuss the xy coc inertance promotes satamre rene, sees te dung program deceopment an haps move one eter 0.10 of Chapter =) tt 4 a) Wet the ambiguity tine owe i oan be overcome. Explain sith ey eter O28 of Chapter) ‘ites in multe inheritence 7 pe o D) What ae tines of. (Refer Q.8 of Chapter - 4) zu 28 8) Writea cu Poem icing & nton tmp (Refer Q.2 of Chapter ss o ey b) Expleix exception handling mechanism in Cot 7 Write a Program in Ce to handle divide by zero exception Refer 0.14 of Chapter ~s) mn Papin class template and futon template wih example Refer Q.3 of Chapter -5) 8 oR 2 9) Explain class template using multiple parameters ? White a yresram in Ces, Refer Q4 of Chapter - 5) m1 ©) Explain namespace with expe, (Refer 0. of Chapter 3) 8 2), et stream ? Explain types of streams solable in Co Wefer 0.18 of Chapter - 8) ‘8 ae ‘A Gale for Engng Su ject Onetd Pngamming 5-4 Lnerty Question Pape G7 0) hat fle made ? Explain any four modes supported by Co (eter Q3 of Chapter 6 a by Explain error handing daring fle operons (eter 0.5 0f Chapter = tsi ©). What i the diernce beac opening fle with contruction {Sanction and open () faction, Refer Qed of Chapter = 6) fel or 8 a) Write program using the open (J, eof () and gene ( Sanctions to open ed rad fle content line by line (eter Q7 3f Chapter = el 1) Explain flection for text fle and binary file operations (Refer Q5 of Chapter - 6) m ©) Explain fle opening modes in deta (eter Q2 of Chapter - 6) [Becenaen-a0an woasaio|] Selved Pape i rane: 24 tow (Masia Mae 70 at a) What are the res for overloading operators ? Refer Q.3 of Chapter - 3) " 1) Write down a Ct» program to implement operator overloading Jor complex class, Refer Q.10 of Chapter ~ 3) ® ©) Explain friend function with example ‘eter WI of Chapter - 3) @ oR 7 Q2 a) What is operator overloading ? Write a program to overload nary opertor. (Refer Q.1 and Q.8 of Chapter - 3) Cy 1 Gute far Ergnotng Ste ‘String(eoist char* str = NULL); // constrictor ~Stxi9g0 { dolore; }/ destructor void pritt0 { cout << << end } ‘Setigistring(const char’ str) ‘ int eize = otron(ets) = new charleiea + 1) strepyte, 2) ? int maing) £ ‘String stri(tndia’): cour -<"\n Original String“ strl.printd;: cout=<"\a Printing String using Copy Constructor sstr2.print(): roturn 0; ont o dt lane po tnd pms nerd Progamming _S°8_ SE try tt” Der Fed IO rg SA ements that Poon a pia, ‘Rtn #8 © KFOUD of Keyword ix used 10 define the Sind tay s +The “sien” Tes a hantions do not Ue "ie a3) (Refer 0.26 and Q.5 of Chapter - 4) npn containment ad Heron ong ay, 1b) What 1 vieual faction ? Expat ow Wah p polymorphism. (Refer Q.18 of Chapter « 4) ‘e) Explain function over loading and function every (Refer Qu2 of Chapter - 1 and Q.18 of Chapter -4) OR asa) (Refer Q.1 and Q5 of Chapter - 0) 1) What polymorphism ? Explain sith example time polymorphism (Refer Q.16 and Q.18 of Chapter - 4) ©) Write copy constructor for employee cass in wh string class and date class are the data members. Pinchude using namespace ei class Date tne day, month, y ‘eepaibelel DIESEL na 1 What does inheritance mean int CH ? Give on exe hi ic ben Object Oriented Pr Obie Soted = ram feted Une Questor Pages 17 constructor Datag() Datetine intr, ity) dey = @, month =m; » void Print_detov) - clase Employee private: string name; Dato birth date; Public: UW eonstractor ‘ote Promanming 5-7 Seledeity Quon peje Employeo(atiing n, Dae bay am old print emp.intot) ‘ Det dite prise date > 11 copy conetsctor Employee(conat Employee other) ‘ Dinh datomoterbich dase y in mang { Date debt, 1, 202 Employee empi((AAA 222, do); coute-ata "+" Ble Copy Consist empt pet emp to) ‘Employee emp = emp: // ling oopy constructor cout<-e"nia + Aor Copy Constrctor ****"*< (Refer Q.8 of Chapter - 5) 6 ©) Compare late binding and carly binding, Refer 2.25 of Chapter - 4) 8 Q.7 a) Explain error handling during fle operation. Gefer 0.15 of Chapter - 6) 6 b) Write « program using put () to write characters toa file until, user entires a dollar sign (6 1 Guldefor EnginceingSades hie Cried penning 5 dae Eft so che ctecean sing namerpece at . lexan) sfetoum myfta ostpue x: // Open aut fe for wating ‘Cyt se open) ‘ . ‘te (am gette) aa = 8) mytie pute: Wate cnaracte 0 fe ‘nyble cose) // Cle output fle , > ©) Write « note om file operating modes (Refer Q3 of Chapter - 6) 8 on 28 a) Expiaie manipultors for fle honing in Cov (Refer Q22 of Chapter - 5) 8 1) ivhat is fle pointer ? Write « note on fle opening and fle losing, (Refer Q.13, QA and QS of Chapter - 6) 6 ©) Explain steam classes hierarchy for file handling in Cos, (Refer Q.19 of Chapter -5) ry END. = —____ eos ‘A Guide for Emincering Sates

You might also like