c++ sample paper(newsyllabus)

Upload: akhilesh-chaudhry

Post on 05-Jul-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    1/24

    Roll No.: -------------------------------

    MCA – SECOND SEMESTER

    MODEL TEST PAPER-II

    Object Oriented Programming in C++ MCA-1 !

    Time: " #r$ Total Marks: %

    In$tr&ction$'

    1. Write your class roll no at the top, immediately on receipt of this Q/ aper.

    !. "ttempt (i)e #uestions in all includin$ Q1 %hich is compulsory. "ttempt one#uestion from each unit.

    *1 : &hort ans%er type: 1 , . /

    a/ 0 at do 2o& 3no4 abo&t r&ntime 5o62mor5 i$m7

    "ns: - "t runtime, %hen it is kno%n %hat class o'(ects are under consideration, theappropriate )ersion of the function is in)oked. &ince the functions are linked %ith a

    particular class much later after the compilation, this process is termed as late binding. *tis also kno%n as dynamic binding 'ecause the selection of the appropriate function isdone automatically at runtime. *f the appropriate mem'er function could 'e selected%hile the pro$ram is runnin$. This is kno%n as run time polymorphism. + supports a

    mechanism kno%n as virtual function to achie)e runtime polymorphism.

    b/ Can in eritance be 5ri)ate7 Comment8

    "ns: - The normal %ay of e pressin$ inheritance in + is

    +lass eri)ed: pu'lic ase 0 // stuff

    2

    When this is done, eri)ed is a su'type of ase, and any%here one encounters a ase 3or ase 4 one can su'stitute a eri)ed 3/ eri)ed 4.To $et pri)ate inheritance, one does:

    +lass eri)ed: pri)ate ase 0// pri)ate key%ord is actually optional //stuff 2

    The pri)ate inheritance is the default type of inheritance for classes 'ut not for structs5i.e. ifyou omit the 6pu'lic6 key%ord in the inheritance specification, you $et pri)ate inheritance.

    1

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    2/24

    +onse#uences of pri)ate inheritance:• "ll pu'lic and protected mem'ers of ase 'ecome private mem'ers of eri)ed--i.e. the

    class can use them, 'ut e ternal clients cannot. 78o%e)er, the definition for eri)ed canre-declare these to 'e pu'lic or protected2 mem'ers %hich %ere ori$inally protected canonly 'e re-declared as protected, not pu'lic9.

    eri)ed is not a su'type of ase, tryin$ to $tatic9ca$t a pointer from deri)ed to 'ase 7or cast one implicitly9 %ill result in a compiler error.

    • *f pri)ate inheritance 'roke the su'type link 'ut didn t make all the mem'ers pri)ate, itmi$ht 'e more useful 'ut since it does make mem'ers pri)ate, it isn t )ery $ood.

    c/ #o4 i$ e:ce5tion and6ing i$ bene(icia6 (or object oriented 5rogramming7

    An$' - Ad)antage$ o( ;$ing E:ce5tion #and6ing

    ; ception handlin$ pro)ides the follo%in$ ad)anta$es o)er name 0 // code declarations

    To call the namespace-ena'led )ersion of either function or )aria'le, prepend thenamespace name as follo%s:

    2

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    3/24

    name::code2 // code could 'e )aria'le or function.

    e/ 0 at are r&n time memor2 con$tr&ct$ in C++7

    "ns:- " $ood understandin$ of ho% dynamic memory really %orks in + is essential to 'ecomin$ a $ood + pro$rammer. Memory in your + pro$ram is di)ided into t%o parts:

    • T e $tac3' "ll )aria'les declared inside the function %ill take up memory from the stack.• T e ea5' This is unused memory of the pro$ram and can 'e used to allocate the

    memory dynamically %hen pro$ram runs.

    Many times, you are not a%are in ad)ance ho% much memory you %ill need to store particular information in a defined )aria'le and the si?e of re#uired memory can 'edetermined at run time.

    @ou can allocate memory at run time %ithin the heap for the )aria'le of a $i)en type usin$ aspecial operator in + %hich returns the address of the space allocated. This operator iscalled ne4 operator.

    T e ne4 and de6ete o5erator$'

    There is follo%in$ $eneric synta to use ne4 operator to allocate memory dynamically for any data-type.

    new data-type;

    8ere, data-t25e could 'e any 'uilt-in data type includin$ an array or any user defined data typesinclude class or structure. Aet us start %ith 'uilt-in data types. Bor e ample %e can define a

    pointer to type dou'le and then re#uest that the memory 'e allocated at e ecution time. We cando this usin$ the ne4 operator %ith the follo%in$ statements:

    double* pvalue = NULL; // Pointer initialized with null

    (/ Di$c&$$ t e o5erator$ t at cannot be o)er6oaded7

    "ns: - *n + , follo%in$ operators cannot 'e o)erloaded:

    . 7Mem'er "ccess or ot operator9

    C: 7Ternary or +onditional Dperator 9:: 7&cope Resolution Dperator9.3 7 ointer-to-mem'er Dperator 9si?eof 7D'(ect si?e Dperator9typeid 7D'(ect type Dperator9

    g/ 0 at are re(erence )ariab6e$7

    3

    http://en.wikipedia.org/wiki/Sizeofhttp://msdn.microsoft.com/en-us/library/fyf39xec(VS.80).aspxhttp://en.wikipedia.org/wiki/Sizeofhttp://msdn.microsoft.com/en-us/library/fyf39xec(VS.80).aspx

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    4/24

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    5/24

    ! con t int n,alue (0); // initialize i plictly

    *n the case of classes, this initiali?ation is done )ia constructors:

    1

    !

    con t 1ate c1ate; // initialize u in2 default con tructor con t 1ate c1ate (3 4 354 ); // initialize u in2 para eterizedcon tructor

    *f a class is not initiali?ed usin$ a parameteri?ed constructor, a pu'lic default constructor must 'e pro)ided 5 if no pu'lic default constructor is pro)ided in this case, a compiler error %ill occur.

    Dnce a const class o'(ect has 'een initiali?ed )ia constructor, any attempt to modify the mem'er )aria'les of the o'(ect is disallo%ed, as it %ould )iolate the con$tne$$ of the o'(ect. Thisincludes 'oth chan$in$ mem'er )aria'les directly 7if they are pu'lic9, or callin$ mem'er functions that sets the )alue of mem'er )aria'les:

    j/ 0 a t i$ t e &$e o( t i$ 5ointer in a c6a$$7

    "ns: - ;)ery o'(ect in + has access to its o%n address throu$h an important pointer calledt i$ pointer. The t i$ pointer is an implicit parameter to all mem'er functions. Therefore, insidea mem'er function, this may 'e used to refer to the in)okin$ o'(ect.

    Briend functions do not ha)e a t i$ pointer, 'ecause friends are not mem'ers of a class. Dnlymem'er functions ha)e a t i$ pointer.

    ;nit -I

    * '- 0 at i$ O5erator o)er6oading7 E:56ain di((erent t25e$7 0rite a 5rogram o( o)er6oading binar2 o5erator7 1 /

    "ns: - Dne of the nice features of + is that you can $i)e special meanin$s to operators, %henthey are used %ith user-defined classes. This is called operator overloading 8 @ou can implement+ operator o)erloads 'y pro)idin$ special mem'er-functions on your classes that follo% a

    particular namin$ con)ention. Bor e ample, to o)erload the operator for your class, you %ould pro)ide a mem'er-function named operator on your class.

    The follo%in$ set of operators is commonly o)erloaded for user-defined classes:

    G 7assi$nment operator9• - 3 7'inary arithmetic operators9

    • G -G 3G 7compound assi$nment operators9

    • GG HG 7comparison operators9

    O)er6oadab6e>Non-o)er6oadab6eO5erator$'

    5

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    6/24

    Bollo%in$ is the list of operators %hich can 'e o)erloaded:

    - 3 / I J4 K L H , G

    G G --

    GG HG 44 KKG -G /G IG JG 4GKG 3G G G OP 79- - 3 ne% ne% OP delete delete OP

    AL?ORIT#M'

    &tep 1: &tart the pro$ram.&tep !: eclare the class.&tep : eclare the )aria'les and its mem'er function.&tep : =sin$ the function $et)alue79 to $et the t%o num'ers.&tep S: efine the function operator 79 to add t%o comple num'ers.&tep : efine the function operator U79to su'tract t%o comple num'ers.&tep V: efine the display function.&tep : eclare the class o'(ects o'(1,o'(! and result.&tep X: +all the function $et)alue usin$ o'(1 and o'(!&tep 1Y: +alculate the )alue for the o'(ect result 'y callin$ the function operator andoperator -.&tep 11: +all the display function usin$ o'(1 and o'(! and result.&tep 1!: Return the )alues.&tep 1 : &top the pro$ram.

    PRO?RAM'

    6include7io trea .h86include7conio.h8 cla co ple# int a4b; public$ void 2etvalue() # cout779:nter the value of "o ple Nu ber a4b$9;

    cin88a88b; + co ple operator (co ple ob) # co ple t; t.a=a ob.a; t.b=b ob.b; return(t); + co ple operator-(co ple ob)

    6

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    7/24

    # co ple t; t.a=a-ob.a; t.b=b-ob.b; return(t); + void di play() # cout77a779 977b779i9779nput ,alue $nput ,alueA i i?e ult5 0i Bi

    Different types of operator overloading are:-

    ;nar2 and binar2 o5erator o)er6oading

    There are t%o types of operator o)erloadin$:

    • =nary operator o)erloadin$

    7

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    8/24

    • inary operator o)erloadin$

    E:am56e o( ;nar2 O5erator o)er6oading'-

    The unary operators operate on a sin$le operand and follo%in$ are the e amples of =nary

    operators:• The increment 7 9 and decrement 7--9 operators .• The unary minus 7-9 operator.

    • The lo$ical not 7H9 operator.

    The unary operators operate on the o'(ect for %hich they %ere called and normally, this operatorappears on the left side of the o'(ect, as in Ho'(, -o'(, and o'( 'ut sometime they can 'e usedas postfi as %ell like o'( or o'(--.

    Bollo%in$ e ample e plain ho% minus 7-9 operator can 'e o)erloaded for prefi as %ell as postfi usa$e.

    6include 7io trea 8u in2 na e pace td; cla 1i tance# private$ int feet; // to infinite int inche ; // to 3 public$ // reCuired con tructor 1i tance()# feet = ; inche = ; + 1i tance(int f4 int i)# feet = f; inche = i; + // ethod to di play di tance void di play1i tance() # cout 77 9'$ 9 77 feet 77 9 >$9 77 inche 77endl; + // overloaded inu (-) operator

    1i tance operator- ()#

    feet = -feet; inche = -inche ; return 1i tance(feet4 inche ); ++;int ain()#

    8

    http://www.tutorialspoint.com/cplusplus/increment_decrement_operators_overloading.htmhttp://www.tutorialspoint.com/cplusplus/increment_decrement_operators_overloading.htm

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    9/24

    1i tance 13(334 3 )4 1 (- 4 33);

    -13; // apply ne2ation 13.di play1i tance(); // di play 13

    -1 ; // apply ne2ation 1 .di play1i tance(); // di play 1

    return ;+

    When the a'o)e code is compiled and e ecuted, it produces the follo%in$ result:

    '$ -33 >$-3'$ >$-33

    *"'- E:56ain t e conce5t o( Name$5ace$ in C++ 4it e:am56e7 1 /

    An$' - Name$5ace$

    Namespaces allo% to $roup entities like classes, o'(ects and functions under a name. This %aythe $lo'al scope can 'e di)ided in 6su'-scopes6, each one %ith its o%n name.

    The format of namespaces is:

    namespace identifier 0entities

    Where identifier is any )alid identifier and entities is the set of classes, o'(ects and functions thatare included %ithin the namespace. Bor e ample:

    namespace myNamespace0 int a, '2

    *n this case, the )aria'les a and ' are normal )aria'les declared %ithin a namespace calledmyNamespace. *n order to access these )aria'les from outside the myNamespace namespace %eha)e to use the scope operator '' Bor e ample, to access the pre)ious )aria'les from outsidemyNamespace %e can %rite:

    myNamespace::amyNamespace::'

    9

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    10/24

    The functionality of namespaces is especially useful in the case that there is a possi'ility that a$lo'al o'(ect or function uses the same identifier as another one, causin$ redefinition errors. Bore ample:

    // namespaces

    Zinclude iostreamusin$ namespace std2

    namespace first0 int )ar G S2

    namespace second0 dou'le )ar G .1 1 2

    int main 79 0 cout first::)ar endl2 cout second::)ar endl2 return Y2

    *n this case, there are t%o $lo'al )aria'les %ith the same name: )ar. Dne is defined %ithin thenamespace first and the other one in second. No redefinition errors happen thanks to namespaces.

    &$ingThe key%ord usin$ is used to introduce a name from a namespace into the current declarati)ere$ion. Bor e ample:

    // usin$Zinclude iostreamusin$ namespace std2

    namespace first0 int G S2 int y G 1Y2

    namespace second0 dou'le G .1 1 2 dou'le y G !.V1 2

    10

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    11/24

    int main 79 0 usin$ first:: 2 usin$ second::y2 cout endl2

    cout y endl2 cout first::y endl2 cout second:: endl2 return Y2

    The key%ord usin$ can also 'e used as a directi)e to introduce an entire namespace:

    // usin$Zinclude iostreamusin$ namespace std2

    namespace first0 int G S2 int y G 1Y2

    namespace second0 dou'le G .1 1 2 dou'le y G !.V1 2

    int main 79 0 usin$ namespace first2 cout endl2 cout y endl2 cout second:: endl2 cout second::y endl2 return Y2

    *n this case, since %e ha)e declared that %e %ere usin$ namespace first, all direct uses of and y%ithout name #ualifiers %as referrin$ to their declarations in namespace first.

    ;$ing namespace ha)e )alidity only in the same 'lock in %hich they are stated or in the entirecode if they are used directly in the $lo'al scope. Bor e ample, if %e had the intention to first usethe o'(ects of one namespace and then those of another one, %e could do somethin$ like:

    // usin$ namespace e ample S

    11

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    12/24

    Zinclude iostreamusin$ namespace std2

    namespace first0

    int G S2

    namespace second0 dou'le G .1 1 2

    int main 79 0 0 usin$ namespace first2

    cout endl2 0 usin$ namespace second2 cout endl2 return Y2

    .1 1

    Name$5ace a6ia$

    We can declare alternate names for e istin$ namespaces accordin$ to the follo%in$ format:

    namespace ne%>name G current>name2

    Name$5ace $td

    "ll the files in the + standard li'rary declare all of its entities %ithin the std namespace. Thatis %hy %e ha)e $enerally included the usin$ namespace std2 statement in all pro$rams that usedany entity defined in iostream.

    ;nit -II

    *!'- E:56ain t e conce5t o( In eritance and @riend$ i5 in C++ 4it e:am56e$7 1 /

    12

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    13/24

    An$' - @riend$ i5 and in eritance' - *n principle, pri)ate and protected mem'ers of a classcannot 'e accessed from outside the same class in %hich they are declared. 8o%e)er, thisrule does not apply to "friends" .

    Friends are functions or classes declared %ith the (riend key%ord.

    " non-mem'er function can access the pri)ate and protected mem'ers of a class if it isdeclared a friend of that class. That is done 'y includin$ a declaration of this e ternalfunction %ithin the class, and precedin$ it %ith the key%ord friend :

    @riend (&nction$

    *n principle, pri)ate and protected mem'ers of a class cannot 'e accessed from outside the sameclass in %hich they are declared. 8o%e)er, this rule does not affect friends .

    Briends are functions or classes declared as such.

    *f %e %ant to declare an e ternal function as friend of a class, thus allo%in$ this function to ha)eaccess to the pri)ate and protected mem'ers of this class, %e do it 'y declarin$ a prototype of this e ternal function %ithin the class, and precedin$ it %ith the key%ord friend:

    // friend function6include 7io trea 8u in2 na e pace td;

    cla "?ectan2le # int width4 hei2ht; public$ void etDvalue (int4 int); int area () #return (width * hei2ht);+ friend "?ectan2le duplicate ("?ectan2le);+;

    void "?ectan2le$$ etDvalue (int a4 int b) # width = a; hei2ht = b;+

    "?ectan2le duplicate ("?ectan2le rectpara )# "?ectan2le rectre ; rectre .width = rectpara .width* ; rectre .hei2ht = rectpara .hei2ht* ; return (rectre );+

    int ain () # "?ectan2le rect4 rectb; rect. etDvalue ( 4B);

    13

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    14/24

    rectb = duplicate (rect); cout 77 rectb.area(); return ;+

    The duplicate function is a friend of +Rectan$le. Brom %ithin that function %e ha)e 'een a'le toaccess the mem'ers %idth and hei$ht +Rectan$le, %hich are pri)ate mem'ers. Notice thatneither in the declaration of duplicate79 nor in its later use in main79 ha)e %e consideredduplicate a mem'er of class +Rectan$le. &imply has access to its pri)ate and protected mem'ers%ithout 'ein$ a mem'er of different o'(ects of type

    The friend functions can ser)e, for e ample, to conduct operations 'et%een t%o different classes.[enerally, the use of friend functions is out of an o'(ect-oriented pro$rammin$ methodolo$y, so%hene)er possi'le it is 'etter to use mem'ers of the same class to perform operations %ith them.

    Friend classes

    Eust as %e ha)e the possi'ility to define a friend function, %e can also define a class as friend of another one, $rantin$ that first class access to the protected and pri)ate mem'ers of the secondone.

    // friend cla6include 7io trea 8u in2 na e pace td;

    cla "ECuare;

    cla "?ectan2le # int width4 hei2ht; public$

    int area () #return (width * hei2ht);+ void convert ("ECuare a);+;

    cla "ECuare # private$ int ide; public$ void etD ide (int a) # ide=a;+ friend cla "?ectan2le;+;

    void "?ectan2le$$convert ("ECuare a) # width = a. ide; hei2ht = a. ide;+ int ain () # "ECuare Cr; "?ectan2le rect; Cr. etD ide(A);

    14

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    15/24

    rect.convert( Cr); cout 77 rect.area(); return ;+

    *n this e ample, %e ha)e declared +Rectan$le as a friend of +uare so that +Rectan$lemem'er functions could ha)e access to the protected and pri)ate mem'ers of +uare, moreconcretely to +uare::side, %hich descri'es the side %idth of the s#uare.

    +onsider that friendships are not corresponded if %e do not e plicitly specify so. *n our e ample,+Rectan$le is considered as a friend class 'y +uare, 'ut +Rectan$le does not consider +uare to 'e a friend, so +Rectan$le can access the protected and pri)ate mem'ers of +uare

    'ut not the re)erse %ay. Df course, %e could ha)e declared also +uare as friend of +Rectan$leif %e %anted to.

    "nother property of friendships is that they are not transitive : The friend of a friend is notconsidered to 'e a friend unless e plicitly specified

    * '- 0 at i$ t e mec ani$m o( Late binding7 E:56ain t e 5roce$$ and a6$o e:56ain t er&6e$ (or t e $ame8 1 /

    An$' - Mec ani$m o( Late Binding'-

    15

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    16/24

    "t runtime, %hen it is kno%n %hat class o'(ects are under consideration, the appropriate )ersionof the function is in)oked. &ince the functions are linked %ith a particular class much later after the compilation, this process is termed as late binding. *t is also kno%n as dynamic binding

    'ecause the selection of the appropriate function is done automatically at runtime.

    *f the appropriate mem'er function could 'e selected %hile the pro$ram is runnin$. This iskno%n as run time polymorphism. + supports a mechanism kno%n as virtual function toachie)e runtime polymorphism.

    ;nit -III

    *%'- 0 at are 5&re )irt&a6 (&nction$ in C++7 E:56ain 4it t e e65 o( a 5rogram8 A6$oe:56ain t e r&6e$ o( )irt&a6 (&nction$7 1 /

    An$'- P&re irt&a6 @&nction - C++

    " )irtual function 'ody is kno%n as ure \irtual Bunction. *n a'o)e e ample %e can see that thefunction is 'ase class ne)er $ets in)oked. *n such type of situations %e can use pure )irtualfunctions

    ; ample : same e ample can re-%rittenclass 'ase0

    16

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    17/24

    pu'lic:)irtual )oid sho%79GY2 //pure )irtual function2

    class deri)ed1 : pu'lic 'ase

    0 pu'lic:)oid sho%790cout 6]n eri)ed 162

    2

    class deri)ed! : pu'lic 'ase0

    pu'lic:

    )oid sho%790cout 6]n eri)ed !62

    2

    )oid main790

    'ase 3'2 deri)ed1 d12 deri)ed! d!2 ' G 4d12 '- sho%792 ' G 4d!2 '- sho%792

    R&6e$ (or irt&a6 @&nction$

    1. The )irtual function must 'e mem'er of class!. They cannot 'e static mem'ers. They are accessed 'y usin$ o'(ect pointers. rototype of 'ase class function 4 deri)ed class must 'e sameS. \irtual function in 'ase class must 'e defined e)en thou$h it is not used. " )irtual function can 'e friend function of another classV. We could not ha)e )irtual constructor . *f a )irtual function is deri)ed in 'ase class, it need not 'e necessarily redefined in the deri)edclassX. ointer o'(ect of 'ase class can point to any o'(ect of deri)ed class 'ut re)erse is not true1Y. When a 'ase pointer points to deri)ed class, incrementin$ 4 decrementin$ it %ill not make it

    point to the ne t o'(ect of deri)ed class

    17

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    18/24

    * '- De$cribe di((erent met od$ o( o5ening a (i6e8 0rite an interacti)e 5rogram t atacce5t$ record$ and $tore$ t em in a (i6e8 1 /

    An$' - ifferent file openin$ modes in + are as follo%s:

    Mode$ De$cri5tionios::in Dpens a file for readin$. Ne% contents cannot 'e %ritten in the file.ios::out Dpens a file for %ritin$. *f file e ist already then its contents are deleted

    'ut if the file does not e ist it %ill create a ne% file.ios::'inary *t opens a file in 'inary form.ios::truncate Dpens a file for %ritin$. *f file already e ists then its pre)ious contents

    are replaced %ith the ne% contents.

    ios::app Dpens a file in append mode. *t adds ne% content at the end of the file.ios::ate *t is used to %rite ne% contents at the end of the file and %e can also

    modify the pre)ious contents.ios::nocreate *t does not allo% to create a ne% file if it does not e ist.ios::noreplace *t does replace the old file %ith ne% file.

    " header file fstream.h is used in order to %ork %ith the files in + %hich include functions foropenin$ and closin$ files.For opening a file:*n order to open a file open79 mem'er function of fstream^s class is used.

    S2nta:' open 7filename, mode98ere filename is the name of the file to open and mode can 'e mode a)aila'le in + .For closing a file:*n order to close a file close79 mem'er function of fstream ŝ class is used. This function takes noar$uments.

    Di((erent c6a$$e$ &$ed (or reading and 4riting to and (rom (i6e$ are a$ (o66o4$'

    C6a$$e$ De$cri5tionofstream This class is used for %ritin$ onto filesifstream *t is used for readin$ from filesfstream *t is used for 'oth readin$ and %ritin$ onto files

    Program' - This Menu Driven Program explains how to take get data from user, how toappend data, how to modify record and how to display records

    6include 7io trea .h86include 7f trea .h8

    18

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    19/24

    6include 7conio.h8

    taticint totrec= ; //totrec variable Feep tracF for total variableentered//>nitially ?ecord canned are Gerovoid ain()#int choice;while(3)#clr cr();cout779"hoo e your choice

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    20/24

    totrec = totrec 3; outfile.clo e(); + breaF; ca e B $ # of trea outfile; outfile.open(9e p94io $$ate); cout779!re you intere ted in addin2 record

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    21/24

    ;nit –I

    * '- 0 at are t e ba$ic com5onent$ o( STL in C++7 E:56ain 4it an e:am56e7 1 /

    An$' - The &tandard Template Ai'rary is a collection of classes that pro)ide templated

    containers, al$orithms, and iterators. *f you need a common class or al$orithm, odds are the &TAhas it. The upside is that you can take ad)anta$e of these classes %ithout ha)in$ to %rite andde'u$ the classes yourself, and the &TA does a $ood (o' pro)idin$ reasona'ly efficient )ersionsof these classes. The do%nside is that the &TA is comple , and can 'e a little intimidatin$ sincee)erythin$ is templated.

    "t the core of the + &tandard Template Ai'rary are follo%in$ three %ell-structuredcomponents:

    Com5onent De$cri5tion

    +ontainers+ontainers are used to mana$e collections of o'(ects of a certainkind. There are se)eral different types of containers like de#ue, list,)ector, map etc.

    "l$orithms"l$orithms act on containers. They pro)ide the means 'y %hichyou %ill perform initiali?ation, sortin$, searchin$, and transformin$of the contents of containers.

    *terators*terators are used to step throu$h the elements of collections ofo'(ects. These collections may 'e containers or su'sets ofcontainers.

    We %ill discuss a'out all the three + &TA components in ne t chapter %hile discussin$ +&tandard Ai'rary. Bor no%, keep in mind that all the three components ha)e a rich set of pre-defined functions %hich help us in doin$ complicated tasks in )ery easy fashion.

    Aet us take the follo%in$ pro$ram demonstrates the )ector container 7a + &tandard Template9%hich is similar to an array %ith an e ception that it automatically handles its o%n stora$ere#uirements in case it $ro%s:

    6include 7io trea 86include 7vector8u in2 na e pace td; int ain()# // create a vector to tore int vector7int8 vec;

    int i;

    // di play the ori2inal ize of vec cout 77 9vector ize = 9 77 vec. ize() 77 endl;

    // pu h value into the vector

    21

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    22/24

    for(i = ; i 7 ; i )# vec.pu hDbacF(i); +

    // di play e tended ize of vec cout 77 9e tended vector ize = 9 77 vec. ize() 77 endl;

    // acce value fro the vector for(i = ; i 7 ; i )# cout 77 9value of vec I9 77 i 77 9J = 9 77 vecIiJ 77 endl; +

    // u e iterator to acce the value vector7int8$$iterator v = vec.be2in(); while( v = vec.end()) # cout 77 9value of v = 9 77 *v 77 endl; v ; +

    return ;

    +

    When the a'o)e code is compiled and e ecuted, it produces the follo%in$ result:

    vector ize = e tended vector ize = value of vec I J = value of vec I3J = 3value of vec I J = value of vec IBJ = Bvalue of vec IAJ = Avalue of v = value of v = 3value of v = value of v = Bvalue of v = A

    8ere are follo%in$ points to 'e noted related to )arious functions %e used in the a'o)e e ample:

    • The push>'ack7 9 mem'er function inserts )alue at the end of the )ector, e pandin$ itssi?e as needed.

    • The si?e7 9 function displays the si?e of the )ector.

    • The function 'e$in7 9 returns an iterator to the start of the )ector.

    • The function end7 9 returns an iterator to the end of the )ector.

    *F'- 0 at i$ Tem56ate $5ecia6iGation7 0rite a 5rogram to im56ement tem56ate$5ecia6iGation8 1 /

    22

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    23/24

    An$' - Tem56ate $5ecia6iGation

    *t is possi'le to define a different implementation for a template %hen a specific type is passed astemplate ar$ument. This is called a template specialization .

    Bor e ample, let s suppose that %e ha)e a )ery simple class called mycontainer that can store oneelement of any type and that has (ust one mem'er function called increase, %hich increases its)alue. ut %e find that %hen it stores an element of type char it %ould 'e more con)enient toha)e a completely different implementation %ith a function mem'er uppercase, so %e decide todeclare a class template speciali?ation for that type:

    // template specialization#include using namespace td;

    // class template:template 7 class H8

    class ycontainer # H ele ent; public $ ycontainer (H ar2) #ele ent=ar2;+ H increa e () # return ele ent;++;

    // class template specialization:template 78class ycontainer 7 char 8 # char ele ent; public $ ycontainer ( char ar2) #ele ent=ar2;+ char upperca e () # if ((ele ent8=KaK)&&(ele ent7=KzK)) ele ent =K!K-KaK; return ele ent; ++;

    int ain () # ycontainer7 int 8 yint (0); ycontainer7 char 8 ychar (K K); cout 77 yint.increa e() 77 endl; cout 77 ychar.upperca e() 77 endl; return ;

    +

    This is the synta used for the class template speciali?ation:

    template 78 class ycontainer 7 char 8 # ... +;

    Birst of all, notice that %e precede the class name %ith template , includin$ an empty parameter list. This is 'ecause all types are kno%n and no template ar$uments are re#uired for

    23

  • 8/15/2019 C++ Sample paper(NewSyllabus)

    24/24

    this speciali?ation, 'ut still, it is the speciali?ation of a class template, and thus it re#uires to 'enoted as such.

    ut more important than this prefi , is the char speciali?ation parameter after the classtemplate name. This speciali?ation parameter itself identifies the type for %hich the templateclass is 'ein$ speciali?ed 7char9. Notice the differences 'et%een the $eneric class template andthe speciali?ation:

    3 template 7 class H8 class ycontainer # ... +;template 78 class ycontainer 7 char 8 # ... +;

    The first line is the $eneric template, and the second one is the speciali?ation.

    When %e declare speciali?ations for a template class, %e must also define all its mem'ers, e)en

    those identical to the $eneric template class, 'ecause there is no 6inheritance6 of mem'ers fromthe $eneric template to the speciali?ation.

    24