C++ Aptitude With Ans and Explanation

  • Upload
    adddata

  • View
    224

  • Download
    0

Embed Size (px)

Citation preview

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    1/24

    BALA KRISHNA.A KRISHNA ACADEMY

    C++ Aptitude and OOPSC++ Aptitude and OOPS

    1) class Sample

    {public: int *ptr; Sample(int i) { ptr = new int(i); } ~Sample() { delete ptr; }

    void PrintVal() { cout !"#e value is ! *ptr; }};void Some$unc(Sample %){cout !Sa& i am in some$unc ! endl;}int main(){Sample s1= 1';Some$unc(s1);s1PrintVal();}

    Answer:Sa& i am in some$uncull pointer assinment(+un,time error)

    Explanation:-s t#e ob.ect is passed b& value to Some$unc t#e destructor o/ t#e

    ob.ect is called w#en t#e control returns /rom t#e /unction So w#enPrintVal is called it meets up wit# ptr t#at #as been /reed"#e solution isto pass t#e Sample ob.ect b&referenceto Some$unc:

    void Some$unc(Sample 0%){cout !Sa& i am in some$unc ! endl;}

    because when we pass objects by refernece that object is notdestroyed. while returning from the function.

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    1

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    2/24

    BALA KRISHNA.A KRISHNA ACADEMY

    ) @#ic# is t#e parameter t#at is added to ever& non,static member/unction w#en it is calledA

    Answer: Bt#isC pointer

    D) class base

    { public: int bval; base(){ bval=';} };

    class deri:public base { public: int dval; deri(){ dval=1;} };void Some$unc(base *arr3int si5e){/or(int i='; isi5e; iEE3arrEE) coutarr,Fbval;coutendl;}

    int main(){

    base Gase-rrHIJ;Some$unc(Gase-rr3I);deri Keri-rrHIJ;Some$unc(Keri-rr3I);}

    Answer:''''''1'1'

    Explanation:"#e /unction Some$unc e%pects two aruments"#e /irst one is a

    pointer to an arra& o/ base class ob.ects and t#e second one is t#e si5eo/t#e arra&"#e /irst call o/ some$unc calls it wit# an arra& o/ bae ob.ects3 soit worLs correctl& and prints t#e bval o/ all t#e ob.ects @#en Some/unc iscalled t#e second time t#e arument passed is t#e pointeer to an arra& o/derived class ob.ects and not t#e arra& o/ base class ob.ects Gut t#at isw#at t#e /unction e%pects to be sent So t#e derived class pointer ispromoted to base class pointer and t#e address is sent to t#e /unctionSome$unc() Lnows not#in about t#is and .ust treats t#e pointer as anarra& o/ base class ob.ects So w#en arrEE is met3 t#e si5e o/ base classob.ect is taLen into consideration and is incremented b& si5eo/(int) b&tes

    /or bval (t#e deri class ob.ects #ave bval and dval as members and so is o/si5e F= si5eo/(int)Esi5eo/(int) )

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    2

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    3/24

    BALA KRISHNA.A KRISHNA ACADEMY

    2) class base { public: void base$un(){ cout!/rom base!endl;} };

    class deri:public base { public: void base$un(){ cout !/rom derived!endl;} };void Some$unc(base *baseMb.){ baseMb.,Fbase$un();}int main(){base baseMb.ect;Some$unc(0baseMb.ect);deri deriMb.ect;Some$unc(0deriMb.ect);}

    Answer:/rom base/rom base

    Explanation:-s we #ave seen in t#e previous case3 Some$unc e%pects a pointer

    to a base class Since a pointer to a derived class ob.ect is passed3 ittreats t#e arument onl& as a base class pointer and t#e correspondinbase /unction is called

    I) class base { public: virtual void base$un(){ cout!/rom base!endl;} };class deri:public base {

    public: void base$un(){ cout !/rom derived!endl;} };

    void Some$unc(base *baseMb.){ baseMb.,Fbase$un();}

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    3

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    4/24

    BALA KRISHNA.A KRISHNA ACADEMY

    int main(){base baseMb.ect;Some$unc(0baseMb.ect);

    deri deriMb.ect;Some$unc(0deriMb.ect);}

    Answer:/rom base/rom derived

    Explanation:+emember t#at base$unc is a virtual /unction "#at means t#at it

    supports run,time pol&morp#ism So t#e /unction correspondin to t#ederived class ob.ect is called

    void main(){

    int a3 *pa3 0ra;pa = 0a;ra = a;cout !a=!a !*pa=!*pa !ra!ra ;

    }N*-nswer :

    6ompiler >rror: OraO3re/erence must be initiali5ed>%planation :

    Pointers are di//erent /rom re/erences Mne o/ t#e maindi//erences is t#at t#e pointers can be bot# initiali5ed and assined3w#ereas re/erences can onl& be initiali5ed So t#is code issues an error*Nconst int si5e = I;void print(int *ptr){

    coutptrH'J;}

    void print(int ptrHsi5eJ){

    coutptrH'J;}void main(){

    int aHsi5eJ = {133D323I};int *b = new int(si5e);print(a);print(b);

    }N*

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    4

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    5/24

    BALA KRISHNA.A KRISHNA ACADEMY

    -nswer:6ompiler >rror : /unction Ovoid print(int *)O alread& #as a bod&

    >%planation:-rra&s cannot be passed to /unctions3 onl& pointers (/or arra&s3 base

    addresses)can be passed So t#e aruments int *ptr and int prtHsi5eJ #ave nodi//erenceas /unction aruments n ot#er words3 bot# t#e /unctoins #ave t#e samesinature andso cannot be overloaded*N

    class some{public:

    ~some(){

    cout!someOs destructor!endl;}

    };

    void main(){

    some s;s~some();

    }

    N*-nswer:

    someOs destructorsomeOs destructor

    >%planation:Kestructors can be called e%plicitl& 9ere Os~some()O e%plicitl& calls

    t#edestructor o/ OsO @#en main() returns3 destructor o/ s is called aain3#ence t#e result*N

    include iostream#F

    class /id{

    int dim1;int dim;

    public:/id() { dim1=I; dim=

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    6/24

    BALA KRISHNA.A KRISHNA ACADEMY

    void /id::operator(ostream 0r#s){

    r#s t#is,Fdim1! !t#is,Fdim! !;}

    N*class /iDd : public /id{

    int dimD;public:

    /iDd() { dimD=Q;}virtual void operator(ostream 0r#s);

    };void /iDd::operator(ostream 0r#s){

    /id::operator (r#s);r#st#is,FdimD;

    }*N

    void main(){

    /id ob.1;NN /iDd ob.;

    ob.1 cout;NN ob. cout;}N*-nswer :

    I %planation:

    n t#is proram3 t#e operator is overloaded wit# ostream asarument

    "#is enables t#e OcoutO to be present at t#e ri#t,#and,side ormall&3

    OcoutOis implemented as lobal /unction3 but it doesnOt mean t#at OcoutO is notpossibleto be overloaded as member /unction Mverloadin as virtual member /unction becomes #and& w#en t#eclass in w#ic#it is overloaded is in#erited3 and t#is becomes available to be overrided

    "#is is as opposedto lobal /riend /unctions3 w#ere /riendOs are not in#erited*N

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    6

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    7/24

    BALA KRISHNA.A KRISHNA ACADEMY

    class opMverload{

    public:bool operator==(opMverload temp);

    };

    bool opMverload::operator==(opMverload temp){i/(*t#is == temp ){

    cout!"#e bot# are same ob.ectsRn!;return true;

    }else{

    cout!"#e bot# are di//erentRn!;return /alse;

    }}void main(){

    opMverload a13 a;a1= =a;

    }

    -nswer :+untime >rror: StacL Mver/low

    >%planation :8ust liLe normal /unctions3 operator /unctions can be called

    recursivel& "#is proram .ust illustrates t#at point3 b& callin t#e operator== /unction recursivel&3 leadin to an in/inite loop

    class comple%{double re;double im;

    public:comple%() : re(1)3im('I) {}bool operator==(comple% 0r#s);

    operator int(){}};

    bool comple%::operator == (comple% 0r#s){i/((t#is,Fre == r#sre) 00 (t#is,Fim == r#sim))

    return true;else

    return /alse;}

    int main(){comple% c1;

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    7

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    8/24

    BALA KRISHNA.A KRISHNA ACADEMY

    cout c1;}-nswer : arbae value

    >%planation:

    "#e prorammer wis#es to print t#e comple% ob.ect usin outputre,direction operator3w#ic# #e #as not de/ined /or #is lassGut t#ecompiler instead o/ ivin an error sees t#e conversion /unctionand converts t#e user de/ined ob.ect to standard ob.ect and printssome arbae value

    class comple%{double re;double im;

    public:comple%() : re(')3im(') {}comple%(double n) { re=n3im=n;};comple%(int m3int n) { re=m3im=n;}void print() { coutre; coutim;}

    };

    void main(){comple% cD;double i=I;cD = i;

    cDprint();}

    -nswer:I3I

    >%planation:"#ou# no operator= /unction taLin comple%3 double is de/ined3

    t#e double on t#e r#s is converted into a temporar& ob.ect usin t#esinle arument constructor taLin double and assined to t#e lvalue

    void main()

    {int a3 *pa3 0ra;pa = 0a;ra = a;cout !a=!a !*pa=!*pa !ra!ra ;

    }

    -nswer : 6ompiler >rror: OraO3re/erence must be initiali5ed>%planation :

    Pointers are di//erent /rom re/erences Mne o/ t#e main

    di//erences is t#at t#e pointers can be bot# initiali5ed and assined3w#ereas re/erences can onl& be initiali5ed So t#is code issues an error

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    8

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    9/24

    BALA KRISHNA.A KRISHNA ACADEMY

    1) Ketermine t#e output o/ t#e O6EEO 6odelet

    class base{public :

    out(){

    cout!base !;}

    };class deri{public : out(){cout!deri !;}};void main(){ deri dpHDJ;

    base *bp = (base*)dp;/or (int i='; iD;iEE)(bpEE),Fout();

    }

    ) 8usti/& t#e use o/ virtual constructors and destructors in 6EE

    D) >ac# 6EE ob.ect possesses t#e 2 member /ns3(w#ic# can be declaredb& t#e prorammer e%plicitl& or b& t#e implementation i/ t#e& are notavailable) @#at are t#ose 2 /unctionsA

    2) @#at is wron wit# t#is class declarationAclass somet#in{

    c#ar *str;public:

    somet#in(){ st = new c#arH1'J; } ~somet#in() {

    delete str;}

    };

    I) n#eritance is also Lnown as ,,,,,,,, relations#ip 6ontainers#ip asTTTTTTTT relations#ip

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    9

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    10/24

    BALA KRISHNA.A KRISHNA ACADEMY

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    11/24

    BALA KRISHNA.A KRISHNA ACADEMY

    1. What is a modifier?Answer: - modi/ier3 also called a modi/&in /unction is a member /unctiont#at c#anes t#e value o/ at least one data member n ot#er words3 anoperation t#at modi/ies t#e state o/ an ob.ect 4odi/iers are also Lnown as

    BmutatorsC

    2. What is an accessor?Answer: -n accessor is a class operation t#at does not modi/& t#e state o/an ob.ect "#e accessor /unctions need to be declared as constoperations

    3. Differentiate between a template class and class template.Answer:Template class:

    - eneric de/inition or a parameteri5ed class not instantiated untilt#e client provides t#e needed in/ormation tCs .aron /or plain templatesClass template:

    - class template speci/ies #ow individual classes can be constructedmuc# liLe t#e wa& a class speci/ies #ow individual ob.ects can beconstructed tCs .aron /or plain classes

    4. When does a name clash occur?Answer: - name clas# occurs w#en a name is de/ined in more t#an oneplace $or e%ample3 two di//erent class libraries could ive two di//erent

    classes t#e same name / &ou tr& to use man& class libraries at t#e sametime3 t#ere is a /air c#ance t#at &ou will be unable to compile or linL t#eproram because o/ name clas#es

    5. Define namespace.Answer:

    t is a /eature in cEE to minimi5e name collisions in t#e lobal namespace "#is namespace Le&word assins a distinct name to a librar& t#atallows ot#er libraries to use t#e same identi/ier names wit#out creatinan& name collisions $urt#ermore3 t#e compiler uses t#e namespacesinature /or di//erentiatin t#e de/initions

    6. What is the use of using declaration.Answer:

    - usin declaration maLes it possible to use a name /rom anamespace wit#out t#e scope operator

    !. What is an "terator class?Answer:

    - class t#at is used to traverse t#rou# t#e ob.ects maintained b& acontainer class "#ere are /ive cateories o/ iterators:

    input iterators3

    output iterators3

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    11

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    12/24

    BALA KRISHNA.A KRISHNA ACADEMY

    /orward iterators3

    bidirectional iterators3

    random access-n iterator is an entit& t#at ives access to t#e contents o/ a

    container ob.ect wit#out violatin encapsulation constraints -ccess to t#econtents is ranted on a one,at,a,time basis in order "#e order can bestorae order (as in lists and Uueues) or some arbitrar& order (as in arra&indices) or accordin to some orderin relation (as in an ordered binar&tree) "#e iterator is a construct3 w#ic# provides an inter/ace t#at3 w#encalled3 &ields eit#er t#e ne%t element in t#e container3 or some valuedenotin t#e /act t#at t#ere are no more elements to e%amine terators#ide t#e details o/ access to and update o/ t#e elements o/ a containerclass

    "#e simplest and sa/est iterators are t#ose t#at permit read,onl&access to t#e contents o/ a container class "#e /ollowin code /rament

    s#ows #ow an iterator mi#t appear in code: contTiter:=new contTiterator(); %:=contTiterne%t(); w#ile %N=none do s(%); %:=contTiterne%t(); end; n t#is e%ample3 contTiter is t#e name o/ t#e iterator t is created ont#e /irst line b& instantiation o/ contTiterator class3 an iterator class

    de/ined to iterate over some container class3 cont Succesive elements/rom t#e container are carried to % "#e loop terminates w#en % is boundto some empt& value (9ere3 none)n t#e middle o/ t#e loop3 t#ere is s(%)an operation on %3 t#e current element /rom t#e container "#e ne%telement o/ t#e container is obtained at t#e bottom o/ t#e loop

    #. $ist out some of the %%D&'( a)ailable.Answer:

    >4S"M>NMP-7 o/ emstone s&stems

    M"MS o/ Mntos

    Mb.ectivit& o/ Mb.ectivit& inc Versant o/ Versant ob.ect tec#nolo&

    Mb.ect store o/ Mb.ect Kesin

    -+K>" o/ -+K>" so/tware

    PM>" o/ PM>" so/tware

    1*. $ist out some of the ob+ect,oriented methodologies.Answer:

    Mb.ect Mriented Kevelopment (MMK) (Gooc# 11312)

    Mb.ect Mriented -nal&sis and Kesin (MM-NK) (6oad and ourdon

    11) Mb.ect 4odellin "ec#niUues (M4") (+umbau# 11)

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    12

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    13/24

    BALA KRISHNA.A KRISHNA ACADEMY

    Mb.ect Mriented So/tware >nineerin (Mb.ector&) (8acobson 1)

    Mb.ect Mriented -nal&sis (MM-) (S#laer and 4ellor 1)

    "#e $usion 4et#od (6oleman 11)

    11. What is an incomplete t-pe?

    Answer: ncomplete t&pes re/ers to pointers in w#ic# t#ere is non availabilit&o/ t#e implementation o/ t#e re/erenced location or it points to somelocation w#ose value is not available /or modi/icationExample: int *i='%2'' NN i points to address 2'' *i='; NNset t#e value o/ memor& location pointed b& incomplete t&pes are ot#erwise called uninitiali5ed pointers

    12. What is a dangling pointer?

    Answer:- danlin pointer arises w#en &ou use t#e address o/ an ob.ecta/ter its li/etime is over

    "#is ma& occur in situations liLe returnin addresses o/ t#e automaticvariables /rom a /unction or usin t#e address o/ t#e memor& blocL a/ter itis /reed

    13. Differentiate between the message and method.Answer:

    Message Method Mb.ects communicate b& sendin

    messaes to eac# ot#er

    Provides response to a messae

    - messae is sent to invoLe amet#od

    t is an implementation o/ anoperation

    14. What is an adaptor class or Wrapper class?

    Answer:- class t#at #as no /unctionalit& o/ its own ts member /unctions

    #ide t#e use o/ a t#ird part& so/tware component or an ob.ect wit# t#enon,compatible inter/ace or a non, ob.ect, oriented implementation

    15. What is a ull ob+ect?Answer:

    t is an ob.ect o/ some class w#ose purpose is to indicate t#at a realob.ect o/ t#at class does not e%ist Mne common use /or a null ob.ect is areturn value /rom a member /unction t#at is supposed to return an ob.ectwit# some speci/ied properties but cannot /ind suc# an ob.ect

    16. What is class in)ariant?Answer:

    - class invariant is a condition t#at de/ines all valid states /or an

    ob.ect t is a loical condition to ensure t#e correct worLin o/ a class6lass invariants must #old w#en an ob.ect is created3 and t#e& must be

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    13

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    14/24

    BALA KRISHNA.A KRISHNA ACADEMY

    preserved under all operations o/ t#e class n particular all classinvariants are bot# preconditions and post,conditions /or all operations ormember /unctions o/ t#e class

    1!. What do -ou mean b- (tac/ unwinding?

    Answer:t is a process durin e%ception #andlin w#en t#e destructor is

    called /or all local ob.ects between t#e place w#ere t#e e%ception wast#rown and w#ere it is cau#t10. Define precondition and post,condition to a member function.

    Answer:Precondition: - precondition is a condition t#at must be true on entr& to amember /unction - class is used correctl& i/ preconditions are never /alse-n operation is not responsible /or doin an&t#in sensible i/ itsprecondition /ails to #old

    $or e%ample3 t#e inter/ace invariants o/ stac/ class sa& not#inabout pus#in &et anot#er element on a stacL t#at is alread& /ull @e sa&t#at isfulis a precondition o/ t#epushoperation

    Post-condition: - post,condition is a condition t#at must be true on e%it /rom amember /unction i/ t#e precondition was valid on entr& to t#at /unction -class is implemented correctl& i/ post,conditions are never /alse

    $or e%ample3 a/ter pus#in an element on t#e stacL3 we Lnow t#at

    isempt- must necessaril& #old "#is is a post,condition o/ t#e pushoperation

    1! "hat are the conditions that ha#e to $e met %or a conditionto $e an in#ariant o% the class&

    Answer:

    "#e condition s#ould #old at t#e end o/ ever& constructor

    "#e condition s#ould #old at t#e end o/ ever& mutator(non,const)operation

    '(! "hat are prox) o$*ects&

    Answer:Mb.ects t#at stand /or ot#er ob.ects are called pro%& ob.ects or

    surroatesExample: templateclass "F class -rra&K

    { public: class -rra&1K {

    public: "0 operatorHJ (int inde%);

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    14

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    15/24

    BALA KRISHNA.A KRISHNA ACADEMY

    const "0 operatorHJ (int inde%) const; }; -rra&1K operatorHJ (int inde%); const -rra&1K operatorHJ (int inde%) const;

    };

    "#e /ollowin t#en becomes leal: -rra&K/loatFdata(1'3'); coutdataHDJH

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    16/24

    BALA KRISHNA.A KRISHNA ACADEMY

    24. What is an orthogonal base class?

    Answer:/ two base classes #ave no overlappin met#ods or data t#e& are

    said to be independent o/3 or ort#oonal to eac# ot#er Mrt#oonal in t#esense means t#at two classes operate in di//erent dimensions and do notinter/ere wit# eac# ot#er in an& wa& "#e same derived class ma& in#eritsuc# classes wit# no di//icult&

    25. What is a container class? What are the t-pes of container classes?Answer:

    - container class is a class t#at is used to #old ob.ects in memor& ore%ternal storae - container class acts as a eneric #older - containerclass #as a prede/ined be#avior and a well,Lnown inter/ace - containerclass is a supportin class w#ose purpose is to #ide t#e topolo& used /ormaintainin t#e list o/ ob.ects in memor& @#en a container class containsa roup o/ mi%ed ob.ects3 t#e container is called a #eteroeneouscontainer; w#en t#e container is #oldin a roup o/ ob.ects t#at are all t#esame3 t#e container is called a #omoeneous container

    26. What is a protocol class?Answer:

    -n abstract class is a protocol class i/:

    it neit#er contains nor in#erits /rom classes t#at contain memberdata3 non,virtual /unctions3 or private (or protected) members o/ an&Lind

    it #as a non,inline virtual destructor de/ined wit# an empt&implementation3

    all member /unctions ot#er t#an t#e destructor includin in#erited/unctions3 are declared pure virtual /unctions and le/t unde/ined

    2!. What is a miin class?Answer:

    - class t#at provides some but not all o/ t#e implementation /or avirtual base class is o/ten called mi%in Kerivation done .ust /or t#epurpose o/ rede/inin t#e virtual /unctions in t#e base classes is o/tencalled mi%in in#eritance 4i%in classes t&picall& donOt s#are commonbases

    20. What is a concrete class?Answer:

    - concrete class is used to de/ine a use/ul ob.ect t#at can beinstantiated as an automatic variable on t#e proram stacL "#eimplementation o/ a concrete class is de/ined "#e concrete class is not

    intended to be a base class and no attempt to minimi5e dependenc& onot#er classes in t#e implementation or be#avior o/ t#e class

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    16

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    17/24

    BALA KRISHNA.A KRISHNA ACADEMY

    2#.What is the handle class?Answer:- #andle is a class t#at maintains a pointer to an ob.ect t#at isprorammaticall& accessible t#rou# t#e public inter/ace o/ t#e #andleclass

    Explanation:n case o/ abstract classes3 unless one manipulates t#e ob.ects o/

    t#ese classes t#rou# pointers and re/erences3 t#e bene/its o/ t#e virtual/unctions are lost Wser code ma& become dependent on details o/implementation classes because an abstract t&pe cannot be allocatedstatisticall& or on t#e stacL wit#out its si5e bein Lnown Wsin pointers orre/erences implies t#at t#e burden o/ memor& manaement /alls on t#euser -not#er limitation o/ abstract class ob.ect is o/ /i%ed si5e 6lasses#owever are used to represent concepts t#at reUuire var&in amounts o/storae to implement t#em- popular tec#niUue /or dealin wit# t#ese issues is to separate w#at isused as a sinle ob.ect in two parts: a #andle providin t#e user inter/aceand a representation #oldin all or most o/ t#e ob.ectOs state "#econnection between t#e #andle and t#e representation is t&picall& apointer in t#e #andle M/ten3 #andles #ave a bit more data t#an t#e simplerepresentation pointer3 but not muc# more 9ence t#e la&out o/ t#e#andle is t&picall& stable3 even w#en t#e representation c#anes and alsot#at #andles are small enou# to move around relativel& /reel& so t#at t#euser neednCt use t#e pointers and t#e re/erences

    3*. What is an action class?

    Answer:"#e simplest and most obvious wa& to speci/& an action in 6EE is to

    write a /unction 9owever3 i/ t#e action #as to be dela&ed3 #as to betransmitted Oelsew#ereO be/ore bein per/ormed3 reUuires its own data3#as to be combined wit# ot#er actions3 etc t#en it o/ten becomesattractive to provide t#e action in t#e /orm o/ a class t#at can e%ecute t#edesired action and provide ot#er services as well 4anipulators used wit#iostreams is an obvious e%ampleExplanation:

    A common form of action class is a simple class containingjust one virtual function.

    class -ction { public: virtual int doTit( int )='; virtual ~-ction( ); }

    Given this we can write code say a member that can storeactions for later e!ecution without using pointers to functionswithout "nowing anything about the objects involved andwithout even "nowing the name of the operation it invo"es. #ore!ample$

    class writeT/ile : public -ction { $ile0 /;

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    17

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    18/24

    BALA KRISHNA.A KRISHNA ACADEMY

    public: int doTit(int) { return /write( )suceed( ); }

    }; class errorTmessae: public -ction { responseTbo% db(messaecstr( )3!6ontinue!3!6ancel!3!+etr&!); switc# (dbetresponse( )) { case ': return '; case 1: abort(); case : currentToperationredo( );return 1; } };

    - user o/ t#e -ction class will be completel& isolated /rom an&Lnowlede o/ derived classes suc# as writeT/ile and errorTmessae

    31. When can -ou tell that a memor- lea/ will occur?Answer:

    - memor& leaL occurs w#en a proram loses t#e abilit& to /ree ablocL o/ d&namicall& allocated memor&

    32.What is a parameteried t-pe?

    Answer:- template is a parameteri5ed construct or t&pe containin eneric

    code t#at can use or manipulate an& t&pe t is called parameteri5edbecause an actual t&pe is a parameter o/ t#e code bod& Pol&morp#ismma& be ac#ieved t#rou# parameteri5ed t&pes "#is t&pe o/ pol&morp#ismis called parameteric pol&morp#ism Parameteric pol&morp#ism is t#emec#anism b& w#ic# t#e same code is used on di//erent t&pes passed asparameters

    33. Differentiate between a deep cop- and a shallow cop-?

    Answer:Keep cop& involves usin t#e contents o/ one ob.ect to createanot#er instance o/ t#e same class n a deep cop&3 t#e two ob.ects ma&contain #t same in/ormation but t#e taret ob.ect will #ave its own bu//ersand resources t#e destruction o/ eit#er ob.ect will not a//ect t#eremainin ob.ect "#e overloaded assinment operator would create adeep cop& o/ ob.ects

    S#allow cop& involves cop&in t#e contents o/ one ob.ect intoanot#er instance o/ t#e same class t#us creatin a mirror imae Mwin tostrai#t cop&in o/ re/erences and pointers3 t#e two ob.ects will s#are t#esame e%ternall& contained contents o/ t#e ot#er ob.ect to be

    unpredictableExplanation:

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    18

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    19/24

    BALA KRISHNA.A KRISHNA ACADEMY

    Wsin a cop& constructor we simpl& cop& t#e data values memberb& member "#is met#od o/ cop&in is called s#allow cop& / t#e ob.ect isa simple class3 comprised o/ built in t&pes and no pointers t#is would beacceptable "#is /unction would use t#e values and t#e ob.ects and itsbe#avior would not be altered wit# a s#allow cop&3 onl& t#e addresses o/

    pointers t#at are members are copied and not t#e value t#e address ispointin to "#e data values o/ t#e ob.ect would t#en be inadvertentl&altered b& t#e /unction @#en t#e /unction oes out o/ scope3 t#e cop& o/t#e ob.ect wit# all its data is popped o// t#e stacL

    / t#e ob.ect #as an& pointers a deep cop& needs to be e%ecuted@it# t#e deep cop& o/ an ob.ect3 memor& is allocated /or t#e ob.ect in /reestore and t#e elements pointed to are copied - deep cop& is used /orob.ects t#at are returned /rom a /unction

    34. What is an opaue pointer?Answer:

    - pointer is said to be opaUue i/ t#e de/inition o/ t#e t&pe to w#ic# itpoints to is not included in t#e current translation unit - translation unit ist#e result o/ merin an implementation /ile wit# all its #eaders and#eader /iles

    35. What is a smart pointer?Answer:

    - smart pointer is an ob.ect t#at acts3 looLs and /eels liLe a normalpointer but o//ers more /unctionalit& n 6EE3 smart pointers areimplemented as template classes t#at encapsulate a pointer and override

    standard pointer operators "#e& #ave a number o/ advantaes overreular pointers "#e& are uaranteed to be initiali5ed as eit#er nullpointers or pointers to a #eap ob.ect ndirection t#rou# a null pointer isc#ecLed o delete is ever necessar& Mb.ects are automaticall& /reedw#en t#e last pointer to t#em #as one awa& Mne sini/icant problemwit# t#ese smart pointers is t#at unliLe reular pointers3 t#e& donOtrespect in#eritance Smart pointers are unattractive /or pol&morp#ic codeiven below is an e%ample /or t#e implementation o/ smart pointersExample:

    template class XF class smartTpointer

    { public: smartTpointer(); NN maLes a null pointer smartTpointer(const X0 %) NN maLes pointer to cop& o/ %

    X0 operator *( ); const X0 operator*( ) const; X* operator,F() const;

    smartTpointer(const smartTpointer XF 0);

    const smartTpointer XF 0 operator =(constsmartTpointerXF0);

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    19

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    20/24

    BALA KRISHNA.A KRISHNA ACADEMY

    ~smartTpointer(); private: NN };

    "#is class implement a smart pointer to an ob.ect o/ t&pe X "#e

    ob.ect itsel/ is located on t#e #eap 9ere is #ow to use it: smartTpointer emplo&eeF p= emplo&ee(!9arris!31DDD);7iLe ot#er overloaded operators3 p will be#ave liLe a reular pointer3cout*p;p,FraiseTsalar&('I);

    36. What is reflei)e association?Answer:

    "#e Ois,aO is called a re/le%ive association because t#e re/le%iveassociation permits classes to bear t#e is,a association not onl& wit# t#eirsuper,classes but also wit# t#emselves t di//ers /rom a Ospeciali5es,/romOas Ospeciali5es,/romO is usuall& used to describe t#e association between asuper,class and a sub,class $or e%ample:

    Printer is,a printer

    3!. What is slicing?Answer:

    Slicin means t#at t#e data added b& a subclass are discarded w#enan ob.ect o/ t#e subclass is passed or returned b& value or /rom a /unctione%pectin a base class ob.ectExplanation:

    6onsider t#e /ollowin class declaration: class base { base0 operator =(const base0); base (const base0); } void /un( ) { base e=m; e=m;

    }-s base cop& /unctions donOt Lnow an&t#in about t#e derived onl&

    t#e base part o/ t#e derived is copied "#is is commonl& re/erred to asslicin Mne reason to pass ob.ects o/ classes in a #ierarc#& is to avoidslicin Mt#er reasons are to preserve pol&morp#ic be#avior and to aine//icienc&

    30. What is name mangling?Answer:

    ame manlin is t#e process t#rou# w#ic# &our cEE compilers ive

    eac# /unction in &our proram a uniUue name n 6EE3 all prorams#ave at,least a /ew /unctions wit# t#e same name ame manlin is a

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    20

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    21/24

    BALA KRISHNA.A KRISHNA ACADEMY

    concession to t#e /act t#at linLer alwa&s insists on all /unction namesbein uniUue

    Example:n eneral3 member names are made uniUue b& concatenatin t#e

    name o/ t#e member wit# t#at o/ t#e class e iven t#e declaration: class Gar { public:

    int ival; };

    ival becomes somet#in liLe: NN a possible member name manlin ivalTTDGar6onsider t#is derivation: class $oo : public Gar

    {public:

    int ival; }

    "#e internal representation o/ a $oo ob.ect is t#e concatenation o/ itsbase and derived class members

    NN Pseudo 6EE code NN nternal representation o/ $oo class $oo { public:

    int ivalTTDGar; int ivalTTD$oo; };

    Wnambiuous access o/ eit#er ival members is ac#ieved t#rou# namemanlin 4ember /unctions3 because t#e& can be overloaded3 reUuirean e%tensive manlin to provide eac# wit# a uniUue name 9ere t#ecompiler enerates t#e same name /or t#e two overloadedinstances("#eir arument lists maLe t#eir instances uniUue)

    3#. What are pro- ob+ects?Answer:

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    21

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    22/24

    BALA KRISHNA.A KRISHNA ACADEMY

    Mb.ects t#at points to ot#er ob.ects are called pro%& ob.ects orsurroates ts an ob.ect t#at provides t#e same inter/ace as its serverob.ect but does not #ave an& /unctionalit& Kurin a met#od invocation3 itroutes data to t#e true server ob.ect and sends bacL t#e return value tot#e ob.ect

    4*. Differentiate between declaration and definition in 77.Answer:

    - declaration introduces a name into t#e proram; a de/inition providesa uniUue description o/ an entit& (e t&pe3 instance3 and /unction)Keclarations can be repeated in a iven scope3 it introduces a name ina iven scope "#ere must be e%actl& one de/inition o/ ever& ob.ect3/unction or class used in a 6EE proram

    - declaration is a de/inition unless:

    it declares a /unction wit#out speci/&in its bod&3

    it contains an e%tern speci/ier and no initiali5er or /unction bod&3

    it is t#e declaration o/ a static class data member wit#out a classde/inition3

    it is a class name de/inition3

    it is a t&pede/ declarationA definition is a declaration unless$

    it de/ines a static class data member3

    it de/ines a non,inline member /unction41. What is cloning?

    Answer: -n ob.ect can carr& out cop&in in two wa&s ie it can set itsel/to be a cop& o/ anot#er ob.ect3 or it can return a cop& o/ itsel/ "#e latter

    process is called clonin

    42. Describe the main characteristics of static functions.Answer:

    "#e main c#aracteristics o/ static /unctions include3

    t is wit#out t#e a t#is pointer3

    t canOt directl& access t#e non,static members o/ its class

    t canOt be declared const3 volatile or virtual

    t doesnOt need to be invoLed t#rou# an ob.ect o/ its class3alt#ou# /or convenience3 it ma&

    43. Will the inline function be compiled as the inline function alwa-s?8ustif-.Answer:

    -n inline /unction is a reUuest and not a command 9ence it wonOtbe compiled as an inline /unction alwa&sExplanation:

    nline,e%pansion could /ail i/ t#e inline /unction contains loops3 t#eaddress o/ an inline /unction is used3 or an inline /unction is called in acomple% e%pression "#e rules /or inlinin are compiler dependent

    44. Define a wa- other than using the /e-word inline to ma/e a functioninline.

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    22

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    23/24

    BALA KRISHNA.A KRISHNA ACADEMY

    Answer:"#e /unction must be de/ined inside t#e class

    45. 9ow can a :;;: operator be used as unar- operator?Answer:

    "#e scope operator can be used to re/er to members o/ t#e lobalnamespace Gecause t#e lobal namespace doesnCt #ave a name3 t#enotation :: member,name re/ers to a member o/ t#e lobal namespace

    "#is can be use/ul /or re/errin to members o/ lobal namespace w#osenames #ave been #idden b& names declared in nested local scope Wnlesswe speci/& to t#e compiler in w#ic# namespace to searc# /or adeclaration3 t#e compiler simple searc#es t#e current scope3 and an&scopes in w#ic# t#e current scope is nested3 to /ind t#e declaration /or t#ename

    46. What is placement new?Answer:

    %hen you want to call a constructor directly you use theplacement new. Sometimes you have some raw memory that&salready been allocated and you need to construct an object inthe memory you have. Operator new&s special version placementnew allows you to do it. class @idet { public : @idet(int widetsi5e);

    @idet* 6onstructTwidetTintTbu//er(void *bu//er3intwidetsi5e) { return new(bu//er) @idet(widetsi5e); } };

    'his function returns a pointer to a %idget object that&sconstructed within the buffer passed to the function. Such afunction might be useful for applications using shared memory ormemory(mapped )*O because objects in such applications must

    be placed at specific addresses or in memory allocated by specialroutines.

    $lat o 1'23 1st$loor3 4an5il 6#ambers3 7ane -d. to 8a&ab#us#an 9ospital3 9&derabad6ontact: 2< 1,mail: annalurib?mailcom

    23

  • 7/27/2019 C++ Aptitude With Ans and Explanation

    24/24

    BALA KRISHNA.A KRISHNA ACADEMY24