TEXAS Instruments Placement Sample Paper 5

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

Texas Instruments Technical Test 2005

1. Can we declare a static function as virtual? Ans: No. The virtual function mechanism is used on the specific object that determines which virtual function to call. Since the static functions are not any way related to objects they cannot be declared as virtual. !. Can user"defined object be declared as static data member of another class? Ans: #es. The followin$ code shows how to initiali%e a user"defined object. &include class test ' int i ( public : test ) int ii * + , ' i * ii ( -( class sample ' static test s ( -( test sample::s ) !. , ( /ere we have initiali%ed the object s by callin$ the one"ar$ument constructor. 0e can use the same convention to initiali%e the object by callin$ multiple"ar$ument constructor. 1. 0hat is forward referencin$ and when should it be used? Ans: Consider the followin$ pro$ram: class test ' public : friend void fun ) sample test , ( -( class sample ' public : friend void fun ) sample test , ( -( void fun ) sample s test t , ' 22 code void main) , ' sample s ( test t (

fun ) s t , ( This pro$ram would not compile. 3t $ives an error that sample is undeclared identifier in the statement friend void fun ) sample test , ( of the class test. This is so because the class sample is defined below the class test and we are usin$ it before its definition. To overcome this error we need to $ive forward reference of the class sample before the definition of class test. The followin$ statement is the forward reference of class sample. 4orward referencin$ is $enerally re5uired when we ma6e a class or a function as a friend. 7. The istream8withassi$n class has been derived from the istream class and overloaded assi$nment operator has been added to it. The 8withassi$n classes are much li6e their base classes e9cept that they include overloaded assi$nment operators. :sin$ these operators the objects of the 8withassi$n classes can be copied. The istream ostream and iostream classes are made uncopyable by ma6in$ their overloaded copy constructor and assi$nment operators private. ;. /ow do 3 write my own %ero"ar$ument manipulator that should wor6 same as he9? Ans: This is shown in followin$ pro$ram. &include ostream< myhe9 ) ostream <o , ' o.setf ) ios::he9, ( return o ( void main) , ' cout == endl == myhe9 == !+++ ( ..0e all 6now that a const variable needs to be initiali%ed at the time of declaration. Then how come the pro$ram $iven below runs properly even when we have not initiali%ed p? &include void main) , ' const char >p ( p * ?A const pointer? ( cout == p ( Ans: The output of the above pro$ram is @A const pointer@. This is because in this pro$ram p is declared as @const char>@ which means that value stored at p will be constant and not p and so the pro$ram wor6s properly A. /ow do 3 refer to a name of class or function that is defined within a namespace? Ans: There are two ways in which we can refer to a name of class or function that is defined within a namespace: :sin$ scope resolution operator throu$h the usin$ 6eyword. This is shown in followin$ e9ample: namespace name1 ' class sample1

' 22 code -( namespace name! ' class sample! ' 22 code -( usin$ namespace name! ( void main) , ' name1::sample1 s1 ( sample! s! ( /ere class sample1 is referred usin$ the scope resolution operator. Bn the other hand we can directly refer to class sample! because of the statement usin$ namespace name! ( the usin$ 6eyword declares all the names in the namespace to be in the current scope. So we can use the names without any 5ualifiers. C. 0hile overloadin$ a binary operator can we provide default values? Ans: NoD. This is because even if we provide the default ar$uments to the parameters of the overloaded operator function we would end up usin$ the binary operator incorrectly. This is e9plained in the followin$ e9ample: sample operator E ) sample a sample b * sample )! 1.;f , , ' void main) , ' sample s1 s! s1 ( s1 * s1 E ( 22 error F. /ow do 3 carry out conversion of one object of user"defined type to another? Ans: To perform conversion from one user"defined type to another we need to provide conversion function. 4ollowin$ pro$ram demonstrates how to provide such conversion function. class circle ' private : int radius ( public: circle ) int r * + , ' radius * r ( -(

class rectan$le ' private : int len$th breadth ( public : rectan$le) int l int b , ' len$th * l ( breadth * b ( operator circle) , ' return circle ) len$th , ( -( void main) , ' rectan$le r ) !+ 1+ , ( circle c( c*r( /ere when the statement c * r ( is e9ecuted the compiler searches for an overloaded assi$nment operator in the class circle which accepts the object of type rectan$le. Since there is no such overloaded assi$nment operator the conversion operator function that converts the rectan$le object to the circle object is searched in the rectan$le class. 0e have provided such a conversion function in the rectan$le class. This conversion operator function returns a circle object. Gy default conversion operators have the name and return type same as the object type to which it converts to. /ere the type of the object is circle and hence the name of the operator function as well as the return type is circle. 1+. /ow do 3 write code that allows to create only one instance of a class? Ans: This is shown in followin$ code snippet. &include class sample ' static sample >ptr ( private: sample) , ' public: static sample> create) , ' if ) ptr ** N:HH , ptr * new sample ( return ptr ( -( sample >sample::ptr * N:HH (

void main) , ' sample >a * sample::create) , ( sample >b * sample::create) , ( /ere the class sample contains a static data member ptr which is a pointer to the object of same class. The constructor is private which avoids us from creatin$ objects outside the class. A static member function called create) , is used to create an object of the class. 3n this function the condition is chec6ed whether or not ptr is N:HH if it is then an object is created dynamically and its address collected in ptr is returned. 3f ptr is not N:HH then the same address is returned. Thus in main) , on e9ecution of the first statement one object of sample $ets created whereas on e9ecution of second statement b holds the address of the first object. Thus whatever number of times you call create) , function only one object of sample class will be available. 11. /ow do 3 write code to add functions which would wor6 as $et and put properties of a class? Ans: This is shown in followin$ code. &include class sample ' int data ( public: 88declspec ) property ) put * fun1 $et * fun! , , int 9 ( void fun1 ) int i , ' if ) i = + , data * + ( else data * i ( int fun!) , ' return data ( -( void main) , ' sample a ( a.9 * "FF ( cout == a.9 ( /ere the function fun1) , of class sample is used to set the $iven inte$er value into data whereas fun!) , returns the current value of data. To set these functions as properties of a class we have $iven the statement as shown below: 88declspec ) property ) put * fun1 $et * fun! ,, int 9 ( As a result the statement a.9 * "FF ( would cause fun1) , to $et called to set the value in data. Bn the other hand the last statement would cause fun!) , to $et called to return the value of data.

1!. /ow do 3 write code to ma6e an object wor6 li6e a !"I array? Ans: Ta6e a loo6 at the followin$ pro$ram. &include class emp ' public : int aJ1KJ1K ( emp) , ' int c * 1 ( for ) int i * + ( i =* ! ( iEE , ' for ) int j * + ( j =* ! ( jEE , ' aJiKJjK * c ( cEE ( int> operatorJK ) int i , ' return aJiK ( -( void main) , ' emp e ( cout == eJ+KJ1K ( The class emp has an overloaded operator J K function. 3t ta6es one ar$ument an inte$er representin$ an array inde9 and returns an int pointer. The statement cout == eJ+KJ1K ( would $et converted into a call to the overloaded J K function as e.operatorJ K ) + ,. + would $et collected in i. The function would return aJiK that represents the base address of the %eroeth row. Ne9t the statement would $et e9panded as base address of %eroeth rowJ1K that can be further e9panded as >) base address E 1 ,. This $ives us a value in %eroth row and first column. 11. 0hat are formattin$ fla$s in ios class? Ans: The ios class contains formattin$ fla$s that help users to format the stream data. 4ormattin$ fla$s are a set of enum definitions. There are two types of formattin$ fla$s: Bn2Bff fla$s 4la$s that wor6 in"$roup The Bn2Bff fla$s are turned on usin$ the setf) , function and are turned off usin$ the unsetf) , function. To set the Bn2Bff fla$s the one ar$ument setf) , function is used. The fla$s wor6in$ in $roups are set throu$h the two"ar$ument setf) , function. 4or e9ample to left justify a strin$ we can set the fla$ as cout.setf ) ios::left , ( cout == ?L3C3T Na$pur? ( To remove the left justification for subse5uent output we can say cout.unsetf ) ios::left , ( The fla$s that can be set2unset include s6ipws showbase showpoint

uppercase showpos unitbuf and stdio. The fla$s that wor6 in a $roup can have only one of these fla$s set at a time. 17. 0hat is the purpose of ios::basefield in the followin$ statement? cout.setf ) ios::he9 ios::basefield , ( Ans: This is an e9ample of formattin$ fla$s that wor6 in a $roup. There is a fla$ for each numberin$ system )base, li6e decimal octal and he9adecimal. Collectively these fla$s are referred to as basefield and are specified by ios::basefield fla$. 0e can have only one of these fla$s on at a time. 3f we set the he9 fla$ as setf ) ios::he9 , then we will set the he9 bit but we won@t clear the dec bit resultin$ in undefined behavior. The solution is to call setf) , as setf ) ios::he9 ios::basefield ,. This call first clears all the bits and then sets the he9 bit. 1;. Can we $et the value of ios format fla$s? Ans: #esD The ios::fla$s) , member function $ives the value format fla$s. This function ta6es no ar$uments and returns a lon$ ) typedefed to fmtfla$s, that contains the current format fla$s. 1.. 3s there any function that can s6ip certain number of characters present in the input stream? Ans: #esD This can be done usin$ cin::i$nore) , function. The prototype of this function is as shown below: istream< i$nore ) int n * 1 int d *MB4 , ( Sometimes it happens that some e9tra characters are left in the input stream while ta6in$ the input such as the ?Nn? )Mnter, character. This e9tra character is then passed to the ne9t input and may pose problem. To $et rid of such e9tra characters the cin::i$nore) , function is used. This is e5uivalent to fflush ) stdin , used in C lan$ua$e. This function i$nores the first n characters )if present, in the input stream stops if delimiter d is encountered. 1A. 0rite a pro$ram that implements a date class containin$ day month and year as data members. 3mplement assi$nment operator and copy constructor in this class. Ans: This is shown in followin$ pro$ram: &include class date ' private : int day ( int month ( int year ( public : date ) int d * + int m * + int y * + , ' day * d ( month * m ( year * y ( 22 copy constructor date ) date <d , ' day * d.day (

month * d.month ( year * d.year ( 22 an overloaded assi$nment operator date operator * ) date d , ' day * d.day ( month * d.month ( year * d.year ( return d ( void display) , ' cout == day == ?2? == month == ?2? == year ( -( void main) , ' date d1 ) !; F 1FAF , ( date d! * d1 ( date d1 ( d1 * d! ( d1.display) , ( 1C. 0hen should 3 use unitbuf fla$? Ans: The unit bufferin$ )unitbuf, fla$ should be turned on when we want to ensure that each character is output as soon as it is inserted into an output stream. The same can be done usin$ unbuffered output but unit bufferin$ provides a better performance than the unbuffered output. 1F.0hat are manipulators? Ans: Oanipulators are the instructions to the output stream to modify the output in various ways. The manipulators provide a clean and easy way for formatted output in comparison to the formattin$ fla$s of the ios class. 0hen manipulators are used the formattin$ instructions are inserted directly into the stream. Oanipulators are of two types those that ta6e an ar$ument and those that don?t. !+. 0hat is the difference between the manipulator and setf) , function? Ans: The difference between the manipulator and setf) , function are as follows: The setf) , function is used to set the fla$s of the ios but manipulators directly insert the formattin$ instructions into the stream. 0e can create user"defined manipulators but setf) , function uses data members of ios class only. The fla$s put on throu$h the setf) , function can be put off throu$h unsetf) , function. Such fle9ibility is not available with manipulators. !1. /ow do 3 $et the current position of the file pointer? Ans: 0e can $et the current position of the file pointer by usin$ the tellp) , member function of ostream class or tell$) , member function of istream class. These functions return )in bytes, positions of put pointer and $et pointer respectively.

!!. 0hat are put and $et pointers? Ans: These are the lon$ inte$ers associated with the streams. The value present in the put pointer specifies the byte number in the file from where ne9t write would ta6e place in the file. The $et pointer specifies the byte number in the file from where the ne9t readin$ should ta6e place. !1. 0hat do the nocreate and noreplace fla$ ensure when they are used for openin$ a file? Ans: nocreate and noreplace are file"openin$ modes. A bit in the ios class defines these modes. The fla$ nocreate ensures that the file must e9ist before openin$ it. Bn the other hand the fla$ noreplace ensures that while openin$ a file for output it does not $et overwritten with new one unless ate or app is set. 0hen the app fla$ is set then whatever we write $ets appended to the e9istin$ file. 0hen ate fla$ is set we can start readin$ or writin$ at the end of e9istin$ file. !7. 0hat is the limitation of cin while ta6in$ input for character array? Ans: To understand this consider followin$ statements char strJ;K ( cin PP str ( 0hile enterin$ the value for str if we enter more than ; characters then there is no provision in cin to chec6 the array bounds. 3f the array overflows it may be dan$erous. This can be avoided by usin$ $et) , function. 4or e9ample consider followin$ statement cin.$et ) str ; , ( Bn e9ecutin$ this statement if we enter more than ; characters then $et) , ta6es only first five characters and i$nores rest of the characters. Some more variations of $et) , are available such as shown below: $et ) ch , ? M9tracts one character only $et ) str n , ? M9tracts up to n characters into str $et ) str IMH3O , ? M9tracts characters into array str until specified delimiter )such as @Nn@,. Heaves delimitin$ character in stream. $et ) str n IMH3O , ? M9tracts characters into array str until n characters or IMH3O character leavin$ delimitin$ character in stream. !;. 0hat is the purpose of istream class? Ans: The istream class performs activities specific to input. 3t is derived from the ios class. The most commonly used member function of this class is the overloaded PP operator which can e9tract values of all basic types. 0e can e9tract even a strin$ usin$ this operator. !.. 0ould the followin$ code wor6? &include void main) , ' ostream o ( o == ?Iream. Then ma6e it happenD? ( Ans: NoD This is because we cannot create an object of the ostream class since its constructor and copy constructor are declared private. !A. Can we use this pointer inside static member function? Ans: NoD The this pointer cannot be used inside a static member function. This is because a static member function is never called throu$h an object.

!C. 0hat is strstream? Ans: strstream is a type of input2output stream that wor6s with the memory. 3t allows usin$ section of the memory as a stream object. These streams provide the classes that can be used for storin$ the stream of bytes into memory. 4or e9ample we can store inte$ers floats and strin$s as a stream of bytes. There are several classes that implement this in"memory formattin$. The class ostrstream derived from ostream is used when output is to be sent to memory the class istrstream derived from istream is used when input is ta6en from memory and strstream class derived from iostream is used for memory objects that do both input and output. Ans: 0hen we want to retrieve the streams of bytes from memory we can use istrestream. The followin$ e9ample shows the use of istrstream class. &include void main) , ' int a$e ( float salary ( char nameJ;+K ( char strJK * ?!! 1!++7.;+ L. Qishwanatth? ( istrstream s ) str , ( s PP a$e PP salary PP name ( cout == a$e == endl == salary == endl == name ( cout == endl == s.rdbuf) , ( /ere s is the object of the class istrstream. 0hen we are creatin$ the object s the constructor of istrstream $ets called that receives a pointer to the %ero terminated character array str. The statement s PP a$e PP salary PP name ( e9tracts the a$e salary and the name from the istrstream object s. /owever while e9tractin$ the name only the first word of name $ets e9tracted. The balance is e9tracted usin$ rdbuf) ,. !F. 0hen the constructor of a base class calls a virtual function why doesn@t the override function of the derived class $ets called? Ans: 0hile buildin$ an object of a derived class first the constructor of the base class and then the constructor of the derived class $ets called. The object is said an immature object at the sta$e when the constructor of base class is called. This object will be called a matured object after the e9ecution of the constructor of the derived class. Thus if we call a virtual function when an object is still immature obviously the virtual function of the base class would $et called. This is illustrated in the followin$ e9ample. &include class base ' protected : int i ( public : base ) int ii * + , ' i * ii ( show) , ( virtual void show) , ' cout == ?base@s show) ,? == endl (

-( class derived : public base ' private : int j ( public : derived ) int ii int jj * + , : base ) ii , ' j * jj ( show) , ( void show) , ' cout == ?derived@s show) ,? == endl ( -( void main) , ' derived dobj ) !+ ; , ( The output of this pro$ram would be: base@s show) , derived@s show) , 1+. Can 3 have a reference as a data member of a class? 3f yes then how do 3 initialise it? Ans: #es we can have a reference as a data member of a class. A reference as a data member of a class is initiali%ed in the initiali%ation list of the constructor. This is shown in followin$ pro$ram. &include class sample ' private : int< i ( public : sample ) int< ii , : i ) ii , ' void show) , ' cout == i == endl ( -( void main) , ' int j * 1+ ( sample s ) j , ( s.show) , ( -

/ere i refers to a variable j allocated on the stac6. A point to note here is that we cannot bind a reference to an object passed to the constructor as a value. 3f we do so then the reference i would refer to the function parameter )i.e. parameter ii in the constructor, which would disappear as soon as the function returns thereby creatin$ a situation of dan$lin$ reference. 11. 0hy does the followin$ code fail? &include class sample ' private : char >str ( public : sample ) char >s , ' strcpy ) str s , ( Rsample) , ' delete str ( -( void main) , ' sample s1 ) ?abc? , ( Ans: /ere throu$h the destructor we are tryin$ to deal locate memory which has been allocated statically. To remove an e9ception add followin$ statement to the constructor. sample ) char >s , ' str * new charJstrlen)s, E 1K ( strcpy ) str s , ( /ere first we have allocated memory of re5uired si%e which then would $et deal located throu$h the destructor. 1!. assert) , macro... 0e can use a macro called assert) , to test for conditions that should not occur in a code. This macro e9pands to an if statement. 3f test evaluates to + assert prints an error messa$e and calls abort to abort the pro$ram. &include &include void main) , ' int i ( cout == ?NnMnter an inte$er: ? ( cin PP i ( assert ) i P* + , ( cout == i == endl ( -

11. 0hy it is unsafe to deal locate the memory usin$ free) , if it has been allocated usin$ new? Ans: This can be e9plained with the followin$ e9ample: &include class sample ' int >p ( public : sample) , ' p * new int ( Rsample) , ' delete p ( -( void main) , ' sample >s1 * new sample ( free ) s1 , ( sample >s! * ) sample > , malloc ) si%eof ) sample , , ( delete s! ( The new operator allocates memory and calls the constructor. 3n the constructor we have allocated memory on heap which is pointed to by p. 3f we release the object usin$ the free) , function the object would die but the memory allocated in the constructor would lea6. This is because free) , bein$ a C library function does not call the destructor where we have deal located the memory. As a$ainst this if we allocate memory by callin$ malloc) , the constructor would not $et called. /ence p holds a $arba$e address. Now if the memory is deal located usin$ delete the destructor would $et called where we have tried to release the memory pointed to by p. Since p contains $arba$e this may result in a runtime error. 17. Can we distribute function templates and class templates in object libraries? Ans: NoD 0e can compile a function template or a class template into object code ).obj file,. The code that contains a call to the function template or the code that creates an object from a class template can $et compiled. This is because the compiler merely chec6s whether the call matches the declaration )in case of function template, and whether the object definition matches class declaration )in case of class template,. Since the function template and the class template definitions are not found the compiler leaves it to the lin6er to restore this. /owever durin$ lin6in$ lin6er doesn@t find the matchin$ definitions for the function call or a matchin$ definition for object creation. 3n short the e9panded versions of templates are not found in the object library. /ence the lin6er reports error. 1;. 0hat is the difference between an inspector and a mutator ? Ans: An inspector is a member function that returns information about an object@s state )information stored in object@s data members, without chan$in$ the object@s state. A mutator is a member function that chan$es the state of an object. 3n the class Stac6 $iven below we have defined a mutator and an

