C, C++ Interview Questions

Q : What is a heap ?
Ans : Heap is a chunk of memory. When in a program memory is allocated dynamically, the C run-time library gets the memory from a collection of unused memory called the heap. The heap resides in a program's data segment. Therefore, the amount of heap space available to the program is fixed, and can vary from one program to another.

Q : How to obtain a path of the given file?
Ans: The function searchpath( ) searches for the specified file in the subdirectories of the current path. Following program shows how to make use of the searchpath( ) function.

#include "dir.h"

void main ( int argc, char *argv[] )
{
char *path ;
if ( path = searchpath ( argv[ 1 ] ) )
printf ( "Pathname : %s\n", path ) ;
else
printf ( "File not found\n" ) ;
}

Q : Can we get the process identification number of the current program?
Ans: Yes! The macro getpid( ) gives us the process identification number of the program currently running. The process id. uniquely identifies a program. Under DOS, the getpid( ) returns the Program Segment Prefix as the process id. Following program illustrates the use of this macro.
#include
#include

void main( )
{
printf ( "The process identification number of this program is %X\n",
getpid( ) ) ;
}

Q : How do I write a function that takes variable number of arguments?
Ans: The following program demonstrates this.

#include
#include

void main( )
{
int i = 10 ;
float f = 2.5 ;
char *str = "Hello!" ;
vfpf ( "%d %f %s\n", i, f, str ) ;
vfpf ( "%s %s", str, "Hi!" ) ;
}

void vfpf ( char *fmt, ... )
{
va_list argptr ;
va_start ( argptr, fmt ) ;
vfprintf ( stdout, fmt, argptr ) ;
va_end ( argptr ) ;
}

Here, the function vfpf( ) has called vfprintf( ) that take variable argument lists. va_list is an array that holds information required for the macros va_start and va_end. The macros va_start and va_end provide a portable way to access the variable argument lists. va_start would set up a pointer argptr to point to the first of the variable arguments being passed to the function. The macro va_end helps the called function to perform a normal return.

Q : Can we change the system date to some other date?
Ans: Yes, We can! The function stime( ) sets the system date to the specified date. It also sets the system time. The time and date is measured in seconds from the 00:00:00 GMT, January 1, 1970. The following program shows how to use this function.
#include
#include

void main( )
{
time_t tm ;
int d ;

tm = time ( NULL ) ;

printf ( "The System Date : %s", ctime ( &tm ) ) ;
printf ( "\nHow many days ahead you want to set the date : " ) ;
scanf ( "%d", &d ) ;

tm += ( 24L * d ) * 60L * 60L ;

stime ( &tm ) ;
printf ( "\nNow the new date is : %s", ctime ( &tm ) ) ;
}
In this program we have used function ctime( ) in addition to function stime( ). The ctime( ) function converts time value to a 26-character long string that contains date and time.

Q : How to use function strdup( ) in a program?
Ans : The string function strdup( ) copies the given string to a new location. The function uses malloc( ) function to allocate space required for the duplicated string. It takes one argument a pointer to the string to be duplicated. The total number of characters present in the given string plus one bytes get allocated for the new string. As this function uses malloc( ) to allocate memory, it is the programmer’s responsibility to deallocate the memory using free( ).
#include
#include
#include

void main( )
{
char *str1, *str2 = "double";

str1 = strdup ( str2 ) ;
printf ( "%s\n", str1 ) ;
free ( str1 ) ;
}

Q : On including a file twice I get errors reporting redefinition of function.
How can I avoid duplicate inclusion?
Ans: Redefinition errors can be avoided by using the following macro definition. Include this definition in the header file.
#if !defined filename_h
#define filename_h
/* function definitions */
#endif
Replace filename_h with the actual header file name. For example, if name of file to be included is 'goto.h' then replace filename_h

Q : How to write a swap( ) function which swaps the values of the variables using bitwise operators.

Ans: Here is the swap( ) function.
swap ( int *x, int *y )
{
*x ^= *y ;
*y ^= *x ;
*x ^= *y ;
}
The swap( ) function uses the bitwise XOR operator and does not require any temporary variable for swapping.

C++ Interview Questions

Q. Name some pure object oriented languages.
Answer:

 Smalltalk,
 Java,
 Eiffel,
 Sather.

Q. Name the operators that cannot be overloaded.
Answer:
sizeof . .* .-> :: ?:

Q. What is a node class?
Answer:

A node class is a class that,
 relies on the base class for services and implementation,
 provides a wider interface to te users than its base class,
 relies primarily on virtual functions in its public interface
 depends on all its direct and indirect base class
 can be understood only in the context of the base class
 can be used as base for further derivation
 can be used to create objects.
