[go: up one dir, main page]

0% found this document useful (0 votes)
33 views40 pages

Oop

Uploaded by

adityaarnav.11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
33 views40 pages

Oop

Uploaded by

adityaarnav.11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 40
| | => 3 Polymorphism \| \\ === 3.1 : Introduction to Polymorphism at 18 Polymorphism ? W . «Polymorphism means many forms. {t is one of the impor. Orta atures OF oop. “ a4 polymorphism is basically an ability to create a variable a func’ gn object that has more than one form. sons or «The primary goal of polymorphism is an ability of the object of different types to respond to methods and data values usin; ffe lues by ig the same Q2 Differentiate between inheritance and Polymorphism |sr. No, Inheritance Polymorphism 1: . . : . | | Inheritance is a Property in which Polymorphism is ability for an ane ° the properties and object to used different forms, The Me ods of base class can be name of the function remains the lerived by the derived class. same but it can perform different tasks, : a“ a Various types of inheritance can Various types of polymorphism ar: be single inheritance, multiple + compile time polymorphism and inheritance, multilevel inheritance run time polymorphism. In and hybrid inheritance. compile time polymorphism there are two types of overloading possible, - functional overloading and operator overloading. In run time polymorphism there is a use of virtual function. “aq aject oriented Pe — overload ng ae write a crt program for ng @ Increme,, , +t ., ‘includ? ciostreamn” using nam space std; class coord { ae yill co-ordinate values public: coord( ) (x = OY = 0; }//constructor for obj coord(int i, int {x= iy ah }lconstructor with paren, int &f) (i= =H} void get_xy(int &i, coord operator++( );//anary operator overloading i i Overload ++ operator for coord class coord coord::operator+ +( ) { xt+; retum ‘this; //returning the current instance int main( ) { int x,y; cout<<"\n Enter the co-ordinates x and y ", ; cin>>x>>y; coord obj(x,y); ++obj; +obj; Calls coord operator++() obj.get_xy(x, y); coUut<<"The i imcrement as..."< fort eversing a given string. | oper" cc for displaying @ given string, 0 OS [SPPU ; May 2014, Marks 6] 0s. * 6 seningciass Jas lic char st11301 giringClass() { sropy(stt * "st grringClass(char s{]) { sropy(stt, 8): } StringClass operator+( { strcat(str, si.str); stroat(str, "\O"); ‘StringClass sl) Tetum str; ) friend ostream& operator< <(ostream gout, StringClass &s1) { outt <<"\nString: "<< 81.8th Tetum outt; } StringClas$ &s1) fiend i | istream& operator> > (istream gin, ‘A Guide for ‘Engineerin ‘smudens yenited POR” ont inn >761 87 orev sth 7 anreversed sting: ” << #.etr ee return i Output String: Hello J String : friends } Concatenated String ; int main) Enter string to revere a Reversed string : debe, seingClass 63( Hel), £2(iends"; serngClass 83.54 cout << siy/invokes << operator for display of string cout << s2;/invokes << operator for display of string <3 = s1 + 52;/invokes + operator for string concatenation, cout <<"\nConcatenated String: "<< s3.str; ‘cout << “\nEnter string to reverse: cin >> s4i//invokes >> operator for string reversal } Q8 What is operator overloading ? Overload the num operators + and / for complex numbers addition and division ‘Ans. : Operator overloading is defined as an ability to define a nev ‘meaning for an existing operator. — for overloading numerical operator + and / for ‘Bumbers addition and division*/ ‘include ‘using namespace std; {OE complex(float,flost), complex oBerAtor+ (comple complex Op@rator/ (complex, 2 plaxscomplex(float r,floas i) { real img=i : lex: | plex COMPBR:OpeTBC+ come complex temp; temp r0al=r0al+ obj eal; temp.img=img+obj.img; retum (temp); i complex complex::operator/ (complex obj) { complex temp; float new_temp; new_temp= (obj teal*obj.real) + (obj.img*ebj ng); temp.real= ((real*obj.real) + (img*obj.img))/nevr temp; temp.img=new_temp; return(temp); } ‘nt main() { Complex a(2,6); complex b(4,1); ‘complex ¢; crath; Cout<<"\n The addition of two complex numbers is. Cout< mst be member functions if they ae overoadeg ' soe and ~~ need special treatment because they are prefix op smal 0 operators te ' « Asigmen (=) shoul alvays be overloaded if an object dynanicg, | est bl allocates memory rman i an ot change the mumber of requied operands (unary, fn, — x=201 cout< <"\nValue of x: "< ‘explicit Test(int x) :Val(x) using namespace std; { cout << “\n Val= " << Val; }; class test { k private: int main() int abcd; { public: ‘Tet obj = 100; //Rrror: conversion from int to clase is not pots3# int sum(int.int); retum 0; int sum(int,int,int); ) ‘int sum(int int int,int); @) Mutable Keyword : Mutable keyword is used with the data mens int to everif the object of that class is cons Sesum(int aint b) { return (a+b); , Cr teet:eum(int aint b.int ¢) ‘A Guide for Engineering Sobers ese sum(nt aunt bat cnt) sot te ‘eum (arb+e~dh sot main) est ob int ab, dchoice: int result=0; cout <"\a\t\t Main Menu"; cout <*\n\t 1.Adaition of two numbers"; cout<<"\alt Addition of three numbers’ cout<<"\n\t 3 Addition of four numbers" > choice; switeh(choice) case 1: cout <<*\nEnter 2 numbers: "; cin >> a>>b resuk = obj sum(a.b); break, case 2; cout <<"\aEster 3 numbers: cn>>a>>b>>¢; result = obj sum(a.b); ‘break: ct8e 3: com <<*“\nEnter 4 = ca>>e>>boreos de result = obj sum(a,b.c,d); break; default: cout <<: AoW. . ‘break, tong Choice"; Output ' Main Menu 1.Addition of two , a ‘Addition of three numbers ; of four numbers Enter Your choice : 2 Enter 3 numbers: 10 20 30 result: 60 15 What is function » cot wa ample. overloading EF (SU : bee, nares 6 ‘Ans. Refer Q.13 and Q.14, , 0.16 Differentiate betw en . overriding. funct Ans. overtoading sr.No. Function overload Function overriding bay verriding occurs i= child class when the cid es fenton verdes pre clas face 1. Function overloading occurs in same class, cece Function overloading uring compile time Polymorphism. i mn overloading, we can In function overding we have any number of overloaded have only oce vei & epucn) zl “A Guide for Engines ° “A Guide for Engin ing Sd ning 3-14 ated Programnins_ oF Runtime Polymorphism ntime pol hier nw. 8 rine polymorphism, the rere resolved at ru ime «The runtime polymorphism © method verte ‘sRedefining function in & derived class is called function oven; dy (c++ Program include using namespace st class A { private int public: void get_msg() { a=10; b=20; + void print_msg()const a an “thy an be achieved by function ver, he » MASset_values (4,5); Proly2->set_values (4,5); ‘out << rect.area() << \n' cout << tgLarea() << ‘tum 0; 3.9 : Pointers to Base Class Q.19 In It possible to have pointer to base class? If yes, justly ‘Ans.: One of the key feature of inheritance mechanism is that & Pointer to derived class is type compatible with pointer to its base clas. ca oe variable of a base class and asiP class's objects to it For example - ‘include ‘sing namespace std; “ Glefor Engineering Sede and its Signifcance jy siented Programming 3-19 S inte jt or y P cout<<"Title: "< virtual void Read(int num) ‘using namespace std; { class Meda ‘ { playtime = num; public: t char Tie[10],publication|20}; ‘ual void show 5 virtual void Read) { cout << "Playing time in tape: ‘cout<<"\n Enter casera hme th ts ‘cout<<"\n Enter the | abies Publication: cout << playtime << "\n'; ta i tong eSs——____ |: “A Gulde for Engineering 4 an 3-20 Pe Book bi Tape t obj Retd() howl) corte nenter number of PAGS: ein> >: pRead(num): posnowd show Seon \ninter Time in minut in> >um 3a(num); Enter the title: AAA. Enter the publication : BBB Title: AAA Publication : BBB Enter number of pages : 100 Number of pages of book : 100 Enter Time in minutes : 3 Playing time in tape : 3 3.11 : Pure Virtual Function and Virtual Table 22 What 1s virtual function ? Why do we need virtual function? virtual function "pure" ? What are i When do we make a ‘implications of making ? function a pure virtual functi Ana: Virtual Function and its need - Refer Q.20, A Pract son is virus function whic isto be imple rst class. The class tht contains the pure virtual fico * S&S A Gulde for Engineers 5 [SPPU : Dect, ha ented Programming 3-21 e ~ a finctions ae declared agg ett y en jrual functions are declared ui = jrtual 9B PUTE specifiy i, pee es F mlction of UE VTA Rtn the ae ° an Mc cant be instantiated, but 2 child clay lass becomes aN Override thy that pT ethods to form a concrete clas. This pare java! ne ee "5 B004 way to dese op erface ample pan eociostroam> re namespace 51d; (//makes class B as abstract class pic void display()//overriden function 4 cout<<"\n Derived Class Function’ } pt main() B “ptr; //Base class Pointer Dobj: //ebject for derived class Ptr=&obj; Bt >display(); tetum 0; “ule forEngineing Seen ig ~ uirtual destructor, a HH (SPPU sw Polymer 3.13 : Abstract Base Clas, act base class ? i elas is 8 Class whichis mostly wag east one pure virtual function, Abstrac, pa A base class an interface that must be implemented by aj whee eval function is function having nobody tug yo Maps «basically @ base class destructor 9 "4 declared a8 virtual bet 6 we ws destructor i ' wed Oy The tase lst te ey pet ec he memory of anv clas EXPUCHIY. For example te ste complet that abot exis tr i eens = 9 ae Te ygse cass When @ virtual function is made pure ge” { veh css 10 overTde it I a derived class ees non a wn public: fps, making @ virtual function pure is a wey vy purenn ot Base() ined class will provide its own redefinition ta { enncehn Caling Base class Constructor; } ver) ~Base() /hrtual destructor { eautc<"\n Calling Base clase Destructor’; } END. “ase Det pb Base { public: Derived) { cout<<"\n Calling Derived class Constructor’; } ~Derivedl) { cout<<"\n Calling Derived class Destructor’; } hk ‘int main() { fase ‘bj=new Derived) /object creation voces init cae memory get dealocated, , w=a—_ jou A Gulde for Engineer a —ar——O—OS—SOT WG | | | Files and Streams Jain various predefined stream, a 5 (SPPU : Duneaa, sed be ? 14 What Is stream Mth thelr purpoee. Fig. Q.2.1 Stream class hierarchy 4.3 : Stream Errors (03 Explain the commonly used error functions defied by los as. Ans, sate 3s class defines some member functions using which the stream can be checked. ‘Member Function Purpose tool iasigood) This functions returns tue if there is no eror freee wepiadeagy ts fenetoos reams tne ter: Beer) | Sea iossbadg This function rerums true if no read/write operation is | performed or invalid read/write operation is performed. foto) Pe ena olan incre Se inieoRy This function retums true if the input opersion is reached end of file 4-4) A Guide for Enginvering Sudenss wee es a Programing _ 43 __ “Tis fetons retums tru ifthe input o Ae raad the expected characters, or that an supplied. It can also be used to clear a party fag if supplied as argument. ‘Ans. The ios cl sate ofthe steam can be checked. void maint) { ine val char ans =) cout << ‘\n Enter an integer value: “ cn >> val i (cagood)) == OV/if error For example - cout << “\n Incomect input’; cout << \aThe good() functicn retums: " << cin.good(): cncleatt) else com << "\n Comect input’; cout << “\nThe goed{) function returns: * << cin.good| } The above program will give error message if non integer value is entre? by the user. Se “A Guide for Engincerint on fg ‘penton led to generat the desired chy This fnction cleus ll the 988 1 10 argumen Sag programming 4-4 pate roporning A re net en teams stream ? Write & program to in t HF [SPPU Deceas, manne os Mince USPPU Oncor 6 ng ot team eg qi and 4 Refer 44 : Disk File 1/0 with Streams ofstream, ifstream, and fstream pxpiain the classes, os Bn? Provides following clases to perfor input my r jos gto and from the files. Ls = sae pou = ‘This stream class is used for both read and we & ‘pata file VO, we need to include inthe progam i vs several classes, including ifstream, ofstream and fstream. These iiuses ae derived from ios, so ifstream, ofstream and (tream have 2, To create an output stream, declare an object of type ofstream. 5 To create an input/output stream, declare an object of type (stream. (01 Explain various flags used in modes of file open operation. 5 [SPU dene, Mats 4} 455: The mode is optional parameter and is used with the Hags 3 Sa below = ‘sia Open for input operation. Tso Open for output operation. ‘sbimry Open for binary operations. gst he nti posidon i$ the gag anion i a the Being of he tM —— so a pins we pended le TH i Tm omen A send “ stream in; char Data[60); inopen('Sample.dat"); sf (in) { 1/ Print an error and exit cer << "Sample dat could not be opened for reading!" << end: exit(1); } cout<<"The Contents of the file are.."< include pinclode sing namespace std: class Employee { publi: char Name(40; ‘ot D; double Salary; i vod main?) { ‘Employee empl; cout<<"Writing Data to the stream..."< include using namespace std include const int MAX = 10; int array! (MAX) int array2[MAX]; ‘int main() ‘ ofstream os; //create output stream os.open(é:\\test. dat’, fos:trunc | ios:binary)://Opening file if (08) { cert << ‘Could not open output file\n’; //Brror Handling exit(1); 10,20,30,40,50 }; ‘cout << "Writing the contents to the file..\n\n' os write((char*)&array1 sizeof{array!))i//wrlting ‘array1' to fle if (los) { corr << ‘Could not write to file\n'; //Error handling enct(1); os.close(); //clowe the file ‘Suoam is; /create input stream for reading the contents from ‘8. open('d.\\tost dat, ios:binary); if (is) sil { Sead “Could not open input fle\n'; //Brror Handling ; i SS A Gulde for Engincerin Sale 1. ey __ rogramming 4-10 at P12 File end Steams 1 gasing the contents from the fle xy, or Bare SEAOATEYD: aig to ontet y prea /another array ci) . 1 gq << "000d tf om en Mer Hasag oat ) oy 20,5 < MAX; j++) //check data pate 2S Camayal ee xo error handling in file VO with sultable program, ots Explain FB (SPPU : Dec-39, Marts 6] Refer Q.14. 4.7: File I/O with Member Functions @ member function of a class can take part in et bli fee emer ton of dm te et * { re a char name[40); sven bt ‘wid input_Data(void) { out << "\n Enter Roll Number: * in >> rollNo; cout << "\n Enter name: *; cin >> name cout << "\n Enter marks: ' > mar; rs Slsplay(void) 1 Member function for qq le 2 ganna 8) sir0az 19) spjopenc est dt os: binasy) BS cveegindex’sizeoStudent): ob read (char this, sizeof(*this): //read one record at a tin, . 6 } 2 ss grudee Wneehled)_ // Member function for write fle cfszeam out_obj (rast da’ os:app | ioe: binary): cos open o eis, sizeof *tis); writes current record tog ct_obj wrte((char" ‘nz Srudent-TovalRec)) sisream in_obj ‘2 objopen(test dat’, ios:binary); snob sekg(0,iosend); voy tell geting count for total number of records ‘mt aze= (intin_cbjstellg) / sizeof(Student); retum size; 48: Overloading Extraction and Insertion Operator Qi How do you declare an overloaded stream insertion and cainction operator 1 [SPU : De.n16, Mark 3] ANS. In C= ae ‘he ouput operation is denoted using << which is called Perator. Similarly the input ‘operation is denoted using 7” Ss 4 Guide for Engineering Suder® LT ams ote 7 EAD st, Point &obj) hig 8% oh erpoter 21 poputting the values ) 4.9 : Memory as a Stream Object ‘gwote short note on « memory as a sueam object at Wit “cpr itis possible to treat particular section of memory as oie and data can be inserted into this section of memory with the su of memory object. Tie steam classes ostrstream is commonly used to create memory best, ‘The syntax for creating such memory object is ostrstream ObjectName(databuffer,size_of_buffer) ‘tmsing) ( ‘int RolNo = 10; char name[] = "Rashmi"; ‘har Data(SIZE|; //Data Buffer for memory object wont 7 Guide fr Engineering Sader ee) a ~~ met Ont Presramming 4 seman 0000 SH U6 gg a buffer and size ‘memOb) << ‘Roll Number = " << RollNo ak < //for fle steams soy namespace std sain { ostream printer; //make a file piste opent"PRN);//open it for printer pater << "Hello frendslll" << endl; //sond data to printer priate << "OC; //ormfeed to eect page The arge(0] is the name of the program, or an empty string if the nane is oot availble, After that, every element number less than arge i command line argument. You can use each argy element just like 4 string 2.20 Write a C++ program to read the contents of the wie he same I pecied ty command ine eum include #include <{ostream> Printer.close(); using namespace std; um ‘include } ‘nt main(int arge, char* argvi} ) { END... i arge t= 2) { eS niet = Tana gnaone Ha ay Tannen a Unit V | Exception Handling and Template, 1 What ae three commonly used eror handling techniques ‘Ans. ; Three commonly used error handling techniques - 7 1. Terminate the program on eror situation 2. Write the error code and assign it to global variable. On gems ‘error, retum the corresponding code. Beng he 3. Some suns code can be predefined and on suecest oF fe ge corresponding code can be returned. 4. Use of goto for jumping to desired statement. Typicelly the functions like abortQ or exit() are used for getting out of the error-prone situations. 5.2 : Simple Exception Handling Q2 What is an exception ? How is an exception handled In C++ 1? What are the advantages of using exception handling US [SPPU : Dec.n14, Marks 6, June-22, Marks 4] Ans. Definition: When any unavoidable circumstances (or runtime frrors) occur in our program then exceptions are raised by handling control to special functions called handlers. This provides build-in enor handling mechanism which is known as exception handling. C™ exception handling mechanism makes use of three keywords « 9: atch and throw. The try represents the block of statements in which there are chances of occurring some ‘exceptional conditions. hen exception detected itis thrown using the throw statement. 6-1) a rogramming 5-2 Exception ou Eo Handing nd tn me lock of statements in wh sists 2 bloe Heh the eXcEBon tug a te ee eoriely- This block is clledeateh big sled nrow 100; 3 sen it) {ut << "An exception a } return 0; ) tp above program the iy block contains the porion of the cade for cvepton handling, ‘he main advantage of exception handling mechanism is that any emor casing situation can be gracefully handled by raising appropriace ‘ception without carshing the code. @3 Explain exception handling ceo eee Ans. Refer Q2. ls ion ton handled in C++ ? (4 What Is exception ? How Is an excep See Aas. Refer Q.2. Seo Q.5 What te the Ans. Sr, No. Error ‘wrong situations that occur in the program. 3. Emr is uncoverable. ‘working when an error occurs. s. Error cannot be covered but it 's fixed by the programmer _Freention Handing ang ifference between error and excep es onan [a pmpmcuwomn ti ne 4 Program crashes or stops Program reports user tlon 2 Exception or wrong situations gape inthe pros mettage about the ahora, station and exits gray ‘The exception can be handled sing ty, catch and throw statements, 6 Enor is compile time ero. Exception i rua time ever. 10 now cout << ROR 1/ divide-by-z0r0 << a/b << endl; //for non zer0 value sen (aouble ) ¢ ‘Cant divide by zer0.\n'; qo << ‘Cont v Output aa numerator : 10 tae denominator : 0 coat divide by zero. 5.3 : Divide by Zero Q.6 Write a program to handle divide by zero situation while performing division operation using exception handling. ‘Ans. ‘nt main() { double fj void divide(double, double): cout << “Enter numerator : cout << “Enter denominator : cin >> j EEE A Guide for Engincering Sule 5.4 : Multiple Catching rogram ? Ear [SPPU : Mayeta, Marks 5) 40s: When an exception occurs then the control is transfered to the ‘6 block and at that time #ry block is terminated. There can be multiple ‘options in multiple catch statements with one my block. Following is ‘sniture of the program when multiple catch blocks are allowed. QF How to handle multiple exceptions occurred in function { = war A Guide for Engines odes > onet Oriented Programming 55 ‘catch (datatype! arg) 4 ) catch datatype? arg) { ‘The program iluswating multiple catch statements is as shown below ‘#rnclude , ‘using namespace std; Void fumction(int num) { ty { if{oum) throw num; else throw “Value is zero", , a “Mhraultiple catch for si cateh(int jy { Se A Guide for Enginerng Sue ingle try block Vee Exception Handling and Templates Ems and Templates oO “cc “Exception for number is handled: " <<{ << "pr, cost 1 ajconst chat "82 {ce “Exception for string is handled: *, cout Soot < ot << "N8 ts aaind coat using namespace sta; void function() { uy { throw "“myworld”; + ccatch(char*) i cout<<"\ninside the catch statement of function()"; throw; //rethrowing the exception The exception which is thrown is analeg here by this eaten Block function(); y ‘catch(chas*) 4 ‘cout<<"\n\ninside the catch statement of main()": » return 0; “A Gulde for Engincering Suit? — Programming 5-8 __ Exception Hana 5.6 : Exception Specifications anat teeton SPE 7 Ee Hh ay Smal. ification is used : 1m xception speci '0 Provide the information Wm opexceptions that can be thrown, For example mate” about oes Sond sow (nk. double) of jen ne 0 © prowtt2.94% Lean i) or Se aaa ee tea So t ee camel (epeatalae ee ese eet Spin vi «dlzrce gpten aha ts un tessa oa teal or indirectly, it cannot be caught by a regular int or double type huni, ‘ fechude cman n> MySqridoubie val (cae or Engng Sse __ sm Cotsect Onented Progamming 5° Excetion Handling ong ce-cas not bande "<<<" TUM ET < can a mt maint) cout <\n Enter some number: double num. n> > num. MySqrt(oum): return 0; Output Enter some number: -5 Cen not handle Negative number 5.8 : Processing Unexpected Exceptions Q12 Justify the statement - “An processed in C++" tmexpected exception 4 Ans. : For processing the unexcepted exception, the set_anerpecd function is wed . This fiction is also called as unexpected had function. The unexpected handler by default calls the terminate funciz, | void myunexpected () void function() throw (int double) { throw( Hello"); ‘The string is not specified in the list ‘hence unexpected exception occurs. ‘Set_unexpected (myunexpected);//setting unexpected Hexception handler Ss. “A Gul for Engine Py Exeption Handing and Templates 9; Constructor, Destructor and Exception Handling | 5 How does exception handing activity is carried ovt when 213 How (and destructors are present In C++ program > censtroctor When the exception is raised inside a sry block, for all the created inside the blocks the destructor is called frst and then the svch block executes to handle the exception raised ty bloc ars For example cass Test public: Test) { cout < “\n Constructor is called” ~Tost() { cout < “\n Destructor is called”, } b ‘ot main() wt ‘Test obj1,0bj2; //ealling constructor for twice throw 100; //ealling destructors twice Hand then catch block executen } catch (int @) {cout < “\nBxception is caught” <2; } rerum 0 , = = _—___— = 1 ale for Ergincerig Sede | cout << “min(10.3, 67.2) rerum 0; 5-16 Exception Handling and Templates ing yo 1708 overloaded functions and function betwee | plate fer finding intmum value function GP [SPPU : Deci-46, Marks 6 } - allows the definition of more than one roading and provides a means of choosing between 0 pear matching. Template functions tell the par J on tions, based on the instantiation os BRT create new functions, ate (instantiations) behave pow © ated ftom the template 8 h tion ; BS Wa hy ‘ c00 erloading whereas the function Possible to overload the finction templar eat cot Sat differ in funtion ov funetion or by template function. This non ric ee son b08) sanction template. ‘as the same name as the template function but it ie ot related et not differ 1B template function we ing isan example of overloading the function template template : void display(T x) qin: { aineal =0i<6i++) cout << x; for(int i=01'<85 { } sfeli bjt (109, SOi//eompaning two integers Sebar> obj2(p', Wicomparing two characters cea BaRURLL00 60) = * copy max); COSSS"\n maximum 2) = “b) valng else val=b, vetum val; ) {nt main ¢) { Compare obj (100, 4 << me 0)//eom SP ean, 0) wae A naga max); ©F pointer to oe member ‘emplate parameters, rovide the abilty te pay For example . a = Guldefor Entncerng Sa programming 5-20 Exception Handling and Templates ped Pros yet " gaspay0 (eout << an t xi/finitialization of class with non-type template axgument cet Yi sisplay0: yalsplay() ‘tur 0; 024 What 18 C++ template ? Describe type and non type temp 1 (SPPU : DecotS, Mars 8] Ans. Refer Q21 and Q23, 5.18 ‘emplate and Friends 025 How to use friend function along with templates ? ‘Ans. : A fiend function can be used within a template class Following C++ program illustrates how to use friend function inside ‘the template class, Winclude ‘using namespace std: coe ‘ ‘templet ‘ com kl Ko st EscptionHandig ng te seid eT) { vue ‘template t n void f{TesteT>& obi) (09 =* in the lst { gout << Toe element if present cout << Tose Friend Function’ ee aaa “ale You have entred.."< object; int main) ‘ot oum; { cout << "\n Enter the val to set“ int af} = { 33,12,78,100.55 }; ea>> ae cout << "\n Searching element 100 from the list’; flbjeci/ealing friend function isplay(e, 100, 8: ; nn double b{7] = { 38:33,12.12,78.78,100.10,55.55,66.66.91.67}; cout << “\n Searching element 78.78 trom the list: ; isplay(b,78.78,7) S49 Genere Functions return 0; Tat bee fncton / Witt ltge and daub," *#ENOg an element from the : 0.27 Write short note on - Generic classes. ‘Ans, « When the class logic can be generalized then it becomes a ‘template vwia ; py aby, generic clas. Fr example the class that creates a liked list for integer ‘nt count) inked i numbers, same class can create a linked list for double or characters. Aono herig Soden & “ld for Engng Sues ee : ynming 5+ Exception Hanlin ond Templates _— ing and Templates spanamne tYPOLAYPODA® typ e2> wed export Keyword can be used 1 export the tenga 70" ae files. The keyword export is preceded te template mr age 10 0 : 40 pe template definition eal oe exartle = vemplate say “hs, T ey, ist court ced in some header file say test. This tsth can then be oF ao ‘main application program which uses the templates wa END. ‘Pemame can be used in place of class = eefnctice, B can be used in a template declaration md Semple paramere list A Gulde for Engineering Sade = a Ans 's: The Standard Template Libs Structured generic C+ rary (STL) is lasses (templ: a ion lates) and funct wa so ie apna ne) Eon, Ta * Comainer 2 Algorithms 3, erator 6.2 : STL Components 22, Eaplain the terme ~ Containers, ‘lgorithms and i ** Container : The container isa collection of objects ot 'WPES. These objects store the data. om erator : The iterators are basical basically objects but sometimes oe (te Sometimes they can bp Hs (6-4) progamming 8-2 _Sanded Template trary ——————— container ? ay wat wre of all te claues who Feptesent the semuecce op A vate * manple, vector class defines dynamic array. Deqae infor py ended queue ie. We can perfor insertion and deletion ct "ens rom bth the ends of queue aod lst provides a near na Tre alas defines the collection of elements in hich ios the element 8 alone, ting é only sequential a5 Write and explain some commonly used functionalities ed os OF (SPU: duce 22, warts 4} Ans. Some commonly used vector functions are - Funetion Description vend) Retums the last element of the vector. sizeQ) ‘Returns the size of the vector. erase() Erases the given elements. ‘Push_back() ‘Insert the element in the vector at the end. pen ek) Deen st eet of he ener Tse) Noise pal eo be vor ————— oe eee eS ee —— ‘using namespace std ‘int main() cod "Guide for Engineering Sens Stondeng vot unremming 6-4 Standard Template titey tnt her late, rit = oo iter. choice ey cc “\n The deleted slamont is: << item, Geauecim> dq prea Seavecint> tent scout €< "Wn The 8 of DEGUEY i: * << da sa) io case’ " { resi ge scout << "Elements of DEQUE are: * for (1 = Aapbogin():!= dq.end(); i+ = {1s for iterator cour << tice" } cout << “\n Do you want to continue?(y/n) * ‘¥ || ans == '¥), 644 : Associative Container 7 What Is associative container ? Ans. The associative container allows efficient reieval of values based on keys. The key can be usually an integer or sving value using which ‘be data can be arranged in ascending or descending orde. ‘There are various types of associative containers - Set, mubiset, map and multi. 28 Explain the terms sets, multisets, map and multimaps with lis declaration syntax. Ans. 1) Set : Set is a container that contains unique elements in some specific & ch as inseron of case Sitem = order. We ean perform various operations on set su Sa.pop oa deletion of element, searching particular element from the se, ee oe Aisplaying of size of the set and so en. i Nn The deleted sloment 18: " << item: Syntax : setcobject_1ype> set_name nn . i) Muld-sets : Mutisets are similar t sets but the diference between Sate 4item = da back, tet end mukiset is the se does bot allow dupcting elements but a.PoP_back(); . rust allows duplicating elements Syntax : multe mule name ‘A Gude for Engincering Smads Ss “A Gude for Enineing Sueno sop Uanasostiry sof remy y pa oe ‘oma 25 om epee wen 9) 9 HOH EMD Hom 105 perwers w we/qo//

ATS , NO >> 98 02s aaeseat st a Oyspecs 32 UE. >> sno is eoedseures fry [20] 04 yen RoR oT sePHOG// OPTI g ™ epniry one 57 M22 mug, 55 snoo (Ope #2) 9 5 ‘uy (EPG Vy ones Sree EET Tl epmnamin 4498 a0 Mt > meee, ‘sranb fauoud pu ‘ananb “yams = ar wayy jo s2iduser7 (ewe = amos ores “tuaydepe sauyeyue> “meerq 40 szajeiwos paauap ce noi sounawos am asauy eeu” (terjoseses uey << souanbos sy wo panuop ame ey sovse|> ouos ame aio : suy up aardepe saujeruoy - win ayy ureidrg 40 ‘< Penstep oa or wee ous sug 1, >> moo eves sadepy sauyeuoy : $79 sauirwos amp jo aes a sung suas an raujeruos yeyq ¢ uTEMO? IFIM S}'D { ‘oumaer (A == Sue) orga { sue << mo +, coruminoa oy yeas nok og th, >> noo { Speaig ‘Qensb >> , = enenb Jo ozig w\, >> snoo:g ese> ‘ree1q smog >> , St enanb jo pua qoy ve aemje auL, >> moor ese2 oyeerq, “yee? >> , St enenb jo pus reer 1e yuemieye eu, >> ynad:g ose yee Nuet> >,s} Wen pereted w, >> 309 enenb woy queusje Bureteqy/:()dod'b ‘Qquoyb = wey :z 65% swpara SNpeuesuy sy wey wi, >> 390? enenb om oqo ewes em Survesu//:(tey)asnd> ey << 19 ‘.Peussuy oq 04 ywomele oa roy ti, >> 1N09:1 +, eojoug mok 110d WV 7” s,enanb jo e71S'S ace een Aamugyy ayrjduay Pavpunjs 1-9 Suyuo opm Busaour8u7 sof pny y : wre << up “a { { ‘Odod'ba a>> Odorbd >> anos } (4udae bayoriay 08 reaig MBE >> | = onandjo org u, 5 an0o:¢ ese : oe coset png, mn na Peps > 7: » 8-9 Aamsitoed rou page _ This function is used to reverse he given sequence of ements Description 1 il find the position sven sequence Ue checks whether the mo sequrces a ago ot Ito ssuenees we mashing the teria | _————=____| | : [smh Ths orton we hr ecg din an function accumulate), Ae elements can te element from the given sequence. Ans.: ‘mutating and non mutating al tales 18 White a C++ program to porn bins Herc sing STL. Mutating algorithm Ans ‘clude ‘Pnclude ‘sing namespace sté; ant all = (10.20;3,4089.60.70.80 } ‘an ey, cher ans=V; tat maint) Copies the sequence of clemens for (ot = cout <7 << ali ‘A Guide for Engineering Suen +3 >09 = 0 195 {SIUM eu 9903,> > 209 Simos 105 eBues om Smies// ‘c «. deure =aar], ; u<sanog N{azisdexe merc spuooesamnse: >> = Oop 4 SSIgTTser >> ,= 7 Bis eoedssmrec Sunsn Ot Sais eupepg PePnio UNAHOBTE plomay/ spay > moo {e)coummm = ynsex ome ‘{ Os'ov 0e‘Oz'oT } = 8 one > apoeme Peptaoud, TUS @ = “SHON oS 9g as ok psn 29 uns estan! Semaogoy : sayy wy pas °B os 0) pasn 2q ues unpyosye Supioe meq mes Ord ‘Oumar XA == sce) egg { me << Bes Jo ALG aap St RG Ts 1 paoe yuOp aie oyme puowAsey 242 HN" Seu anus ue woy 30 soqye ons wel) 7 Xv pow uu axztnar oy vousumy anbrun e si Qremapm aL? “WRUCK HE 11g wy paen uopsun; (reunqus ogy Ie F . {CWA )genamaueo oF EA RAK Og EL >> anOS Naueserd you st >> Sag sagt a 3 nso ae Saesard st, >> 4ay >> ag EL >> 0s usu >> (ag 3 + w wRaES NE F ee a : Mag << ue gee > roe ~ Paqanwas oq 04 yoemeg eq ARES TL +S sO . : ert es papas — Kemgr] aed | pampeas vig Rapes oe swuewe(e jo sy) cso Peuos em Smuderistp// Tpue> > ~~ sy wey pasios el 7 dba peebaln tet All = (10.20.5040 5 tee Bil = { £6,6020,10 }, werent 110), vecson : nwnatcn woth, b+ 6), WonlB, B+ 4); Cat << Ben hm» 020.3040 (1030.50 60; 1620.50.40,5061, ie 11030 Ve 10,35, 7 * (2046 ent, Mt 1559) trey fer nt | = 0,5 << A t44) Cat <<" ce Ay) Cot << “ne ws, for(int} = 0, << it) A Gulde for Lnginecring Sino 2 = Toegeh, t= Tey === wan ce 20 TE | 62: Heap Sort 6 Heap ? Explain sypes of nena . ji! Dedatn Tey stooge ea em 1 child noes. 4 Max heap is a ree os wt vrual to the value of ine of cack node a emer than For example : Fig. 0.24.1 Max heap C7 “Auld for Emgnering Sadets Tes | hb anion 2y soveint 2m 0} woe souensvowap wresfoxd Sumo|iod : sea aq mensounp 0} US Baten urford © 21M LED p Ce penoge st Sao paewona pseu pO SURES A ANFTAY po OHS Teuons2pig, ‘Geos prewso} tive paMo(fe 8 SuUEHS STIE|Z anding ney | Fovom prewsny aie pemoyE 5 RAIMA UET.IZ ‘pemojre st Butrou bw uo mg posounaL ao pau 9g oeD sHME.S a presi ] ‘rauopon poses so pauow 29 wes ememayg ——ssaoae wopary | vondusseq 0y8225] sows jo sedis 248 oy woos Jo suzy a acsauen o} pam 2m SOE! (sen rear : aes) es sadly ey wyeydry ¢ soyeroy sj eu 8° = $5829 wopuey pue | fPuons2sipig ‘puemsoy ‘indyng ‘ynduy - ssoyesaal | 6° Seal anaemia ere + rt Qeawas >t 19 = 1 Pee 0) st ase] pews © dey eyioe//((jpae + (ses en Mr] ay dua) Papers La“ Buntiog a\0), 5s ano {MA >>. 5 anoo 30 oBtrez SRO den oma semen //()pue4 ‘OmBec-a)deon" ‘Barden Aa, > 5 snap kee ‘Ba 10~en { ee eseresory: } = (he sar } u Orme sx PHM “etoag : : — MORRIS +45 ae gry Potedas tai “Proxdde weop doy PES jo fom doo SOF BE ay UM D9 By *p = SE @ AY DOO oO ~~ ® ~~ © Le Mew wrt sag QT ee, SP PP ae Vane 8 8 eae a Press my

You might also like