inspector. class Stac6 ' public : int pop) , ( int $etcount) , ( 3n the above e9ample the function pop) , removes top element of stac6 thereby chan$in$ the state of an object. So the function pop) , is a mutator. The function $etcount) , is an inspector because it simply counts the number of elements in the stac6 without chan$in$ the stac6. 1.. Namespaces: The CEE lan$ua$e provides a sin$le $lobal namespace. This can cause problems with $lobal name clashes. 4or instance consider these two CEE header files: 22 file1.h float f ) float int , ( class sample ' ... - ( 22 file!.h class sample ' ... - ( 0ith these definitions it is impossible to use both header files in a sin$le pro$ram( the sample classes will clash. A namespace is a declarative re$ion that attaches an additional identifier to any names declared inside it. The additional identifier thus avoids the possibility that a name will conflict with names declared elsewhere in the pro$ram. 3t is possible to use the same name in separate namespaces without conflict even if the names appear in the same translation unit. As lon$ as they appear in separate namespaces each name will be uni5ue because of the addition of the namespace identifier. 4or e9ample: 22 file1.h namespace file1 ' float f ) float int , ( class sample ' ... - ( 22 file!.h namespace file! ' class sample ' ... - ( Now the class names will not clash because they become file1::sample and file!::sample respectively. 1A. 0hat would be the output of the followin$ pro$ram? &include class user ' int i ( float f ( char c ( public : void displaydata) ,

' cout == endl == i == endl == f == endl == c ( -( void main) , ' cout == si%eof ) user , ( user u1 ( cout == endl == si%eof ) u1 , ( u1.displaydata) , ( Ans: The output of this pro$ram would be F or A F or A Sarba$e Sarba$e Sarba$e Since the user class contains three elements int float and char its si%e would be F bytes )int"7 float"7 char"1, under 0indows and A bytes )int"! float"7 char"1, under IBS. Second output is a$ain the same because u1 is an object of the class user. 4inally three $arba$e values are printed out because i f and c are not initiali%ed anywhere in the pro$ram. Note that if you run this pro$ram you may not $et the answer shown here. This is because pac6in$ is done for an object in memory to increase the access efficiency. 4or e9ample under IBS the object would be ali$ned on a !"byte boundary. As a result the si%e of the object would be reported as . bytes. :nli6e this 0indows bein$ a 1!"bit BS the object would be ali$ned on a 7"byte boundary. /ence the si%e of the object would be reported as 1! bytes. To force the ali$nment on a 1"byte boundary write the followin$ statement before the class declaration. &pra$ma pac6 ) 1 , 1C. 0rite a pro$ram that will convert an inte$er pointer to an inte$er and vice"versa. Ans: The followin$ pro$ram demonstrates this. &include void main) , ' int i * .;+++ ( int >iptr * reinterpret8cast ) i , ( cout == endl == iptr ( iptrEE ( cout == endl == iptr ( i * reinterpret8cast ) iptr , ( cout == endl == i ( iEE ( cout == endl == i ( 1F. 0hat is a const8cast? Ans. The const8cast is used to convert a const to a non"const. This is shown in the followin$ pro$ram:

&include void main) , ' const int a * + ( int >ptr * ) int > , <a ( 22one way ptr * const8cast8 ) <a , ( 22better way /ere the address of the const variable a is assi$ned to the pointer to a non"const variable. The const8cast is also used when we want to chan$e the data members of a class inside the const member functions. The followin$ code snippet shows this: class sample ' private: int data( public: void func) , const ' )const8cast )this,,"Pdata * A+ ( -( 7+. 0hat is forward referencin$ and when should it be used? Ans: 4orward referencin$ is $enerally re5uired when we ma6e a class or a function as a friend. Consider followin$ pro$ram: class test ' public: friend void fun ) sample test , ( -( class sample ' public: friend void fun ) sample test , ( -( void fun ) sample s test t , ' 22 code void main) , ' sample s ( test t ( fun ) s t , ( Bn compilin$ this pro$ram it $ives error on the followin$ statement of test class. 3t $ives an error that sample is undeclared identifier. friend void fun ) sample test ,( This is so because the class sample is defined below the class test and we are usin$ it before its definition. To overcome this error we need to $ive forward reference of the class sample before the definition of class test. The followin$ statement is the forward reference of class sample.

class sample ( 71. /ow would you $ive an alternate name to a namespace? Ans: An alternate name $iven to namespace is called a namespace"alias. namespace"alias is $enerally used to save the typin$ effort when the names of namespaces are very lon$ or comple9. The followin$ synta9 is used to $ive an alias to a namespace. namespace myname * my8old8very8lon$8name ( 7!. :sin$ a smart pointer can we iterate throu$h a container? Ans: #es. A container is a collection of elements or objects. 3t helps to properly or$ani%e and store the data. Stac6s lin6ed lists arrays are e9amples of containers. 4ollowin$ pro$ram shows how to iterate throu$h a container usin$ a smart pointer. &include class smartpointer ' private : int >p ( 22 ordinary pointer public : smartpointer ) int n , ' p * new int J n K ( int >t * p ( for ) int i * + ( i =* F ( iEE , >tEE * i > i ( int> operator EE ) int , ' return pEE ( int operator > ) , ' return >p ( -( void main) , ' smartpointer sp ) 1+ , ( for ) int i * + ( i =* F ( iEE , cout == >spEE == endl ( /ere sp is a smart pointer. 0hen we say >sp the operator > ) , function $ets called. 3t returns the inte$er bein$ pointed to by p. 0hen we say spEE the operator EE ) , function $ets called. 3t increments p to point to The ne9t element in the array and then returns the address of this new location. 71. Can objects read and write themselves? Ans: #esD This can be e9plained with the help of followin$ e9ample: &include &include class employee

' private : char name J !+ K ( int a$e ( float salary ( public : void $etdata) , ' cout == ?Mnter name a$e and salary of employee : ? ( cin PP name PP a$e PP salary ( void store) , ' ofstream file ( file.open ) ?MOTHB#MM.IAT? ios::app U ios::binary , ( file.write ) ) char > , this si%eof ) >this , , ( file.close) , ( void retrieve ) int n , ' ifstream file ( file.open ) ?MOTHB#MM.IAT? ios::binary , ( file.see6$ ) n > si%eof ) employee , , ( file.read ) ) char > , this si%eof ) >this , , ( file.close) , ( void show) , ' cout == ?Name : ? == name == endl == ?A$e : ? == a$e == endl == ?Salary :? == salary == endl ( -( void main) , ' employee e J ; K ( for ) int i * + ( i =* 7 ( iEE , ' e J i K.$etdata) , ( e J i K.store) , ( for ) i * + ( i =* 7 ( iEE , ' e J i K.retrieve ) i , ( e J i K.show) , ( /ere employee is the class whose objects can write and read themselves. The $etdata) , function has been used to $et the data of employee and store it in the data members name a$e and salary. The store)

, function is used to write an object to the file. 3n this function a file has been opened in append mode and each time data of current object has been stored after the last record )if any, in the file. 4unction retrieve) , is used to $et the data of a particular employee from the file. This retrieved data has been stored in the data members name a$e and salary. /ere this has been used to store data since it contains the address of the current object. The function show) , has been used to display the data of employee. 77. 0hy is it necessary to use a reference in the ar$ument to the copy constructor? Ans : 3f we pass the copy constructor the ar$ument by value its copy would $et constructed usin$ the copy constructor. This means the copy constructor would call itself to ma6e this copy. This process would $o on and on until the compiler runs out of memory. This can be e9plained with the help of followin$ e9ample: class sample ' int i ( public : sample ) sample p , ' i * p.i ( -( void main) , ' sample s ( sample s1 ) s , ( 0hile e9ecutin$ the statement sample s1 ) s , the copy constructor would $et called. As the copy construct here accepts a value the value of s would be passed which would $et collected in p. 0e can thin6 of this statement as sample p * s. /ere p is $ettin$ created and initiali%ed. Oeans a$ain the copy constructor would $et called. This would result into recursive calls. /ence we must use a reference as an ar$ument in a copy constructor. 7;.

7.. Qirtual Oultiple 3nheritance: A class b is defined havin$ member variable i. Suppose two classes d1 and d! are derived from class b and a class multiple is derived from both d1 and d!. 3f variable i is accessed from a member function of multiple then it $ives error as @member is ambi$uous@. To avoid this error derive classes d1 and d! with modifier virtual as shown in the followin$ pro$ram. &include class b ' public : int i ( public : fun) , ' i*+(

-( class d1 : virtual public b ' public : fun) , ' i*1( -( class d! : virtual public b ' public : fun) , ' i*!( -( class multiple : public d1 public d! ' public : fun) , ' i * 1+ ( -( void main) , ' multiple d ( d.fun) , ( cout == d.i ( 7.. Can we use this pointer in a class specific operator"overloadin$ function for new operator? Ans: NoD The this pointer is never passed to the overloaded operator new), member function because this function $ets called before the object is created. /ence there is no 5uestion of the this pointer $ettin$ passed to operator new) ,. 7A. Can we allocate memory dynamically for a reference? Ans: NoD 3t is not possible to allocate memory dynamically for a reference. This is because when we create a reference it $ets tied with some variable of its type. Now if we try to allocate memory dynamically for a reference it is not possible to mention that to which variable the reference would $et tied. 7C. 0hen should 3 overload new operator on a $lobal basis or a class basis? Ans: 0e overload operator new in our pro$ram when we want to initiali%e a data item or a class object at the same place where it has been allocated memory. The followin$ e9ample shows how to overload new operator on $lobal basis. &include

&include void > operator new ) si%e8t s , ' void >5 * malloc ) s , ( return 5 ( void main) , ' int >p * new int ( >p * !; ( cout == >p ( 0hen the operator new is overloaded on $lobal basis it becomes impossible to initiali%e the data members of a class as different classes may have different types of data members. The followin$ e9ample shows how to overload new operator on class"by"class basis. &include &include class sample ' int i ( public : void> operator new ) si%e8t s int ii , ' sample >5 * ) sample > , malloc ) s , ( 5 "P i * ii ( return 5 ( -( class sample1 ' float f ( public : void> operator new ) si%e8t s float ff , ' sample1 >5 * ) sample1 > , malloc ) s , ( 5 "P f * ff ( return 5 ( -( void main) , ' sample >s * new ) A , sample ( sample1 >s1 * new ) ;..f , sample1 ( Bverloadin$ the operator new on class"by"class basis ma6es it possible to allocate memory for an object and initiali%e its data members at the same place. 7F. /ow would you define a pointer to a data member of the type pointer to pointer? Ans: The followin$ pro$ram demonstrates this...

&include class sample ' public : sample ) int >>pp , ' p * pp ( int >>p ( -( int >>sample::>ptr * <sample::p ( void main) , ' int i * F ( int >pi * <i ( sample s ) <pi , ( cout == >> ) s.>ptr , ( /ere ptr is the pointer to data member p of class sample which in turn is a pointer pointin$ to an int. ;+. /ow do 3 write a code to catch multiple types of e9ceptions in one sin$le catch bloc6? Ans: The followin$ pro$ram demonstrates the use of a sin$le catch bloc6 to catch multiple e9ceptions. &include class test ' -( class sample ' public : void fun1) , ' throw FF ( void fun!) , ' throw 1.17f ( void fun1) , ' throw ?error? ( void fun7) , ' throw test) , ( -( void main) , ' try

' sample s ( s.fun7) , ( s.fun1) , ( s.fun!) , ( s.fun1) , ( catch ) ... , ' cout == ?stran$e? ( /ere different types of e9ceptions are thrown by the member functions of the class sample. 0hile catchin$ the e9ception instead of four different catch bloc6s we can as well define one sin$le catch bloc6. Note the synta9 for definin$ the catch bloc6 where we have used three dots )?, in the formal parameter list. This indicates that any thrown e9ception should $et cau$ht in the same catch bloc6. 0hen the e9ception is thrown from the fun7) , control reaches the catch bloc6 i$norin$ the rest of the calls. ;1. Can we return an error value from the constructor of a class? Ans: No. 0e cannot return any error value from the constructor as the constructor doesn@t have any return type. /owever by throwin$ an e9ception we can pass value to catch bloc6. This is shown in the followin$ e9ample: &include class sample ' public : sample ) int i , ' if ) i ** + , throw ?error? ( -( void main) , ' try ' sample s ) + , ( catch ) char > str , ' cout == str ( 3n this pro$ram the statement throw ?error? ( would throw an e9ception when an object s of the class sample would $et created. The catch bloc6 would collect the strin$ error. ;!. /ow do 3 define the member function of a template class which has to be defined outside the template class. The function receives an object of its own class as a parameter and returns the value of

the same type. Ans: The followin$ e9ample shows how we can define such a function. sample sample::fun ) sample s , ' 22 code /ere the first sample indicates the return type of the function and the ne9t sample is used for the scope of function. ;1. /ow name man$lin$ can be prevented? Ans: To avoid name man$lin$ the function should be declared with an e9tern ?C? attribute. 4unctions declared as e9tern ?C? are treated as C"style functions. /ence the compiler does not man$le them. The followin$ code snippet shows how to declare such a function. &include e9tern ?C? void display) , ' cout == ?See the effect of C in CEE ? ( void main) , ' display) , ( ;7. Can we allocate memory dynamically for a reference? Ans: No it is not possible to allocate memory dynamically for a reference. A reference is initiali%ed at the time of creation. Tryin$ to allocate memory dynamically for a reference creates a problem in initiali%in$ it. Thus the compiler does not allow us to dynamically allocate the memory for references. ;;. 0hat is VTT3? Ans: VTT3 stands for @Vun Time Type 3nformation@. 0e use virtual function mechanism where we can call derived class@s member functions usin$ base class@s pointer. /owever many times we wish to 6now the e9act type of the object. 0e can 6now the type of the object usin$ VTT3. A function that returns the type of the object is 6nown as VTT3 functions. CEE supports two ways to obtain information about the object@s class at run time they are typeid) , operator and dynamic8cast operator. ;.. 0hat is Iata Conversion? Ans: Assi$nments between types whether they are basic or user"defined are handled by the compiler. 3f the variables are of different basic types compiler calls a special routine to convert the value. Gut if we want to convert between user"defined data type and basic types we have to write conversion routine ourselves. A conversion routine to convert user"defined data type strin$ to inte$er is shown below: class strin$ ' private : char strJ!+K ( public : strin$) , ' strin$ ) char >s ,

' strcpy ) str s , ( operator int) , ' return 1!1 ( 22 0rite lo$ic to convert strin$ to inte$er -( main) , ' strin$ s! * ?1!1? ( int i1 * int ) s! , ( cout == endl == i1 ( ;A. /ow to obtain type information usin$ typeid) , operator? Ans: typeid) , operator ta6es an object a reference or a pointer and returns its type. 4ollowin$ pro$ram shows how to use the typeid) , operator. &include &include class Gase ' public : virtual void show) , ' -( class Ier1 : public Gase ' -( void main) , ' Gase >b1 ( cout == endl == typeid ) b1 ,.name) , ( Ier1 d1 ( b1 * <d1 ( cout == endl == typeid ) >b1 ,.name) , ( cout == endl == typeid ) 1! ,.name) , == endl == typeid ) 1!.; ,.name) , ( The output of this pro$ram will be Gase> Ier1 int double VTT3 operators must be used for polymorphic class )class havin$ virtual function, only. 4or non" polymorphic class static type information is returned. ;C. /ow to use VTT3 with class templates?

Ans: Templates can $enerate different classes. 0e may wish to $et the type of class which we are wor6in$ in. The followin$ pro$ram shows how to use VTT3 operator typeid) , with class template. &include &include template class base ' public : base) , ' cout == typeid ) >this ,.name) , == ?Constructor? == endl ( T add ) T a T b , ' return a E b ( Rbase) , ' cout == typeid ) >this ,.name) , == ?Iestructor? == endl ( -( void main) , ' base b1 ( cout == b1.add ) 1+ !+ , == endl ( base b! ( cout == b!.add ) ;.; 1+.; , == endl ( ;F. 0e can use followin$ CEE operators for typecastin$. static8cast is used for castless conversions narrowin$ conversions conversion from void> and implicit type conversions. const8cast is used to convert a const to a non"const. reinterpret8cast is used to assi$n one 6ind of pointer to another. .+. 0hat will be the output of the followin$ pro$ram? &include class A ' public : A) , ' cout == ?Veached in ConstructorNn? ( -( void main) , ' A a) , ( Ab( Butput : Veached in Constructor

Constructor $ets called only once when the object b is created. 0hen the statement A a) , ( $ets e9ecuted constructor does not $et called. This is because compiler ta6es this statement as a prototype declaration of function a) , that returns an object of class A. /owever if we pass ar$uments li6e A a ) 1+ , ( Compiler would search for one ar$ument constructor and if not found would flash an error. .1. 0hat is a container? Ans: A container is an object that holds other objects. Qarious collection classes li6e Hist /ash Table AbstractArray etc. are the e9amples of containers. 0e can use the classes to hold objects of any derived classes. The containers provide various methods usin$ which we can $et the number of objects stored in the container and iterate throu$h the objects stored in it. .!. 4unction template overloadin$ Bne can declare several function templates with the same name and even declare a combination of function templates and ordinary functions with the same name. 0hen an overloaded function is called overload resolution is necessary to find the ri$ht function or template function to invo6e. 4or e9ample: template = class T P T s5rt ) T , ( template = class T P comple9 = T P s5rt ) comple9 = T P , (double s5rt ) double , ( void f ) comple9 = double P % , ' s5rt ) ! , ( 22 s5rt = int P ) int , s5rt ) !.+ , ( 22 s5rt ) double , s5rt ) % , ( 22 s5rt = comple9 = double P ) comple9 = double P , 3n the same way that a template function is a $enerali%ation of the notion of a function the rules for resolution in the presence of function templates are $enerali%ations of the function overload resolution rules. Gasically for each template we find the speciali%ation that is best for the set of function ar$uments. Then we apply the usual function overload resolution rules to these speciali%ations and all ordinary functions. .1. M9ception /andlin$ in CEE 3n CEE we can handle run"time errors $enerated by cEE classes by usin$ three new 6eywords: throw catch and try. 0e also have to create an e9ception class. 3f durin$ the course of e9ecution of a member function of this class a run"time error occurs then this member function informs the application that an error has occurred. This process of informin$ is called @throwin$@ an e9ception. The followin$ code shows how to deal with e9ception handlin$. class sample ' public : class errorclass ' -( void fun) , ' if ) some error occurs , throw errorclass) , 22 throws e9ception -

-( 22application void main) , ' try ' sample s ( s.fun) , ( catch ) sample::errorclass , ' 22 do somethin$ about the error .7. Consider the followin$ code: &include class base ' public : int data ( -( class d1 : public base ' -( class d! : public base ' -( class der : public d1 public d! ' public : void showdata) , ' cout == data ( -( void main) , ' der d ( d.showdata) , ( 3f you run this pro$ram it is bound to $ive you errors. This is because of the rules of inheritance: 1. Mach base class not specified virtual will have its own sub"object representin$ it. 3n the above pro$ram if we create object of d1 it will have a sub"object of class base containin$ a data member data. 3f we create an object of class der it will have sub"objects of classes d1 and d! and both the sub"objects will refer to a separate copy of data. /ence to access data from class der we will have to mention the class name. 4or e9ample d1::data or d!::data. !. 3f we want that only one sub"object should e9ist we must use the concept of virtual base class. The sin$le object of this will represent every base class of $iven name that is specified to be virtual class.

After ma6in$ d1 and d! as virtual base class if we create an object of der only one sub"object would e9ist and so accessin$ data would no lon$er $ive us errors. .;. /ow to declare a pointer to a member function? Ans: Suppose 3 wish to declare a pointer to a member function that receives an int and returns an int. 3 will have to declare it as int )A::> , ) int ,. 4ollowin$ is an e9ample. &include class A ' public : int fun ) int f , ' cout == ?in funNn? ( return f > f ( -( typedef int ) A:: >pfun , ) int , ( void main) , ' pfun p * A::fun ( Aa( int s * ) a.>p , ) . , ( cout == s ( ... 0hat is the disadvanta$e of a template function? Ans: A template function cannot be distributed in the obj form. This is because with which parameters the template function is $oin$ to be called is decided at the run time only. Therefore an obj form of a template function cannot be made by merely compilin$ it. .A. /ow to declare a pointer to the data members of a class? Ans: 4ollowin$ pro$ram shows how to declare a pointer to non"function members of a class. &include class A ' public : int a ( void print) , ' cout == a ( -( void main) , ' int A::>pa * <A::a ( A obj ( obj.>pa * !+ ( obj.print) , ( -

/ere we have initialised the data member a usin$ the pointer pa. .C. /ow to allocate memory for a multidimensional array dynamically? Ans: Oany times we need to allocate memory for a multidimensional array dynamically. Gecause of comple9ity of pointers many find this difficult. 4ollowin$ pro$ram allocates memory for a 1 9 1 array dynamically copies contents of a 1 9 1 array in it and prints the contents usin$ the pointer. &include &include int aJ KJ1K * ' 1 ! 1 7 ; . A C F -( void main) , ' int >>p ( p * new int >J1K ( for ) int i * + ( i = 1 ( iEE , pJiK * new intJ1K ( for ) i * + ( i = 1 ( iEE , for ) int j * + ( j = 1 ( jEE , pJiKJjK * aJiKJjK ( for ) i * + ( i = 1 ( iEE , ' for ) j * + ( j = 1 ( jEE , cout == pJiKJjK ( cout == ?Nn? ( .F. 0hen should we use the :: ) scope resolution , operator to invo6e the virtual functions? Ans: Senerally :: operator is used to call a virtual function from constructor or destructor. This is because if we call a virtual function from base class constructor or destructor the virtual function of the base class would $et called even if the object bein$ constructed or destroyed would be the object of the derived class. Thus whenever we want to bypass the dynamic bindin$ mechanism we must use the :: operator to call a virtual function. A+. /ow do 3 use operators .> and "P> in a pro$ram? Ans: The followin$ code snippet demonstrates the use of .> and "P> operators. &include class sample ' public : int i ( void fun) , ' cout == ?fun? == endl ( -(

void ) sample::>pf ,) , * <sample::fun ( int sample::>pdm * <sample::i ( void main) , ' sample s ( sample >p * new sample ( ) s .> pf ,) , ( ) p "P> pf ,) , ( s .> pdm * 1 ( p "P> pdm * ! ( cout == s .> pdm == endl ( cout == p "P> pdm == endl ( 3n the above pro$ram pf is a pointer to a function fun) , of class sample and pdm is a pointer to a data member i of the same class sample. The object s of the class sample is created statically. Ne9t p is a pointer to an object created dynamically. The usin$ the operator .> and "P> the member functions are called and also the public data member is accessed. A1. 0hat happens when we add an int value to a user defined type of object? Ans: 0henever an int value is added to an object of user defined type the object would search for an overloaded operator int) ,. This operator must be defined in such a way that it always returns an int value. /owever we need not specify the return type as on doin$ so the compiler flashes an error. &include class sample ' int i ( public : sample ) , ' i * 1+ ( operator int) , ' return this "P i ( -( void main) , ' sample s ( int i ( i * s E 1+ ( cout == i ( 3n the above pro$ram on addin$ 1+ to an object s the value of i would become !+. A!. Can we have a reference to an array? Ans: #es we can have a reference to an array. int aJ K * ' C ! 1! F - ( int ) <r , J 7 K * a ( 22 reference to an array

/ere r is a reference to an array of four elements. 0e can even print the elements of array with the help of reference. This is shown in the followin$ code se$ment: for ) int i * + ( i = 7 ( iEE , cout == r JiK == endl ( A1. 0hen friend function becomes indispensable... Ans: Consider the followin$ pro$ram. &include class distance ' private : int feet ( public : distance) , ' feet * + ( distance ) int f , ' feet * f ( distance operator E ) distance 9 , ' int f * feet E 9.feet ( return distance ) f , ( -( void main) , ' distance d1 ) !+ , d! d1 ( d! * d1 E 1+ ( d1 * 1+ E d! ( 3f you run this pro$ram it is bound to $ive errors. The error lies in the statement d1 * 1+ E d! ( 0e may thin6 that since we have overloaded E operator this statement would add 1+ to d!. Gut this does not happen. This is because the specified statement will $et converted as d1 * 1+.operatorE ) d! , ( This means that this statement should call the operatorE) , function that ta6es an object of distance class as parameter written in the float class which is not possible. The solution is to write operatorE) , as a @friend@ function. Ieclare operatorE function in distance class as $iven below: friend distance operator E ) distance 91 distance 9! , ( and define it outside the class as shown below: distance operator E ) distance 91 distance 9! , ' int f * 91.feet E 9!.feet ( return distance ) f , ( 0hen compiler would see that the @friend@ operatorE) , function is available it would convert the statement d1 * 1+ E d! as operatorE )1+ d! ,. Now since 1+ is passed as a parameter not as a callin$ object there would be no error. Thus in such cases @friend@ function becomes indispensable.

A7. /ow to use a memory as a stream? Ans: Suppose details of an employee such as name desi$nation a$e etc. are stored in different types of variables. Now if we wish to concatenate these details in a character array we will have to use various strin$ manipulation functions li6e strcpy) , and strcat) ,. 3nstead of usin$ these functions we can use more easy and clean way to $ather the details in the char array in the form of streams. 0e can declare the memory allocated for the array as stream and use the == operator to store variables havin$ different types in this memory. 4ollowin$ pro$ram shows how to achieve this. &include void main) , ' char buff J;+K ( char strJ K * ?Sanjay? ( char desi$J K * ?Oana$er? ( char jdJ K * ?!A21!21FF;? ( int a$e * 1; ( ostrstream o ) buff si%eof ) buff , , ( o == str == endl == desi$ == endl == jd == endl == a$e == ends ( cout == buff ( As shown in the pro$ram we can also use the manipulators and formattin$ fla$s. The output of this pro$ram will be: Sanjay Oana$er !A21!21FF; 1; A;. /ow would you declare and initiali%e reference to a data member? Ans: Sometimes we may need to declare a data member which is a reference to another data member of the class as shown below: class A ' public : char >p ( char ><rp ( -( 0e can@t initiali%e a reference to a data member at the time of declaration. 3t should be initiali%ed usin$ @member wise initiali%ation as shown below. &include class A ' public : char >p ( char ><rp ( A) , : rp ) p , ' p * ?? ( A ) char >s , : rp ) p ,

' p*s( -( void main) , ' A a ) ?abcd? , ( cout == a.rp ( A.. iostream library has made it easy to read data from various input devices and write data to the output devices. The followin$ pro$ram shows how to print a dis6 file @data.dat@ on the printer usin$ stream classes. Mvery hardware device has a familiar name $iven by the operatin$ system. The printer is $enerally connected to the first parallel port. So the file name for the printer should be TVN or lpt1. &include void main) , ' ifstream i ) ?data.dat? , ( ofstream o ( o.open ) ?TVN? , ( char ch ( while ) 1 , ' i.$et ) ch , ( if ) i.eof) , , brea6 ( o.put ) ch , ( o.put ) @N9+C@ , ( AA. 0e 6now that a destructor is automatically called when an object of a class $oes out of scope. There is another case where destructor is called automatically. 3f an object is created in a try bloc6 and an e9ception is thrown after the object is created then the destructor is called automatically. AC. Can a function call be at the left hand side of the assi$nment operator? Ans: #es. 4ollowin$ pro$ram shows how it is possible. &include class ref ' private : struct data ' int a ( char >p ( - d1 d! ( public : data <set ) , '

return d1 ( data <$et ) , ' cin PP d!.a PP d!.p ( return d! ( -( void main) , ' ref r ( r.set) , * r.$et) , ( r.print) , ( 3n the above pro$ram the functions $et) , and set) , both return a reference to the object of the structure data. 0e have assi$ned the reference returned by $et) , to the reference returned by set) , function. That is we are assi$nin$ d! to d1. So the values of d! would $et assi$ned to d1. #ou can chec6 this out by printin$ the values of d1. AF. 3f a class contains a virtual function a pointer called QTTV is created. This QTTV becomes a part of every object of that class. The first two bytes )in IBS, are occupied by QTTV. 0e can prove this by displayin$ the first two bytes of memory allocated for the objects. 4ollowin$ pro$ram shows how this can be achieved. &include class vir ' public : virtual void f) , ' -( void main) , ' vir v v1 ( int >p1 * ) int> , <v ( int >p! * ) int> , <v1 ( cout == endl == >p1 == ? ? == >p! ( C+. M9ception /andlin$ in CEE 3n CEE we can handle run"time errors $enerated by cEE classes by usin$ three new 6eywords: throw catch and try. 0e also have to create an e9ception class. 3f durin$ the course of e9ecution of a member function of this class a run"time error occurs then this member function informs the application that an error has occurred. This process of informin$ is called @throwin$@ an e9ception. The followin$ code shows how to deal with e9ception handlin$. class sample ' public : class errorclass

' -( void fun) , ' if ) some error occurs , throw errorclass) , 22 throws e9ception -( 22application void main) , ' try ' sample s ( s.fun) , ( catch ) sample::errorclass , ' 22 do somethin$ about the error C1. Accessin$ a private data member from a different Bbject...Iifferent objects of the same class can access each other@s members even if these members are private. 4or e9ample: &include = iostream.h P class sample ' float f ( public : sample ) float ff , ' f * ff ( void fun ) sample> objptr , ' objptr "P n * + ( cout == ?Qalue of this objects f is : ? == f == endl ( cout == ?Qalue of other objects f? == objptr "P n == endl ( - 22 another object@s private memberD -( void main) , ' sample s1 ) ..;f , s! ) !.;f , ( s1.f ) <s! , ( 22 s1 chan$es s!@s n Typically this codin$ style should be avoided. /owever you should be aware that private members of an object can be chan$ed by another object of the same type. Therefore in certain special conditions this codin$ style may be useful.

C!. Can you access private data members of a class from out side the class? Ans: #es. This pro$ram shows how. &include class emp private : int i ( public : emp) , ' i * 1+ ( -( void main) , emp >p * new emp ( int >pi * )int>, p ( cout == >pi ( >pi * !+ ( cout == >pi ( The pointer to the class is typecasted in an inte$er pointer. 0ith the help of this pointer private data member @i@ is accessed in main) ,. C1. 0hy creatin$ array of references is not possible? Ans: The array name always refers or points to the %eroeth element. 3f array is of references then the array name would point to the %eroeth element which happens to be a reference. Creatin$ pointer to a reference is not valid. So creatin$ array of references too is not possible. C7. /ow do 3 call a virtual function of a class usin$ a pointer to a function ? Ans : &include class Cvirtual ' public : virtual float vfun) , ' cout == ?from vfun? == endl ( return A.+1f ( -( void main) , ' Cvirtual obj ( int >>p * ) int >> , <obj ( float ) >pf1 , ) , ( pf1 * ) float ) > , ) , , >>p ( float f * ) >pf1 , ) , ( cout == ?return val * ? == f == endl ( 3n the above pro$ram class Cvirtual consists of a virtual function vfun),. 3n variable p we have stored

the address of an object of class Cvirtual. 0hile doin$ so we have type casted the address of obj to int >> because obj holds a hidden data member called vptr which in turn holds the address of virtual function vfun) ,. 3n pf1 a pointer to a function we are collectin$ the address of the virtual function vfun) ,. Thus the value returned by vfun) , would then $et collected in f. C;. 0hy an overloaded new operator defined in a class is static? Ans: An overloaded new function is by default static even if it is not declared so. This is because non" static member functions can be called throu$h an object only. Gut when an overloaded new operator function $ets called the object doesn@t stand created. Since new operator function itself is responsible for creatin$ the object. /ence to be able to call a function without an object the function must be static. C.. 0hat is a pure virtual destructor? Ans: Hi6e a pure virtual function we can also have a pure virtual destructor. 3f a base class contains a pure virtual destructor it becomes necessary for the derived classes to implement the destructor. An ordinary pure virtual function does not have a body but pure virtual destructor must have a body. This is because all the destructors in the hierarchy of inheritance are always called as a part of destruction. CA. 0hen we are re5uired to find offset of an element within a structure? or how do we call the function of an outer class from a function in the inner class? )The inner class is nested in the outer class, Ans: &include class outer ' int i ( float f ( public : class inner ' public : infunc) , ' outer >pout ( pout * )outer>, this " ) si%e8t , <) ) ) outer> , + , "P in , ( pout "P outfunc) , ( -( inner in ( outfunc) , ' cout == ?in outer class@s function? ( -( void main) , ' outer out ( out.in.infunc) , 3n the above e9ample we are callin$ outer::outfunc) , from inner::infunc),. To call outfunc) , we need a

pointer to the outer class. To $et the pointer we have subtracted offset of the inner class@s object )base address of outer class@s object " address of inner class@s object, from address of inner class@s object. CC. void f ) float n int i * 1+ , ( void f ) float a , ( void main) , ' f ) 1!.. , ( void f ) float n int i , ' void f ) float n , ' The above pro$ram results in an error )ambi$uous call, since without the default ar$ument the two functions have ar$uments that are matchin$ in number order and type. CF. Some pro$rams need to e9ercise precise control over the memory areas where data is placed. 4or e9ample suppose we wish to read the contents of the boot sector into a structure. 4or this the byte arran$ement of the structure elements must match the arran$ement of various fields in the boot sector of the dis6. The &pra$ma pac6 directives offer a way to fulfill this re5uirement. The &pra$ma pac6 directive specifies pac6in$ ali$nment for structure and union members. The &pra$ma ta6es effect at the first structure or union declaration after the &pra$ma is seen. Consider the followin$ structure: &pra$ma pac6 )1, struct emp ' int a ( float s ( char ch ( -( &pra$ma pac6) , /ere &pra$ma pac6 ) 1 , lets each structure element to be$in on a 1"byte boundary. /ence the si%e of the structure will be F. )int " 7 float " 7 char " 1,. 3f we use &pra$ma pac6 ) ! , each structure element can be$in on a !"byte boundary. /ence the si%e of the structure will be 1+. )int " 7 float " 7 char " !,. F+. /ow to restrict a friend class@s access to the private data members? Ans: 3f we declare a class as a friend of our class the friend class can access the private data members of our class. /owever if we want we can restrict this access to some selective functions of the class. 4ollowin$ pro$ram shows how to achieve this: &include class W ' public : void print ) class X <% , ( -( class X '

