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 userdefined object be declared as static data member of another class? Ans: "es. The followin# code shows how to initiali$e a userdefined 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 onear#ument constructor. /e can use the same convention to initiali$e the object by callin# multiplear#ument constructor. 0. /hat 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
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
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 wayrelated to objects, they cannot be declared as virtual.
!.
Can userdefined object be declared as static data member of another class?
Ans: "es. The followin# code shows how to initiali$e a userdefined 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 onear#ument constructor. /ecan use the same convention to initiali$e the object by callin# multiplear#ument
constructor.
0.
/hat is forward referencin# and when should it be used?
This pro#ram would not compile. 2t #ives an error that sample is undeclared identifierin 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 ofthe class sample before the definition of class test. The followin#
statement is the forward reference of class sample. 3orward
referencin# is #enerally re4uired when we ma5e a class or a function as a friend.
6.
The istream7withassi#n class has been derived from the istream class and
overloaded assi#nment operator has been added to it. The 7withassi#n classes are much li5e their base classes e8cept that
they include overloaded assi#nment operators. 9sin# these operators the objects of
the 7withassi#n classes can be copied. The istream, ostream,and iostream classes are made uncopyable by ma5in# their
overloaded copy constructor and assi#nment operators private.
.
ow do 2 write my own $eroar#ument manipulator that should wor5 same as he8?
/e all 5now 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?
%includevoid 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 thispro#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 wor5s properly@.
ow do 2 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: 9sin# scope resolution operator
throu#h the usin# 5eyword. This is shown in followin# e8ample:namespace name
&class sample
& 11 code
'
namespace name!
&class sample!
& 11 code
'
usin# namespace name! ' void main( +
&name::sample s '
sample! s! '
ere, class sample is referred usin# the scope resolution operator. Bn the other
from creatin# objects outside the class. A static memberfunction called create( + is used to create an object of the class. 2n this function
the condition is chec5ed whether or not ptr is N9HH, if it is then anobject is created dynamically and its address collected in ptr is
returned. 2f ptr is not N9HH, then the same address is returned.Thus, in main( + on e8ecution of the first statement one object of sample #ets
created whereas on e8ecution of second statement, b holds theaddress of the first object. Thus, whatever number of times you call create( +function, only one object of sample class will be available.
.
ow do 2 write code to add functions, which would wor5 as #et and put properties of
The Bn1Bff fla#s are turned on usin# the setf( + function and are turned off usin# theunsetf( + function. To set the Bn1Bff fla#s, the one ar#ument
setf( + function is used. The fla#s wor5in# in #roups are setthrou#h the twoar#ument setf( + function. 3or e8ample, to left justify a
strin# we can set the fla# as,cout.setf ( ios::left + '
cout << >L2C2T Na#pur> 'To remove the left justification for subse4uent output we can say,
cout.unsetf ( ios::left + '
The fla#s that can be set1unset include s5ipws, showbase, showpoint, uppercase,
showpos, unitbuf and stdio. The fla#s that wor5 in a #roup canhave only one of these fla#s set at a time.
6./hat is the purpose of ios::basefield in the followin# statement?
cout.setf ( ios::he8, ios::basefield + 'Ans: This is an e8ample of formattin# fla#s that wor5 in a #roup. There is a fla# foreach numberin# system (base+ li5e decimal, octal and
he8adecimal. Collectively, these fla#s are referred to asbasefield and are specified by ios::basefield fla#. /e can have only one of these
fla#s on at a time. 2f we set the he8 fla# as setf ( ios::he8 + then wewill set the he8 bit but we wont clear the dec bit resultin# in
undefined behavior. The solution is to call setf( + as setf( ios::he8, ios::basefield +. This call first clears all the bits and then sets the he8 bit.
.
Can we #et the value of ios format fla#s?
Ans: "esD The ios::fla#s( + member function #ives the value format fla#s. Thisfunction ta5es no ar#uments and returns a lon# ( typedefed to
fmtfla#s+ that contains the current format fla#s.
-.
2s there any function that can s5ip certain number of characters present in the inputstream?
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 ) , int d )MB3 + '
Sometimes it happens that some e8tra characters are left in the input stream whileta5in# the input such as, the n (Mnter+ character. This e8tra
character is then passed to the ne8t input and may poseproblem.
To #et rid of such e8tra characters the cin::i#nore( + function is used. This is
e4uivalent 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.
@.
/rite a pro#ram that implements a date class containin# day, month and year asdata members. 2mplement assi#nment operator and copyconstructor 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 '
11 copy constructor
date ( date ;d +&
day ) d.day '
month ) d.month ' year ) d.year '
11 an overloaded assi#nment operator date operator ) ( date d +
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 outputbut unit bufferin# provides a better performance than the unbuffered output.
F.
/hat 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 theios class. /hen manipulators are used, the formattin# instructions
are inserted directly into the stream. Oanipulators are of two types, those that
ta5e an ar#ument and those that dont.
!*.
/hat 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. /e can createuserdefined manipulators but setf( + function uses data
members of ios class only. The fla#s put on throu#h the setf( + functioncan be put off throu#h unsetf( + function. Such fle8ibility is not available with
manipulators.
!.ow do 2 #et the current position of the file pointer?
Ans: /e can #et the current position of the file pointer by usin# the tellp( + memberfunction of ostream class or tell#( + member function of istream class. These
functions return (in bytes+ positions of put pointer and #etpointer respectively.
!!./hat 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 wherene8t write would ta5e place in the file. The #et pointer specifies
the byte number in the file from where the ne8t readin# should ta5e place.
!0./hat do the nocreate and noreplace fla# ensure when they are used for openin# a
file?
Ans: nocreate and noreplace are fileopenin# modes. A bit in the ios class definesthese modes. The fla# nocreate ensures that the file must e8istbefore 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. /hen the app fla# is set then whatever we write#ets appended to the e8istin# file. /hen ate fla# is set we can
start readin# or writin# at the end of e8istin# file.
!6.
/hat is the limitation of cin while ta5in# input for character array?
Ans: To understand this consider followin# statements,
char strJK ' cin PP str '/hile enterin# the value for str if we enter more than characters then there is no
provision in cin to chec5 the array bounds. 2f the arrayoverflows, it may be dan#erous. This can be avoided by usin#
ere, s is the object of the class istrstream. /hen we are creatin# the object s, theconstructor of istrstream #ets called that receives a pointer to
the $ero terminated character array str. The statement s PPa#e PP salary PP name ' e8tracts the a#e, salary and the name from the istrstream
object s. owever, while e8tractin# the name, only the first
word of name #ets e8tracted. The balance is e8tracted usin#
rdbuf( +.
0*./hen the constructor of a base class calls a virtual function, why doesnt the
override function of the derived class #ets called?
Ans: /hile buildin# an object of a derived class first the constructor of the base class
and then the constructor of the derived class #ets called. Theobject is said an immature object at the sta#e when theconstructor of base class is called. This object will be called a matured object after
the e8ecution of the constructor of the derived class. Thus, if wecall a virtual function when an object is still immature,
obviously, the virtual function of the base class would #et called. This isillustrated in the followin# e8ample.
Can 2 have a reference as a data member of a class? 2f yes, then how do 2 initialiseit?
Ans: "es, we can have a reference as a data member of a class. A reference as adata member of a class is initialised in the initialisation list ofthe 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 ) * '
sample s ( j + ' s.show( + '
ere, i refers to a variable j allocated on the stac5. A point to note here is that we
cannot bind a reference to an object passed to the constructoras a value. 2f we do so, then the reference i would refer to the
function parameter (i.e. parameter ii in the constructor+, which woulddisappear as soon as the function returns, thereby creatin# a situation of
The new operator allocates memory and calls the constructor. 2n the constructor wehave allocated memory on heap, which is pointed to by p. 2f we
release the object usin# the free( + function the object would die but the memory
allocated in the constructor would lea5. This is because free( + bein# a C libraryfunction 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 locatedusin# delete, the destructor would #et called where we have
tried to release the memory pointed to by p. Since p contains #arba#ethis may result in a runtime error.
0.
Can we distribute function templates and class templates in object libraries?
Ans: NoD /e 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 thatcreates an object from a class template can #et compiled. This is because the
compiler merely chec5s whether the call matches the declaration (in case of functiontemplate+ and whether the object definition matches class declaration (in case of
class template+. Since the function template and the class template definitions arenot found, the compiler leaves it to the lin5er to restore this. owever, durin#lin5in#, lin5er doesnt find the matchin# definitions for the function call or a matchin#
definition for object creation. 2n short the e8panded versions of templates are not
found inthe object library. ence the lin5er reports error.
0-./hat is the difference between an inspector and a mutator ?
Ans: An inspector is a member function that returns information about an objects
state (information stored in objects data members+ without chan#in# the objects
state. A mutator is a member function that chan#es the state of an object. 2n theclass Stac5 #iven below we have defined a mutator and an inspector.
class Stac5 &
public : int pop( + '
int #etcount( + '
2n the above e8ample, the function pop( + removes top element of stac5 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 thestac5 without chan#in# the stac5.
0@.
Namespaces:
The CEE lan#ua#e provides a sin#le #lobal namespace. This can cause problemswith #lobal name clashes. 3or instance, consider these two CEE header files:
11 file.h
float f ( float, int + ' class sample & ... '
11 file!.h
class sample & ... '
/ith 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 thusavoids the possibility that a name will conflict with names declared elsewhere in the
pro#ram. 2t 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 theyappear in separate namespaces, each name will be uni4ue because of the addition of
the namespace identifier. 3or e8ample:
11 file.h namespace file
& float f ( float, int + ' class sample & ... '
11 file!.h
namespace file! &
class sample & ... '
Now the class names will not clash because they become file::sample and
file!::sample, respectively.
0.
/hat would be the output of the followin# pro#ram?
Since the user class contains three elements, int, float and char its si$e would be Fbytes (int6, float6, char+ under /indows and @ bytes (int!, float6, char+
under IBS. Second output is a#ain the same because u is an object of the classuser. 3inally 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 isbecause pac5in# is done for an object in memory to increase the access efficiency.3or e8ample, 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. 9nli5e this, /indows
bein# a 0!bit BS the object would be ali#ned on a 6byte boundary. ence the si$eof the object would be reported as ! bytes. To force the ali#nment on a byte
boundary, write the followin# statement before the class declaration.%pra#ma pac5 ( +
0F.
/rite a pro#ram that will convert an inte#er pointer to an inte#er and viceversa.
Ans: The followin# pro#ram demonstrates this.%include
void main( + &
int i ) -*** '
int =iptr ) reinterpret7cast ( i + ' cout << endl << iptr '
iptrEE '
cout << endl << iptr '
i ) reinterpret7cast ( iptr + '
cout << endl << i '
iEE 'cout << endl << i '
6*.
/hat is a const7cast?
Ans. The const7cast is used to convert a const to a nonconst. This is shown in thefollowin#
pro#ram:%include
void main( + &
const int a ) * ' int =ptr ) ( int = + ;a ' 11one way
ptr ) const7cast7 ( ;a + ' 11better way
ere, the address of the const variable a is assi#ned to the pointer to a nonconst
variable. The const7cast is also used when we want to chan#e the data members ofa class inside the const member functions. The followin# code snippet shows this:
class sample &
private:int data'
public:void func( + const
&
(const7cast (this++Pdata ) @* '
'
6./hat is forward referencin# and when should it be used?
Ans: 3orward referencin# is #enerally re4uired when we ma5e a class or a functionas 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 +&
11 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. 2t#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 theforward reference of class sample.
class sample '
6!.
ow would you #ive an alternate name to a namespace?
Ans: An alternate name #iven to namespace is called a namespacealias.
namespacealias is #enerally used to save the typin# effort when the names ofnamespaces are very lon# or comple8. The followin# synta8 is used to #ive an alias
to a namespace.namespace myname ) my7old7very7lon#7name '
60.
9sin# a smart pointer can we iterate throu#h a container?
Ans: "es. A container is a collection of elements or objects. 2t helps to properlyor#ani$e and store the data. Stac5s, lin5ed lists, arrays are e8amples of containers.
3ollowin# pro#ram shows how to iterate throu#h a container usin# a smart pointer.%include
class smartpointer
&
private :int =p ' 11 ordinary pointerpublic :
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 ( * + '
for ( int i ) * ' i <) F ' iEE +
cout << =spEE << endl '
ere, sp is a smart pointer. /hen we say =sp, the operator = ( + function #ets called.2t returns the inte#er bein# pointed to by p. /hen we say spEE the operator EE ( +
function #ets called. 2t increments p to point tothe ne8t element in the array and then returns the address of this new location.
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 thedata members name, a#e and salary. The store( + function is used to write an object
to the file. 2n this function a file has been opened in append mode and each timedata of current object has been stored after the last record (if any+ in the
file.3unction 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.
6./hy is it necessary to use a reference in the ar#ument to the copy constructor?
Ans : 2f 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 callitself to ma5e this copy. This process would #o on and on until the compiler runs out
of memory. This can be e8plained with the help of followin# e8ample:class sample
&int i '
public :
sample ( sample p +&
i ) p.i '
'
void main( +
&sample s '
sample s ( s + '
/hile e8ecutin# the statement sample s ( s +, the copy constructor would #etcalled. As the copy construct here accepts a value, the value of s would be passed
which would #et collected in p. /e can thin5 of this statement as sample p ) s. erep 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 anar#ument in a copy constructor.
6-.
Qirtual Oultiple 2nheritance:A class b is defined havin# member variable i. Suppose two classes d and d! are
derived from class b and a class multiple is derived from both d and d!. 2f variable i
is accessed from a member function of multiple then it #ives error as member isambi#uous. To avoid this error derive classes d and d! with modifier virtual as
shown in the followin# pro#ram. %include
class b&
public :int i 'public :
fun( +
&i ) * '
'
class d : virtual public b&
public :fun( +
&
i ) ' '
class d! : virtual public b &
public :fun( +
&i ) ! '
'
class multiple : public d, public d!
&public :
fun( +&
i ) * '
'
void main( +&
multiple d 'd.fun( + '
cout << d.i '
6@.
Can we use this pointer in a class specific, operatoroverloadin# function for newoperator?
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 4uestion of the this pointer #ettin# passed to operator new( +.
6.
Can we allocate memory dynamically for a reference?
Ans: NoD 2t is not possible to allocate memory dynamically for a reference. This isbecause, 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.
6F.
/hen should 2 overload new operator on a #lobal basis or a class basis?
Ans: /e overload operator new in our pro#ram, when we want to initiali$e a dataitem or a class object at the same place where it has been allocated memory. The
followin# e8ample shows how to overload new operator on #lobal basis.
%include
%include
void = operator new ( si$e7t s +
&void =4 ) malloc ( s + '
return 4 '
void main( +
&int =p ) new int '
=p ) ! '
cout << =p '
/hen the operator new is overloaded on #lobal basis it becomes impossible toinitiali$e the data members of a class as different classes may have different types of
data members. The followin# e8ample shows how tooverload new operator on classbyclass basis.
ere, different types of e8ceptions are thrown by the member functions of the classsample. /hile catchin# the e8ception instead of four different catch bloc5s we can as
well define one sin#le catch bloc5. Note the synta8 for definin# the catch bloc5,where we have used three dots (V+ in the formal parameter list. This indicates that
any thrown e8ception should #et cau#ht in the same catch bloc5. /hen thee8ception is thrown from the fun6( + control reaches the catch bloc5, i#norin# the
Ans: To avoid name man#lin# the function should be declared with an e8tern >C>attribute. 3unctions declared as e8tern >C> are treated as Cstyle functions. ence
the compiler does not man#le them. The followin# code snippet shows how todeclare such a function.
%include
e8tern >C> void display( + &
cout << >See the effect of C in CEE > '
void main( +
&display( + '
.
Can we allocate memory dynamically for a reference?
Ans: No, it is not possible to allocate memory dynamically for a reference. Areference 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 allowus to dynamically allocate the memory for references.
-./hat is WTT2?
Ans: WTT2 stands for Wun Time Type 2nformation. /e use virtual function
mechanism where we can call derived classs member functions usin# base classs
pointer. owever, many times we wish to 5now the e8act type of the object. /e can5now the type of the object usin# WTT2. A function that returns the type of the object
is 5nown as WTT2 functions. CEE supports two ways to obtain information about theobjects class at run time, they are typeid( + operator and dynamic7cast operator.
@.
/hat is Iata Conversion?Ans: Assi#nments between types whether they are basic or userdefined, are
handled by the compiler. 2f the variables are of different basic types compiler calls aspecial routine to convert the value. Gut if we want to convert between userdefined
data type and basic types we have to write conversion routine ourselves. Aconversion routine to convert userdefined data type strin# to inte#er is shown
conversions, narrowin# conversions, conversion from void= and implicit typeconversions. const7cast is used to convert a const to a nonconst. reinterpret7cast is
used to assi#n one 5ind of pointer to another.
-.
/hat will be the output of the followin# pro#ram?
%include
class A
& public :
A( + &
cout << >Weached in Constructorn> '
'
void main( +
& A a( + ' A b '
Butput : Weached in Constructor
Constructor #ets called only once when the object b is created. /hen the statement
A a( + ' #ets e8ecuted constructor does not #et called. This is because compiler ta5esthis statement as a prototype declaration of function a( + that returns an object of
class A. owever, if we pass ar#uments li5e A a ( * + '
Compiler would search for one ar#ument constructor and if not found would flash an
error.
-!.
/hat is a container?
Ans: A container is an object that holds other objects. Qarious collection classes li5eHist, ash Table, AbstractArray, etc. are the e8amples of containers. /e can use the
classes to hold objects of any derived classes. The containers provide variousmethods usin# which we can #et the number of objects stored in the container and
iterate throu#h the objects stored in it.
-0.
3unction template overloadin#
Bne can declare several function templates with the same name and even declare acombination of function templates and ordinary functions with the same name. /hen
an overloaded function is called, overload resolution is necessary to find the ri#ht
function or template function to invo5e.3or e8ample:
template < class T P T s4rt ( T + ' template < class T P comple8 < T P s4rt ( comple8 < T P + 'double s4rt (
double + ' void f ( comple8 < double P $ +
& s4rt ( ! + ' 11 s4rt < int P ( int + s4rt ( !.* + ' 11 s4rt ( double +
s4rt ( $ + ' 11 s4rt < comple8 < double P ( comple8 < double P +
2n 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 weapply the usual function overload resolution rules to these speciali$ations and all
ordinary functions.
-6.
M8ception andlin# in CEE 2n CEE we can handle runtime errors #enerated by cEE classes by usin# three new
5eywords: throw, catch, and try. /e also have to create an e8ception class. 2f durin#the course of e8ecution of a member function of
this class a runtime error occurs, then this member function informs the applicationthat an error has occurred. This process of informin# is called throwin# an
e8ception. The followin# code shows how to deal with e8ception handlin#. class sample
2f you run this pro#ram it is bound to #ive you errors. This is because of the rules ofinheritance:
. Mach base class not specified virtual will have its own subobject representin# it.2n the above pro#ram, if we create object of d it will have a subobject of class base
containin# a data member data. 2f we create an object of class der it will have subobjects of classes d and d! and both the subobjects will refer to a separate copy of
data. ence, to access data from class der we will have to mention the class name.3or e8ample, d::data or d!::data.
!. 2f we want that only one subobject should e8ist we must use the concept of
virtual base class. The sin#le object of this will represent every base class of #ivenname that is specified to be virtual
class. After ma5in# d and d! as virtual base class if we create an object of der onlyone subobject would e8ist and so accessin# data would no lon#er #ive us errors.
Ans: Suppose, 2 wish to declare a pointer to a member function that receives an intand returns an int. 2 will have to declare it as int (A::= + ( int +. 3ollowin# is an
e8ample.
%include
class A
&
public :
int fun ( int f + &
cout << >in funn> '
return f = f '
'
typedef int ( A:: =pfun + ( int + '
void main( + &
pfun p ) A::fun ' A a '
int s ) ( a.=p + ( - + ' cout << s '
-@.
/hat is the disadvanta#e of a template function?
Ans: A template function cannot be distributed in the obj form. This is because, withwhich 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 merelycompilin# it.
-.
ow to declare a pointer to the data members of a class?
Ans: 3ollowin# pro#ram shows how to declare a pointer to nonfunction members of
ere, we have initialised the data member a usin# the pointer pa.
-F.ow to allocate memory for a multidimensional array dynamically?
Ans: Oany times we need to allocate memory for a multidimensional array
dynamically. Gecause of comple8ity of pointers many find this difficult. 3ollowin#pro#ram allocates memory for a 0 8 0 array dynamically, copies contents of a 0 8 0
array in it and prints the contents usin# the pointer.
%include%include
int aJ KJ0K ) & , !, 0,
6, , -, @, , F
'
void main( +
& int ==p '
p ) new int =J0K ' for ( int i ) * ' i < 0 ' iEE +
pJiK ) new intJ0K '
for ( i ) * ' i < 0 ' iEE + for ( int j ) * ' j < 0 ' jEE +
/hen should we use the :: ( scope resolution + operator to invo5e the virtualfunctions?
Ans: enerally, :: operator is used to call a virtual function from constructor ordestructor. 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.
@.
ow do 2 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 ) '
p P= pdm ) ! '
cout << s .= pdm << endl ' cout << p P= pdm << endl '
2n 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. Ne8t, 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.
@!.
/hat happens when we add an int value to a user defined type of object?
Ans: /henever 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 thereturn type as on doin# so the compiler flashes an error.
%include
class sample &
int i '
public :
sample ( + & i ) * '
operator int( +
& return this P i '
'
void main( + &
sample s '
int i ' i ) s E * '
cout << i '
2n the above pro#ram on addin# * to an object s, the value of i would become !*.
@0.Can we have a reference to an array?
Ans: "es, we can have a reference to an array.
int aJ K ) & , !, !, F ' int ( ;r + J 6 K ) a ' 11 reference to an array
ere, r is a reference to an array of four elements. /e 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 < 6 ' iEE +cout << r JiK << endl '
2f you run this pro#ram it is bound to #ive errors. The error lies in the statement d0) * E d! ' /e may thin5 that since we have overloaded E operator this statement
would add * to d!. Gut this does not happen. This is because the specifiedstatement will #et converted as d0 ) *.operatorE ( d! + ' This means that this
statement should call the operatorE( + function that ta5es an object of distance classas 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:
int f ) 8.feet E 8!.feet ' return distance ( f + '
/hen compiler would see that the friend operatorE( + function is available it wouldconvert the statement d0 ) * E d! as operatorE (*, d! +. Now since * is passed
as a parameter not as a callin# object there would be no error. Thus in such cases
Ans: Suppose, details of an employee such as name, desi#nation, a#e, etc. arestored in different types of variables. Now, if we wish to concatenate these details ina character array we will have to use various strin# manipulation functions li5e
strcpy( + and strcat( +. 2nstead 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. /e candeclare the memory allocated for the array as stream and use the << operator to
store variables havin# different types in this memory. 3ollowin# pro#ram shows howto achieve this.
%include void main( +
& char buff J*K '
char strJ K ) >Sanjay> '
char desi#J K ) >Oana#er> ' char jdJ K ) >!@1!1FF> ' int a#e ) 0 '
@@.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 dis5 filedata.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 firstparallel port. So, the file name for the printer should be WN or lpt.
%includevoid main( +
& ifstream i ( >data.dat> + '
ofstream o '
o.open ( >WN> + ' char ch '
while ( + &
i.#et ( ch + ' if ( i.eof( + +
brea5 '
o.put ( ch + '
o.put ( 8*C + '
@.
/e 5now that a destructor is automatically called when an object of a class #oes outof scope. There is another case where destructor is called automatically. 2f an object
is created in a try bloc5 and an e8ception is thrown after the object is created, thenthe destructor is called automatically.
Can a function call be at the left hand side of the assi#nment operator?
Ans: "es. 3ollowin# pro#ram shows how it is possible.%include
class ref&
private :struct data&
int a ' char =p '
d, d! 'public :
data ;set ( +&
return d '
data ;#et ( +&
cin PP d!.a PP d!.p '
return d! ' '
void main( +&
ref r 'r.set( + ) r.#et( + '
r.print( + '
2n the above pro#ram the functions #et( + and set( + both return a reference to theobject of the structure data. /e have assi#ned the reference returned by #et( + to
the reference returned by set( + function. That is, we are assi#nin# d! to d. So, the
values of d! would #et assi#ned to d. "ou can chec5 this out by printin# the valuesof d.
*.
2f a class contains a virtual function a pointer called QTW is created. This QTWbecomes a part of every object of that class. The first two bytes (in IBS+ are
occupied by QTW. /e can prove this by displayin# the first two bytes of memoryallocated for the objects. 3ollowin# pro#ram shows how this can be achieved.
2n CEE we can handle runtime errors #enerated by cEE classes by usin# three new5eywords: throw, catch, and try. /e also have to create an e8ception class. 2f durin#
the course of e8ecution of a member function ofthis class a runtime error occurs, then this member function informs the application
that an error has occurred. This process of informin# is called throwin# ane8ception. The followin# code shows how to deal with e8ception handlin#.
class sample
& public :
class errorclass &
' void fun( +
& if ( some error occurs +
throw errorclass( + 11 throws e8ception
'
11application void main( +
& try
& sample s '
s.fun( + '
catch ( sample::errorclass +
& 11 do somethin# about the error
!.
Accessin# a private data member from a different Bbject...
Iifferent objects of the same class can access each others members, even if thesemembers are private. 3or e8ample:
objptr P n ) * ' cout << >Qalue of this objects f is : > << f << endl '
cout << >Qalue of other objects f> << objptr P n << endl ' 11 another objects private memberD
' void main( +
& sample s ( -.f + , s! ( !.f + '
s.f ( ;s! + ' 11 s chan#es s!s n
Typically, this codin# style should be avoided. owever, you should be aware thatprivate 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.
0.
Can you access private data members of a class from out side the class? Ans: "es. This pro#ram shows how.
%includeclass emp
private :
int i ' public :
emp( + &
i ) * '
'
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. /ith the help of thispointer private data member i is accessed in main( +.
6./hy creatin# array of references is not possible?
Ans: The array name always refers or points to the $eroeth element. 2f array is ofreferences 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 ofreferences too is not possible.
.ow do 2 call a virtual function of a class usin# a pointer to a function ? Ans :
2n the above pro#ram class Cvirtual consists of a virtual function vfun(+. 2n variable p
we have stored the address of an object of class Cvirtual. /hile doin# so, we have
type casted the address of obj to int ==, because obj holds a hidden data membercalled vptr, which in turn holds the address of virtual function vfun( +. 2n pf, 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.
-.
/hy 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 nonstatic member functions can be called throu#h an object only.
Gut when an overloaded new operator function #ets called the object doesnt standcreated. 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.
@.
/hat is a pure virtual destructor?
Ans: Hi5e a pure virtual function we can also have a pure virtual destructor. 2f a base
class contains a pure virtual destructor it becomes necessary for the derived classesto 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 inthe hierarchy of inheritance are always called as a part of destruction.
./hen we are re4uired to find offset of an element within a structure? or, how do wecall 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$e7t + ;( ( ( outer= + * + P in + '
pout P outfunc( + '
'inner in '
outfunc( +&
cout << >in outer classs function> '
'
void main( +&
outer out 'out.in.infunc( +
2n the above e8ample we are callin# outer::outfunc( + from inner::infunc(+. To calloutfunc( + we need a pointer to the outer class. To #et the pointer we have
subtracted offset of the inner classs object (base address of outer classs object address of inner classs object+ from address of inner classs object.
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 andtype.
F*.Some pro#rams need to e8ercise precise control over the memory areas where data
is placed. 3or e8ample, suppose we wish to read the contents of the boot sector intoa structure. 3or this the byte arran#ement of the
structure elements must match the arran#ement of various fields in the boot sector
of the dis5.
The %pra#ma pac5 directives offer a way to fulfill this re4uirement. The %pra#ma
pac5 directive specifies pac5in# ali#nment for structure and union members. The%pra#ma ta5es effect at the first structure or union declaration after the
%pra#ma is seen. Consider the followin# structure:%pra#ma pac5 (+
struct emp&
int a 'float s '
char ch '
'%pra#ma pac5( +
ere, %pra#ma pac5 ( + lets each structure element to be#in on a byteboundary. ence the si$e of the structure will be F. (int 6, float 6, char +. 2f we
use %pra#ma pac5 ( ! + each structure element can be#in on a !byte boundary.ence the si$e of the structure will be *. (int 6, float 6, char !+.
F.
ow to restrict a friend classs access to the private data members?
Ans: 2f we declare a class as a friend of our class the friend class can access theprivate data members of our class. owever, if we want we can restrict this access to
some selective functions of the class. 3ollowin# pro#ram shows how to achieve this:
2n the above pro#ram only the X::print( + function can access the private data
members of class Y.
F!.
/hat 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 whichparticular 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 to5ens 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 s ' s.fun ( -, A + '
s.fun ( >Anil>, .f + '
At the time of resolvin# the calls to fun( + function the lin5er would not be able tofind the definition of the overloaded function fun( + and it would report an error. 2f
you loo5 at these errors you will see the man#led names li5e, (?
funZtestZZ[AMX\\ZY+ and (?funZtestZZ[AMXOOZY+. Note that differentcompilers may use different name man#lin# schemes.
F0.
ow would you call a C function from CEE code?Ans: 9sin# e8tern >C>.
The function prototype must be preceded by e8tern >C>. Oore than one C functionscan be #rouped inside braces as shown below:
e8tern >C>
&
void f( + 'void f( + '
11 2n cfunc.c
%includevoid f( +
&printf ( >in f( +> + '
11 2n func.cpp%includee8tern >C> void f( + '
void main( +&
f( + '
Mnsure that both .c and .cpp files are in the same project.
F6.ow to restrict the number of floatin#point di#its displayed ?
Ans: /hen 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. 3or e8ample,
cout << setprecision ( 0 + << !.06-@ '
This statement would #ive the output as !.06@.
F.
/hat is a wild pointer ?
Ans: A wild pointer is the one that points to a #arba#e value. 3or e8ample, anuninitiali$ed pointer that contains #arba#e value or a pointer that refers to somethin#
F-.ow friend function helps to increase the versatility of overloaded operators?
Ans: Consider the followin# statement,
s! ) s = ! 'where, s and s! are objects of sample class. This statement would wor5 if the
overloaded operator = ( sample s + or conversion function is provided in the class.2nternally this statement would #et converted to,
s! ) s.operator = ( ! + '
The function materiali$es because it is called with an object s. The this pointer of swould #et passed implicitly. To collect ! in s, first the compiler would call the one
ar#ument constructor, then it would build anameless object, which then would #et collected in s. owever, if we write the
above statement as,s! ) ! = s '
then it wont compile. This is because the call now would #et treated as,s! ) !.operator = ( s + '
and ! is not an object. The friend function helps to #et rid of such a situation. This is
ere the operator =( + function ta5es two parameters. This is because the operator
function is no lon#er a member function of the class. 2t is a friend of the classsample. Thus the statement s! ) s = ! ' would not ta5e the form s!.operator =( ! +. This e8ample shows that usin# friend permits the overloaded operators to be
more versatile.
F@.
/hat is a const7cast?
Ans: The const7cast is used to convert a const to a nonconst. This is shown in the
followin# pro#ram.%include
void main( + &
const int a ) * '
int =ptr ) ( int = + ;a ' 11 one way
ptr ) const7cast ( ;a + ' 11 better way
ere, the address of the const variable a is assi#ned to the pointer to a nonconst
variable. The const7cast is also used when we want to chan#e the data members ofa class inside the const member functions. The followin# code snippet shows how to
do this.
class sample&
private :int data '
public :void fun( + const
&
( const7cast ( this + + P data ) @* '
'
F.
9sin# a smart pointer we can ma5e an object appear li5e a pointer.
2f a class overloads the operator P then any object of that class can appear li5e apointer when the operator P ( + is called. The followin# pro#ram illustrates this.
The beauty of overloadin# operator P is that even thou#h sp is an object we can
ma5e it wor5 li5e a pointer. The operator P ( + returns the address of the object ofthe type test. 9sin# 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 wecan still call it usin# sp.
FF.
Can we apply delete on this pointer inside a member function?
Ans : "esD 2f the member function of a class is called usin# a pointer to an object,
which is allocated dynamically, the object would #et deleted. Gut if the memberfunction is called usin# the object, which is allocated statically, then a runtime error
would occur. This is because we cannot call delete on statically allocated objects.This is illustrated in the followin# e8ample.
sample s ' s.fun( + ' 11 would throw a runtime error
**./hy cant data members of a class be initiali$ed at the time of declaration as #iven
in the followin# code? class emp &
private :
int j ) * ' '
Ans: Oemory for data members of a class is allocated only when object of that classis created. Bne cannot store data in a memory location, which does not e8ist at all.
Therefore initiali$ation at the time of declarationis not possible.
*.
/hy in a copy constructor an object is collected in a reference to object as shownbelow?
%includeclass emp
& public :
emp( + &
emp ( emp; +
&
cout << >copy> '
' void main( +
& emp e '
emp e ) e '
Ans: A copy constructor is called when an object is created and initialised at the
same time. 2t is also called when object is passed to a function. So, 2f we pass theobject to copy constructor copy constructor would #et called recursively. Thus it will
stuc5 up in an infinite loop.
*!.
/hat is Marly Gindin# and Iynamic Gindin#?
Ans: The term bindin# refers to the connection between a function call and the actualcode e8ecuted as a result of the call. Marly Gindin#: 2f which function is to be called is
5nown at the compiletime it is 5nown as static or early bindin#. Iynamic Gindin#: 2fwhich function is to be called is decided at run time it is called as late or dynamic
bindin#. Iynamic bindin# is so called because the actual function called at runtime
depends on the contents of the pointer. 3or e8ample, call to virtual functions, call tofunctions to be lin5ed from dlls use late bindin#.
*0./hen can we use the function ostrstream::free$e( +?
Ans: /hile outputtin# data to memory in the inmemory formattin# we need tocreate an object of the class ostrstream. The constructor of ostrstream receives the
address of the buffer but if we want that the ostrstream
object should do its own memory mana#ement then we need to create an ostrstreamobject with no constructor ar#uments as:
ostrstream s 'Now s will do its own memory mana#ement. /e can stuff as many bytes into it as
we want. 2f it falls short of memory, it will allocate more memory. 2f it cannot, it mayeven move the bloc5 of memory. /hen the object #oes out of scope, the heap
stora#e is automatically released. This is a more fle8ible approach if we do not 5nowhow much space we are #oin# to need. 2f we want the physical address of the
memory used by s we can obtain it by callin# the str( + member function:
char= p ) s.str( + 'Bnce str( + has been called then the bloc5 of memory allocated by ostrstream cannotbe moved. This is lo#ical. 2t cant move the bloc5 since we are now e8pectin# it to be
at a particular location. 2n such a case wesay that ostrstream has free$ed itself. Bnce fro$en we cant add any more characters
to it. Addin# characters to a fro$en ostrstream results in undefined behavior. 2naddition, the ostrstream is no lon#er responsible for cleanin# up the stora#e. "ou
too5 over that responsibility when you as5ed for the char = with str( +. /e can cleanthe stora#e in two ways: 9sin# the delete operator as shown below:
ostrstream s ' char =p '
p ) s.str( + '
delete p 'Gy unfree$in# the ostrstream. "ou do this by callin# free$e( +, with an ar#ument .
Iurin# free$in# it is called with the default ar#ument of *.