C++ Interview Questions
C++ Interview Questions
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.
-------------------------------------------------------------------------------------------------
2.Can user-defined object be declared as static data member of another class?
Ans: Yes. The following code shows how to initialize a user-defined object.
#include
Here we have initialized the object s by calling the one-argument constructor. We can use the
same convention to initialize the object by calling multiple-argument constructor.
-------------------------------------------------------------------------------------------------
3.What is forward referencing and when should it be used?
#include
o.setf ( ios::hex) ;
return o ;
void main( )
{
}
-------------------------------------------------------------------------------------------------
6.We all know that a const variable needs to be initialized at the time of declaration. Then
how come the program given below runs properly even when we have not initialized p?
#include
void main( )
{
const char *p ;
p = "A const pointer" ;
cout << p ;
}
Ans: The output of the above program is 'A const pointer'. This is because in this program p is
declared as 'const char*' which means that value stored at p will be constant and not p and so the
program works properly
-------------------------------------------------------------------------------------------------
Ans: There are two ways in which we can refer to a name of class or function that is defined
within a namespace: Using scope resolution operator through the using keyword. This is shown
in following example:
namespace name1
{
class sample1
{
// code
} ;
}
namespace name2
{
class sample2
{
// code
} ;
}
using namespace name2 ;
void main( )
{
name1::sample1 s1 ;
sample2 s2 ;
}
Here, class sample1 is referred using the scope resolution operator. On the other hand we can
directly refer to class sample2 because of the statement using namespace name2 ; the using
keyword declares all the names in the namespace to be in the current scope. So we can use the
names without any qualifiers.
-------------------------------------------------------------------------------------------------
Ans: No!. This is because even if we provide the default arguments to the parameters of the
overloaded operator function we would end up using the binary operator incorrectly. This is
explained in the following example:
sample operator + ( sample a, sample b = sample (2, 3.5f ) )
{
}
-------------------------------------------------------------------------------------------------
9.How do I 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. Following program demonstrates how to provide such conversion function.
#include
class sample
{
static sample *ptr ;
private:
sample( )
{
}
public:
static sample* create( )
{
if ( ptr == NULL )
ptr = new sample ;
return ptr ;
}
} ;
sample *sample::ptr = NULL ;
void main( )
{
sample *a = sample::create( ) ;
sample *b = sample::create( ) ;
}
Here, 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 creating objects outside the class. A static
member function called create( ) is used to create an object of the class. In this function the
condition is checked whether or not ptr is NULL, if it is then an object is created dynamically
and its address collected in ptr is returned. If ptr is not NULL, then the same address is returned.
Thus, in main( ) on execution of the first statement one object of sample gets created whereas on
execution 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.How do I write code to add functions, which would work as get and put properties of a
class?
Ans: The ios class contains formatting flags that help users to format the stream data. Formatting
flags are a set of enum definitions. There are two types of formatting flags:On/Off flagsFlags that
work in-group The On/Off flags are turned on using the setf( ) function and are turned off using
the unsetf( ) function. To set the On/Off flags, the one argument setf( ) function is
used. The flags working in groups are set through the two-argument setf( ) function. For
example, to left justify a string we can set the flag as,cout.setf ( ios::left ) ;cout << "KICIT
Nagpur" ;To remove the left justification for subsequent output we can say,cout.unsetf
( ios::left ) ;The flags that can be set/unset include skipws, showbase, showpoint, uppercase,
showpos, unitbufand stdio. The flags that work in a group can have only one of these flags set at
a time.
-------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
16.Is there any function that can skip certain number of characters present in the input
stream?
Ans: Yes! This can be done using cin::ignore( ) function. The prototype of this function is as
shown below:
istream& ignore ( int n = 1, int d =EOF ) ;
Sometimes it happens that some extra characters are left in the input stream while taking the
input such as, the '\n' (Enter) character. This extra character is then passed to the next input and
may pose problem.
To get rid of such extra characters the cin::ignore( ) function is used. This is equivalent to fflush
( stdin ) used in C language. This function ignores the first n characters (if present) in the input
stream, stops if delimiter d is encountered.
-------------------------------------------------------------------------------------------------
17.Write a program that implements a date class containing day, month and year as data
members. Implement assignment operator and copy constructor in this class.
Ans: The unit buffering (unitbuf) flag 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 using
unbuffered output but unit buffering provides a better performance than the unbuffered output.
-------------------------------------------------------------------------------------------------
19.What are manipulators?
Ans: Manipulators 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
formatting flags of the ios class. When manipulators are used, the formatting instructions are
inserted directly into the stream. Manipulators are of two types, those that take an argument and
those that don't.
-------------------------------------------------------------------------------------------------
20.What 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 flags of the ios but manipulators directly insert the
formatting instructions into the stream. We can create user-defined manipulators but setf( )
function uses data members of ios class only. The flags put on through the setf( ) function can be
put off through unsetf( ) function. Such flexibility is not available with manipulators.
-------------------------------------------------------------------------------------------------
21.How do I get the current position of the file pointer?
Ans: We can get the current position of the file pointer by using the tellp( ) member function of
ostream class or tellg( ) member function of istream class. These functions return (in bytes)
positions of put pointer and get pointer respectively.
-------------------------------------------------------------------------------------------------
22.What are put and get pointers?
Ans: These are the long integers associated with the streams. The value present in the put pointer
specifies the byte number in the file from where next write would take place in the file. The get
pointer specifies the byte number in the file from where the next reading should take place.
-------------------------------------------------------------------------------------------------
23. What do the nocreate and noreplace flag ensure when they are used for opening a file?
Ans: nocreate and noreplace are file-opening modes. A bit in the ios class defines these modes.
The flag nocreate ensures that the file must exist before opening it. On the other hand the flag
noreplace ensures that while opening a file for output it does not get overwritten with new one
unless ate or app is set. When the app flag is set then whatever we write gets appended to the
existing file. When ate flag is set we can start reading or writing at the end of existing file.
-------------------------------------------------------------------------------------------------
24. What is the limitation of cin while taking input for character array?
get ( str, DELIM ) - Extracts characters into array str until specified delimiter
(such as '\n'). Leaves delimiting character in stream.
get ( str, n, DELIM ) - Extracts characters into array str until n characters or
DELIM character, leaving delimiting character in stream.
-------------------------------------------------------------------------------------------------
25.What is the purpose of istream class?
Ans: The istream class performs activities specific to input. It is derived from the iosclass. The
most commonly used member function of this class is the overloaded >> operator which
canextract values of all basic types. We can extract even a string using this operator.
-------------------------------------------------------------------------------------------------
26.Would the following code work?
#include
void main( )
{
ostream o ;
o << "Dream. Then make it happen!" ;
}
Ans: No! This is because we cannot create an object of the ostream class since its constructor
and copy constructor are declared private.
Ans: No! The this pointer cannot be used inside a static member function. This is because a static
member function is never called through an object.
-------------------------------------------------------------------------------------------------
28.What is strstream?
Ans: strstream is a type of input/output stream that works with the memory. It allows using
section of the memory as a stream object. These streams provide the classes that can be used for
storing the stream of bytes into memory. For example, we can store integers, floats and strings as
a stream of bytes. There are several classes that implement this in-memory formatting. 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 taken from memory and strstream class derived from
iostream is used for memory objects that do both input and output.
-------------------------------------------------------------------------------------------------
29.
Ans: When we want to retrieve the streams of bytes from memory we can use istrestream. The
followingexample shows the use of istrstream class.
#include
cout << age << endl << salary << endl << name ;
cout << endl << s.rdbuf( ) ;
}
Here, s is the object of the class istrstream. When we are creating the object s, the constructor of
istrstream gets called that receives a pointer to the zero terminated character array str. The
statement s >> age >> salary >> name ; extracts the age, salary and the name from the istrstream
object s. However, while extracting the name, only the first word of name gets extracted. The
balance is extracted using rdbuf( ).
-------------------------------------------------------------------------------------------------
30.When the constructor of a base class calls a virtual function, why doesn't the override
function of the derived class gets called?
Ans: While building an object of a derived class first the constructor of the base class and then
the constructor of the derived class gets called. The object is said an immature object at the stage
when the constructor of base class is called. This object will be called a matured object after the
execution 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 get called. This is
illustrated in the following example.
#include
31.Can I have a reference as a data member of a class? If yes, then how do I initialise it?
Ans: Yes, we can have a reference as a data member of a class. A reference as a data member of
a class is initialised in the initialisation list of the constructor. This is shown in following
program.
#include
class sample
{
private :
int& i ;
public :
sample ( int& ii ) : i ( ii )
{
}
#include
class sample
{
private :
char *str ;
public :
sample ( char *s )
{
strcpy ( str, s ) ;
}
~sample( )
{
delete str ;
}
} ;
34. Why it is unsafe to deal locate the memory using free( ) if it has been allocated using
new?
Ans: This can be explained with the following example:
#include
As against this, if we allocate memory by calling malloc( ) the constructor would not get called.
Hence p holds a garbage address. Now if the memory is deal located using delete, the destructor
would get called where we have tried to release the memory pointed to by p. Since p contains
garbage this may result in a runtime error.
-------------------------------------------------------------------------------------------------
35.Can we distribute function templates and class templates in object libraries?
Ans: No! We 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 get compiled. This is because the compiler merely checks 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 linker to restore this. However, during
linking, linker doesn't find the matching definitions for the function call or a matching definition
for object creation. In short the expanded versions of templates are not found in
the object library. Hence the linker reports error.
-------------------------------------------------------------------------------------------------
36.What 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 changing the object's state. A mutator is a
member function that changes the state of an object. In the class Stack given below we have
defined a mutator and an inspector.
class Stack
{
public :
int pop( ) ;
int getcount( ) ;
}
In the above example, the function pop( ) removes top element of stack thereby changing the
state of an object. So, the function pop( ) is a mutator. The function getcount( ) is an inspector
because it simply counts the number of elements in the stack without changing the stack.
37. Namespaces:
The C++ language provides a single global namespace. This can cause problems with global
name clashes. For instance, consider these two C++ header files:
// file1.h
float f ( float, int ) ;
class sample { ... } ;
// file2.h
class sample { ... } ;
With these definitions, it is impossible to use both header files in a single program; the sample
classes will clash.A namespace is a declarative region 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 program. It is possible to use the same name in
separate namespaces without conflict even if the names appear in the same translation unit. As
long as they appear in separate namespaces, each name will be unique because of the addition of
the namespace identifier. For example:
// file1.h
namespace file1
{
float f ( float, int ) ;
class sample { ... } ;
}
// file2.h
namespace file2
{
class sample { ... } ;
}
Now the class names will not clash because they become file1::sample and file2::sample,
respectively.
-------------------------------------------------------------------------------------------------
38.What would be the output of the following program?
#include
class user
{
int i ;
float f ;
char c ;
public :
void displaydata( )
{
cout << endl << i << endl << f << endl << c ;
}
};
void main( )
{
cout << sizeof ( user ) ;
user u1 ;
cout << endl << sizeof ( u1 ) ;
u1.displaydata( ) ;
}
9 or 7
9 or 7
Garbage
Garbage
Garbage
Since the user class contains three elements, int, float and char its size would be 9 bytes (int-4,
float-4, char-1) under Windows and 7 bytes (int-2, float-4, char-1) under DOS. Second output is
again the same because u1 is an object of the class user. Finally three garbage values are printed
out because i, f and c are not initialized anywhere in the program.
Note that if you run this program you may not get the answer shown here. This is because
packing is done for an object in memory to increase the access efficiency. For example, under
DOS, the object would be aligned on a 2-byte boundary. As a result, the size of the object would
be reported as 6 bytes. Unlike this, Windows being a 32-bit OS the object would be aligned on a
4-byte boundary. Hence the size of the object would be reported as 12 bytes. To force the
alignment on a 1-byte boundary, write the following statement before the class declaration.
#pragma pack ( 1 )
-------------------------------------------------------------------------------------------------
39.Write a program that will convert an integer pointer to an integer and vice-versa.
Ans: The following program demonstrates this.
#include
void main( )
{
int i = 65000 ;
iptr++ ;
cout << endl << iptr ;
i++ ;
cout << endl << i ;
}
40.What is a const_cast?
Ans. The const_cast is used to convert a const to a non-const. This is shown in the following
program:
#include
void main( )
{
const int a = 0 ;
int *ptr = ( int * ) &a ; //one way
ptr = const_cast_ ( &a ) ; //better way
}
Here, the address of the const variable a is assigned to the pointer to a non-const variable. The
const_cast is also used when we want to change the data members of a class inside the const
member functions. The following code snippet shows this:
class sample
{
private:
int data;
public:
void func( ) const
{
(const_cast (this))->data = 70 ;
}
} ;
-------------------------------------------------------------------------------------------------
43.Using a smart pointer can we iterate through a container?
Ans: Yes. A container is a collection of elements or objects. It helps to properly organize and
store the data. Stacks, linked lists, arrays are examples of containers. Following program shows
how to iterate through a container using a smart pointer.
#include
Ans: Yes! This can be explained with the help of following example:
#include
#include
Ans : If we pass the copy constructor the argument by value, its copy would get constructed
using the copy constructor. This means the copy constructor would call itself to make this copy.
This process would go on and on until the compiler runs out of memory. This can be explained
with the help of following example:
class sample
{
int i ;
public :
sample ( sample p )
{
i = p.i ;
}
} ;
Ans: No! The this pointer is never passed to the overloaded operator new() member function
because this function gets called before the object is created. Hence there is no question of the
this pointer getting passed to operator new( ).
-------------------------------------------------------------------------------------------------
48.Can we allocate memory dynamically for a reference?
Ans: No! It is not possible to allocate memory dynamically for a reference. This is because,
when we create a reference, it gets 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 get tied.
Ans: We overload operator new in our program, when we want to initialize a data item or a class
object at the same place where it has been allocated memory. The following example shows how
to overload new operator on global basis.
#include
#include
public :
void* operator new ( size_t s, int ii )
{
sample *q = ( sample * ) malloc ( s ) ;
q -> i = ii ;
return q ;
}
} ;