private : int i ( public : X ) int ii , ' i * ii ( friend W::print ) class X <% , ( -( void W::print ) X <%1 , ' cout == %1.i ( main) , ' X % ) 1+ , ( W9( 9.print ) 1+ , ( 3n the above pro$ram only the W::print) , function can access the private data members of class X. F1. 0hat is name man$lin$? Ans: CEE enables you to assi$n the same function name to more than one functions but with different parameter types. This feature is called function overloadin$. Gut when we $ive several functions the same name how does the compiler decide which particular function is to be called? CEE solves this problem by applyin$ a process called name man$lin$. Name man$lin$ applies a decorated name to the function. The man$led name includes to6ens that identify the functions@ return type and the types of its ar$uments. class test ' public : void fun ) int a char b , ( void fun ) char >c float y , ( -( void main) , ' test s1 ( s1.fun ) .; @A@ , ( s1.fun ) ?Anil? ;.;f , ( At the time of resolvin$ the calls to fun) , function the lin6er would not be able to find the definition of the overloaded function fun) , and it would report an error. 3f you loo6 at these errors you will see the man$led names li6e )?funYtestYYZAMW[[YX, and )?funYtestYYZAMWOOYX,. Note that different compilers may use different name man$lin$ schemes. F!. /ow would you call a C function from CEE code? Ans: :sin$ e9tern ?C?. The function prototype must be preceded by e9tern ?C?. Oore than one C functions can be $rouped inside braces as shown below:

e9tern ?C? ' void f) , ( void f1) , ( 22 3n cfunc.c &include void f) , ' printf ) ?in f) ,? , ( 22 3n func.cpp &include e9tern ?C? void f) , ( void main) , ' f) , ( Mnsure that both .c and .cpp files are in the same project. F1. /ow to restrict the number of floatin$"point di$its displayed ? Ans: 0hen we display floatin$"point values we can use the setprecision manipulator to specify the desired number of di$its to the ri$ht of the decimal point. 4or e9ample cout == setprecision ) 1 , == 1!.17.AC ( This statement would $ive the output as 1!.17A. F7. 0hat is a wild pointer ? Ans: A wild pointer is the one that points to a $arba$e value. 4or e9ample an uninitiali%ed pointer that contains $arba$e value or a pointer that refers to somethin$ that no lon$er e9ists. F;. /ow friend function helps to increase the versatility of overloaded operators? Ans: Consider the followin$ statement s! * s1 > ! ( where s1 and s! are objects of sample class. This statement would wor6 if the overloaded operator > ) sample s , or conversion function is provided in the class. 3nternally this statement would $et converted to s! * s1.operator > ) ! , ( The function materiali%es because it is called with an object s1. The this pointer of s1 would $et passed implicitly. To collect ! in s first the compiler would call the one"ar$ument constructor then it would build a nameless object which then would $et collected in s. /owever if we write the above statement as s! * ! > s1 ( then it won@t compile. This is because the call now would $et treated as s! * !.operator > ) s1 , ( and ! is not an object. The friend function helps to $et rid of such a situation. This is shown in the followin$ pro$ram. &include class sample

