Good Questions In
C++
!!Enjoy!!!
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.
-------------------------------------------------------------------------------------------------
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 <iostream.h>
class test
{
int i ;
public :
test ( int ii = 0 )
{
i = ii ;
}
} ;
class sample
{
static test s ;
} ;
test sample::s ( 26 ) ;
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?
Ans: Consider the following program:
class test
{
public :
friend void fun ( sample, test ) ;
} ;
class sample
{
public :
friend void fun ( sample, test ) ;
} ;
void fun ( sample s, test t )
{
// code
}
void main( )
{
sample s ;
test t ;
fun ( s, t ) ;
}
This program would not compile. It gives 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 using
it before its definition. To overcome this error we need to
give forward reference of the class sample before the
definition of class test. The following statement is the
forward reference of class sample. Forward referencing is
generally required when we make a class or a function as a
friend.
-------------------------------------------------------------------------------------------------
4.
The istream_withassign class has been derived from the istream
class and overloaded assignment operator has been added to it.
The _withassign classes are much like their base classes
except that they include overloaded assignment operators.
Using these operators the objects of the _withassign classes
can be copied. The istream, ostream, and iostream classes are
made uncopyable by making their overloaded copy constructor
and assignment operators private.
-------------------------------------------------------------------------------------------------
5.
How do I write my own zero-argument manipulator that should
work same as hex?
Ans: This is shown in following program.
#include <iostream.h>
ostream& myhex ( ostream &o )
{
o.setf ( ios::hex) ;
return o ;
}
void main( )
{
cout << endl << myhex << 2000 ;
}
-------------------------------------------------------------------------------------------------
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 <iostream.h>
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
-------------------------------------------------------------------------------------------------
7.
How do I 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: 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.
-------------------------------------------------------------------------------------------------
8.
While overloading a binary operator can we provide default
values?
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 ) )
{
}
void main( )
{
sample s1, s2, s3 ;
s3 = s1 + ; // error
}
-------------------------------------------------------------------------------------------------
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.
class circle
{
private :
int radius ;
public:
circle ( int r = 0 )
{
radius = r ;
}
} ;
class rectangle
{
private :
int length, breadth ;
public :
rectangle( int l, int b )
{
length = l ;
breadth = b ;
}
operator circle( )
{
return circle ( length ) ;
}
} ;
void main( )
{
rectangle r ( 20, 10 ) ;
circle c;
c = r ;
}
Here, when the statement c = r ; is executed the compiler
searches for an overloaded assignment operator in the class
circle which accepts the object of type rectangle. Since there
is no such overloaded assignment operator, the conversion
operator function that converts the rectangle object to the
circle object is searched in the rectangle class. We have
provided such a conversion function in the rectangle class.
This conversion operator function returns a circle object. By
default conversion operators have the name and return type
same as the object type to which it converts to. Here the type
of the object is circle and hence the name of the operator
function as well as the return type is circle.
-------------------------------------------------------------------------------------------------
10.
How do I write code that allows to create only one instance of
a class?
Ans: This is shown in following code snippet.
#include <iostream.h>
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: This is shown in following code.
#include <iostream.h>
class sample
{
int data ;
public:
__declspec ( property ( put = fun1, get = fun2 ) )
int x ;
void fun1 ( int i )
{
if ( i < 0 )
data = 0 ;
else
data = i ;
}
int fun2( )
{
return data ;
}
} ;
void main( )
{
sample a ;
a.x = -99 ;
cout << a.x ;
}
Here, the function fun1( ) of class sample is used to set the
given integer value into data, whereas fun2( ) returns the
current value of data. To set these functions as properties of
a class we have given the statement as shown below:
__declspec ( property ( put = fun1, get = fun2 )) int x ;
As a result, the statement a.x = -99 ; would cause fun1( ) to
get called to set the value in data. On the other hand, the
last statement would cause fun2( ) to get called to return the
value of data.
-------------------------------------------------------------------------------------------------
12.
How do I write code to make an object work like a 2-D array?
Ans: Take a look at the following program.
#include <iostream.h>
class emp
{
public :
int a[3][3] ;
emp( )
{
int c = 1 ;
for ( int i = 0 ; i <= 2 ; i++ )
{
for ( int j = 0 ; j <= 2 ; j++ )
{
a[i][j] = c ;
c++ ;
}
}
}
int* operator[] ( int i )
{
return a[i] ;
}
} ;
void main( )
{
emp e ;
cout << e[0][1] ;
}
The class emp has an overloaded operator [ ] function. It
takes one argument an integer representing an array index and
returns an int pointer. The statement cout << e[0][1] ; would
get converted into a call to the overloaded [ ] function as
e.operator[ ] ( 0 ). 0 would get collected in i. The function
would return a[i] that represents the base address of the
zeroeth row. Next the statement would get expanded as base
address of zeroeth row[1] that can be further expanded as *(
base address + 1 ). This gives us a value in zeroth row and
first column.
-------------------------------------------------------------------------------------------------
13.
What are formatting flags in ios 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 flags
Flags 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, unitbuf and stdio. The flags
that work in a group can have only one of these flags set at a
time.
-------------------------------------------------------------------------------------------------
14.
What is the purpose of ios::basefield in the following
statement?
cout.setf ( ios::hex, ios::basefield ) ;
Ans: This is an example of formatting flags that work in a
group. There is a flag for each numbering system (base) like
decimal, octal and hexadecimal. Collectively, these flags are
referred to as basefield and are specified by ios::basefield
flag. We can have only one of these flags on at a time. If we
set the hex flag as setf ( ios::hex ) then we will set the hex
bit but we won't clear the dec bit resulting in undefined
behavior. The solution is to call setf( ) as setf ( ios::hex,
ios::basefield ). This call first clears all the bits and then
sets the hex bit.
-------------------------------------------------------------------------------------------------
15.
Can we get the value of ios format flags?
Ans: Yes! The ios::flags( ) member function gives the value
format flags. This function takes no arguments and returns a
long ( typedefed to fmtflags) that contains the current format
flags.
-------------------------------------------------------------------------------------------------
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: This is shown in following program:
#include <iostream.h>
class date
{
private :
int day ;
int month ;
int year ;
public :
date ( int d = 0, int m = 0, int y = 0 )
{
day = d ;
month = m ;
year = y ;
}
// copy constructor
date ( date &d )
{
day = d.day ;
month = d.month ;
year = d.year ;
}
// an overloaded assignment operator
date operator = ( date d )
{
day = d.day ;
month = d.month ;
year = d.year ;
return d ;
}
void display( )
{
cout << day << "/" << month << "/" << year ;
}
} ;
void main( )
{
date d1 ( 25, 9, 1979 ) ;
date d2 = d1 ;
date d3 ;
d3 = d2 ;
d3.display( ) ;
}
-------------------------------------------------------------------------------------------------
18.
When should I use unitbuf flag?
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 dont.
-------------------------------------------------------------------------------------------------
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?
Ans: To understand this consider following statements,
char str[5] ;
cin >> str ;
While entering the value for str if we enter more than 5
characters then there is no provision in cin to check the
array bounds. If the array overflows, it may be dangerous.
This can be avoided by using get( ) function. For example,
consider following statement,
cin.get ( str, 5 ) ;
On executing this statement if we enter more than 5
characters, then get( ) takes only first five characters and
ignores rest of the characters. Some more variations of get( )
are available, such as shown below:
get ( ch ) Extracts one character only
get ( str, n ) Extracts up to n characters into str
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.
-------------------------------------------------------------------------------------------------