A node class is a class that has added new services or functionality beyond the services inherited from its base class.

Q. What is an orthogonal base class?
Answer: If two base classes have no overlapping methods or data they are said to be independent of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in different dimensions and do not interfere with each other in any way. The same derived class may inherit such classes with no difficulty.

Q. What is a container class? What are the types of container classes?
Answer: A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.

Q. What is a protocol class?
Answer: An abstract class is a protocol class if:

 it neither contains nor inherits from classes that contain member data, non-virtual functions, or private (or protected) members of any kind.
 it has a non-inline virtual destructor defined with an empty implementation,
 all member functions other than the destructor including inherited functions, are declared pure virtual functions and left undefined.

Q. What is a mixin class?
Answer: A class that provides some but not all of the implementation for a virtual base class is often called mixin. Derivation done just for the purpose of redefining the virtual functions in the base classes is often called mixin inheritance. Mixin classes typically don't share common bases.

Q. What is a concrete class?
Answer: A concrete class is used to define a useful object that can be instantiated as an automatic variable on the program stack. The implementation of a concrete class is defined. The concrete class is not intended to be a base class and no attempt to minimize dependency on other classes in the implementation or behavior of the class.

Q.What is the handle class?
Answer: A handle is a class that maintains a pointer to an object that is programmatically accessible through the public interface of the handle class.

Explanation:

In case of abstract classes, unless one manipulates the objects of these classes through pointers and references, the benefits of the virtual functions are lost. User code may become dependent on details of implementation classes because an abstract type cannot be allocated statistically or on the stack without its size being known. Using pointers or references implies that the burden of memory management falls on the user. Another limitation of abstract class object is of fixed size. Classes however are used to represent concepts that require varying amounts of storage to implement them.

A popular technique for dealing with these issues is to separate what is used as a single object in two parts: a handle providing the user interface and a representation holding all or most of the object's state. The connection between the handle and the representation is typically a pointer in the handle. Often, handles have a bit more data than the simple representation pointer, but not much more. Hence the layout of the handle is typically stable, even when the representation changes and also that handles are small enough to move around relatively freely so that the user needn’t use the pointers and the references.

Q. What is an action class?
Answer: The simplest and most obvious way to specify an action in C++ is to write a function. However, if the action has to be delayed, has to be transmitted 'elsewhere' before being performed, requires its own data, has to be combined with other actions, etc then it often becomes attractive to provide the action in the form of a class that can execute the desired action and provide other services as well. Manipulators used with iostreams is an obvious example.

Explanation:
A common form of action class is a simple class containing just one virtual function.
class Action
{
public:
virtual int do_it( int )=0;
virtual ~Action( );
}
Given this, we can write code say a member that can store actions for later execution without using pointers to functions, without knowing anything about the objects involved, and without even knowing the name of the operation it invokes. For example:
class write_file : public Action
{
File& f;
public:
int do_it(int)
{
return fwrite( ).suceed( );
}
};
class error_message: public Action
{
response_box db(message.cstr( ),"Continue","Cancel","Retry");
switch (db.getresponse( ))
{
case 0: return 0;
case 1: abort();
case 2: current_operation.redo( );return 1;
}
};

A user of the Action class will be completely isolated from any knowledge of derived classes such as write_file and error_message.

C++ Interview Questions

Q. Name some pure object oriented languages.
Answer:

 Smalltalk,
 Java,
 Eiffel,
 Sather.

Q. Name the operators that cannot be overloaded.
Answer:
sizeof . .* .-> :: ?:

Q. What is a node class?
Answer:

A node class is a class that,
 relies on the base class for services and implementation,
 provides a wider interface to te users than its base class,
 relies primarily on virtual functions in its public interface
 depends on all its direct and indirect base class
 can be understood only in the context of the base class
 can be used as base for further derivation
 can be used to create objects.
A node class is a class that has added new services or functionality beyond the services inherited from its base class.

Q. What is an orthogonal base class?
Answer: If two base classes have no overlapping methods or data they are said to be independent of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in different dimensions and do not interfere with each other in any way. The same derived class may inherit such classes with no difficulty.

Q. What is a container class? What are the types of container classes?
Answer: A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.

Q. What is a protocol class?
Answer: An abstract class is a protocol class if:

 it neither contains nor inherits from classes that contain member data, non-virtual functions, or private (or protected) members of any kind.
 it has a non-inline virtual destructor defined with an empty implementation,
 all member functions other than the destructor including inherited functions, are declared pure virtual functions and left undefined.

Q. What is a mixin class?
Answer: A class that provides some but not all of the implementation for a virtual base class is often called mixin. Derivation done just for the purpose of redefining the virtual functions in the base classes is often called mixin inheritance. Mixin classes typically don't share common bases.