' private : int i ( public : sample ) int ii * + , ' i * ii ( void showdata) , ' cout == i == endl ( friend sample operator > ) sample sample , ( -( sample operator > ) sample s1 sample s! , ' sample temp ( temp.i * s1.i > s!.i ( return ) temp , ( void main) , ' sample s1 ) 1+ , s! ( s! * s1 > ! ( s!.showdata) , ( s1 * ! > s! ( s1.showdata) , ( /ere the operator >) , function ta6es two parameters. This is because the operator function is no lon$er a member function of the class. 3t is a friend of the class sample. Thus the statement s! * s1 > ! ( would not ta6e the form s!.operator > ) ! ,. This e9ample shows that usin$ friend permits the overloaded operators to be more versatile. F.. 0hat is a const8cast? Ans: The const8cast is used to convert a const to a non"const. This is shown in the followin$ pro$ram. &include void main) , ' const int a * + ( int >ptr * ) int > , <a ( 22 one way ptr * const8cast ) <a , ( 22 better way /ere the address of the const variable a is assi$ned to the pointer to a non"const variable. The const8cast is also used when we want to chan$e the data members of a class inside the const member functions. The followin$ code snippet shows how to do this. class sample ' private : int data (

public : void fun) , const ' ) const8cast ) this , , "P data * A+ ( -( FA. :sin$ a smart pointer we can ma6e an object appear li6e a pointer. 3f a class overloads the operator "P then any object of that class can appear li6e a pointer when the operator "P ) , is called. The followin$ pro$ram illustrates this. &include class test ' public : void fun) , ' cout == ?fun of smart pointer? ( -( class smartpointer ' test t ( public : test> operator "P) , ' return <t ( -( void main) , ' smartpointer sp ( sp "P fun) , ( The beauty of overloadin$ operator "P is that even thou$h sp is an object we can ma6e it wor6 li6e a pointer. The operator "P ) , returns the address of the object of the type test. :sin$ this address of the test object the function fun) , of the class test $ets called. Thus even thou$h fun) , is not a member of smartpointer class we can still call it usin$ sp.

You might also like