Q. What is a concrete class?
Answer: A concrete class is used to define a useful object that can be instantiated as an automatic variable on the program stack. The implementation of a concrete class is defined. The concrete class is not intended to be a base class and no attempt to minimize dependency on other classes in the implementation or behavior of the class.

Q.What is the handle class?
Answer: A handle is a class that maintains a pointer to an object that is programmatically accessible through the public interface of the handle class.

Explanation:

In case of abstract classes, unless one manipulates the objects of these classes through pointers and references, the benefits of the virtual functions are lost. User code may become dependent on details of implementation classes because an abstract type cannot be allocated statistically or on the stack without its size being known. Using pointers or references implies that the burden of memory management falls on the user. Another limitation of abstract class object is of fixed size. Classes however are used to represent concepts that require varying amounts of storage to implement them.

A popular technique for dealing with these issues is to separate what is used as a single object in two parts: a handle providing the user interface and a representation holding all or most of the object's state. The connection between the handle and the representation is typically a pointer in the handle. Often, handles have a bit more data than the simple representation pointer, but not much more. Hence the layout of the handle is typically stable, even when the representation changes and also that handles are small enough to move around relatively freely so that the user needn’t use the pointers and the references.

Q. What is an action class?
Answer: The simplest and most obvious way to specify an action in C++ is to write a function. However, if the action has to be delayed, has to be transmitted 'elsewhere' before being performed, requires its own data, has to be combined with other actions, etc then it often becomes attractive to provide the action in the form of a class that can execute the desired action and provide other services as well. Manipulators used with iostreams is an obvious example.

Explanation:
A common form of action class is a simple class containing just one virtual function.
class Action
{
public:
virtual int do_it( int )=0;
virtual ~Action( );
}
Given this, we can write code say a member that can store actions for later execution without using pointers to functions, without knowing anything about the objects involved, and without even knowing the name of the operation it invokes. For example:
class write_file : public Action
{
File& f;
public:
int do_it(int)
{
return fwrite( ).suceed( );
}
};
class error_message: public Action
{
response_box db(message.cstr( ),"Continue","Cancel","Retry");
switch (db.getresponse( ))
{
case 0: return 0;
case 1: abort();
case 2: current_operation.redo( );return 1;
}
};

A user of the Action class will be completely isolated from any knowledge of derived classes such as write_file and error_message.

C++ Interview Questions

Q. What is an incomplete type?
Answer: Incomplete types refers to pointers in which there is non availability of the implementation of the referenced location or it points to some location whose value is not available for modification.
Example:
int *i=0x400 // i points to address 400
*i=0; //set the value of memory location pointed by i.
Incomplete types are otherwise called uninitialized pointers.

Q. What is a dangling pointer?
Answer: A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed.

Q. Differentiate between the message and method.
Answer:

Message Method
Objects communicate by sending messages Provides response to a message.
to each other.
A message is sent to invoke a method. It is an implementation of an operation.

Q. What is an adaptor class or Wrapper class?
Answer: A class that has no functionality of its own. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a non- object- oriented implementation.

Q. What is a Null object?
Answer: It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object.

Q. What is a Null object?
Answer: It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object.

Q. What is class invariant?
Answer: A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.

Q. What do you mean by Stack unwinding?
Answer: It is a process during exception handling when the destructor is called for all local objects between the place where the exception was thrown and where it is caught.

Q. Define precondition and post-condition to a member function.
Answer:

Precondition: A precondition is a condition that must be true on entry to a member function. A class is used correctly if preconditions are never false. An operation is not responsible for doing anything sensible if its precondition fails to hold.
For example, the interface invariants of stack class say nothing about pushing yet another element on a stack that is already full. We say that isful() is a precondition of the push operation.

Post-condition: A post-condition is a condition that must be true on exit from a member function if the precondition was valid on entry to that function. A class is implemented correctly if post-conditions are never false.
For example, after pushing an element on the stack, we know that isempty() must necessarily hold. This is a post-condition of the push operation.

Q. What are the conditions that have to be met for a condition to be an invariant of the class?
Answer:

 The condition should hold at the end of every constructor.
 The condition should hold at the end of every mutator(non-const) operation.

Q. What are proxy objects?
Answer:

Objects that stand for other objects are called proxy objects or surrogates.

Example:
template
class Array2D
{
public:
class Array1D
{
public:
T& operator[] (int index);
const T& operator[] (int index) const;
...
};
Array1D operator[] (int index);
const Array1D operator[] (int index) const;
...
};

The following then becomes legal:
Array2Ddata(10,20);
........