C++ INTERVIEW QUESTIONS

PREVIOUS

 OTHER INTERVIEW QUESTIONS

Q: Should I use NULL or 0?A: In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid
macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe
that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes
defined to something unsuitable and therefore had/has to be avoided. That's less common these
days.

Q: Can inline functions have a recursion? A: No. Syntax wise it is allowed. But then the function is no longer Inline. As the compiler will
never know how deep the recursion is at compilation time.

Q: Explain the scope resolution operator? A: It permits a program to reference an identifier in the global scope that has been hidden by
another identifier with the same name in the local scope.

Q: Write a function to display an integer in a binary format. A: void displayBits( unsigned value )
{
const int SHIFT = 8 * sizeof( unsigned ) - 1;
const unsigned MASK = 1<< SHIFT;
cout << setw(10 ) << value << " = ";
for ( unsigned i = 1; i <= SHIFT + 1; i++ )
{
cout << ( value & MASK ? '1' : '0' );
value <<= 1;
if ( i % 8 == 0 ) // output a space after bits
cout << ' ';
}
cout << endl;
}
You can do the same using divide by 2, until the number is greator than 0. But you will have to
use stack to print it in reverse order.

Q: How many ways are there to initialize an int with a constant?A: (a) int foo = 123;
(b) int bar(123);

Q: What is your reaction to this line of code?delete this;
A: It is not a good programming Practice. A good programmer will insist that you should
absolutely never use the statement if the class is to be used by other programmers an instantiated
as static, extern, or automatic objects. That much should be obvious. The code has two built-in
pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the
program will probably crash as soon as the delete statement executes. There is no portable way
for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is
properly instantiated. Second, when an object commits suicide this way, the using program might
not know about its demise. As far as the instantiating program is concerned, the object remains in
scope and continues to exist even though the  object did itself in. Subsequent dereferencing of
the caller can and usually does lead to disaster. I think that the language rules should disallow the
idiom, but that's another matter.

Q: What are the debugging methods you use when came across a problem? A: Debugging with tools like :
(a) GDB, DBG, Forte, Visual Studio.
(b) Analyzing the Core dump.
(c) Using tusc to trace the last system call before crash.
(d) Putting Debug statements in the program source code.

Q: How the compiler arranges the various sections in the executable image? A: The executable had following sections:
(a) Data Section (uninitialized data variable section, initialized data variable section )
(b) Code Section
(c) Remember that all static variables are allocated in the initialized variable section.

Q: Can you think of a situation where your program would crash without reaching the breakball,which you set at the beginning of main()?
A: C++ allows for dynamic initialization of global variables before main() is invoked. It is
possible that initialization of global will invoke some function. If this function crashes the
rash will occur before main() is entered.

Q: Why do C++ compilers need name mangling?A: Name mangling is the rule according to which C++ changes function's name into function
signature before passing that function to a linker. This is how the linker differentiates between
different functions with the same name.

Q: What is difference between template and macro?A: In C++ there is a major difference between a template and a macro. A
macro is merely a string that the compiler replaces with the value that was defined.
E.g. #define STRING_TO_BE_REPLACED "ValueToReplaceWith"
A template is a way to make functions independent of data-types. This cannot be accomplished
using macros.
E.g. a sorting function doesn't have to care whether it's sorting integers or letters since the same
algorithm might apply anyway.

Q: What are C++ storage classes? A:
auto: the default. Variables are automatically created and initialized when they are defined and
are destroyed at the end of the block containing their definition. They are not visible
outside that block.
register: a type of auto variable. a suggestion to the compiler to use a CPU register for
performance.
static: a variable that is known only in the function that contains its definition but is never
destroyed and retains its value between calls to that function. It exists from the time the
program begins execution.
extern: a static variable whose definition and placement is determined when all object and library
modules are combined (linked) to form the executable code file. It can be visible outside
the file where it is defined.

Q: What are storage qualifiers in C++ ?A: They are:
Const: Indicates that memory once initialized, should not be altered by a program.
Volatile: Indicates that the value in the memory location can be altered even though nothing
in the program code modifies the contents. for example if you have a pointer to hardware
location that contains the time, where hardware changes the value of this pointer variable
and not the program. The intent of this keyword to improve the optimization ability of the
compiler.
Mutable: Iindicates that particular member of a structure or class can be altered even if a
particular structure variable, class, or class member function is constant.
struct data
{
char name[80];
mutable double salary;
}
const data MyStruct = { "Satish Shetty", 1000 };
//initlized by complier
strcpy ( MyStruct.name, "Shilpa Shetty"); // compiler
error
MyStruct.salaray = 2000 ; // complier is happy
allowed

Q: What is reference ??A: reference is a name that acts as an alias, or alternative name, for a previously defined variable
or an object. prepending variable with "&" symbol makes it as reference.
for example:
int a;
int &b = a;

Q: What is passing by reference?A: Method of passing arguments to a function which takes parameter of type reference.
for example:
void swap( int & x, int &amp;amp;amp;amp; y )
{
int temp = x;
x = y;
y = temp;
}
int a=2, b=3;
swap( a, b );
Basically, inside the function there won't be any copy of the arguments "x" and "y" instead they
refer to original variables a and b. so no extra memory needed to pass arguments and it is more
efficient.

Q: When do use "const" reference arguments in function?A:
a) Using const protects you against programming errors that inadvertently alter data.
b) Using const allows function to process both const and non-const actual arguments, while a
function without const in the prototype can only accept non constant arguments.
c) Using a const reference allows the function to generate and use a temporary variable
appropriately.

Q: When are temporary variables created by C++ compiler?A: Provided that function parameter is a "const reference", compiler generates temporary
variable
in following2 ways.
a) The actual argument is the correct type, but it
isn't Lvalue
double Cube(const double & num)
{
num = num * num * num;
return num;
}
double temp = 2.0;
double value = cube(3.0 + temp); // argument is a expression and not a Lvalue;
b) The actual argument is of the wrong type, but of a type that can be converted to the correct
type
long temp = 3L;
double value = cuberoot ( temp); // long to double conversion

Q: What problem does the namespace feature solve?A: Multiple providers of libraries might use common global identifiers causing a name collision
when an application tries to link with two or more such libraries. The namespace feature
surrounds a library's external declarations with a unique namespace that eliminates the potential
for those collisions.
namespace [identifier] { namespace-body }
A namespace declaration identifies and assigns a name to a declarative region.
The identifier in a namespace declaration must be unique in the declarative region in which it is
used. The identifier is the name of the namespace and is used to reference its members.

Q: What is the use of 'using' declaration?A: A using declaration makes it possible to use a name from a namespace without the scope
operator.

Q: What is an Iterator class?A: A class that is used to traverse through the objects maintained by a container class. There are
_ve categories of iterators: input iterators, output iterators, forward iterators, bidirectional
iterators, random access. An iterator is an entity that gives access to the contents of a container
object without violating encapsulation constraints. Access to the contents is granted on a one-ata-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary
order (as in array indices) or according to some ordering relation (as in an ordered binary tree).
The iterator is a construct, which provides an interface that, when called, yields either the next
element in the container, or some value denoting the fact that there are no more elements to
examine. Iterators hide the details of access to and update of the elements of a container class.
Something like a pointer.

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

Q: Implementation of string length using pointer hopping A: #include
// Test to see if pointer hopping is worthwhile.
// strlen implemented with usual indexing mechanism.
int strlen1( const char str[ ] )
{
int i;
for( i = 0; str[ i ] != '\0'; i++ )
;
return i;
}
// strlen implemented with pointer hopping.
int strlen2( const char *str )
{
const char *sp = str;
while( *sp++ != '\0' )
;
return sp - str - 1;
}
// Quick and dirty main
int main( )
{
char str[ 512 ];
cout << "Enter strings; use EOF-marker to terminate: " << endl;
while( cin >> str )
{
if( strlen1( str ) != strlen2( str ) )
cerr << "Oops!!!" << endl;
}
return 0;
}

Q: What is inline function?A: The inline keyword tells the compiler to substitute the code within the function de_nition for
every instance of a function call. However, substitution occurs only at the compiler's discretion.
For example, the compiler does not inline a function if its address is taken or if it is too large to
inline.

Q: What is name mangling in C++??A: The process of encoding the parameter types with the function/method name into a unique
name is called name mangling. The inverse process is called demangling.
For example Foo::bar(int, long) const is mangled as 'bar__C3Fooil'.
For a constructor, the method name is left out.
That is Foo::Foo(int, long) const is mangled as ‘C3Fooil’

Q: Can you think of a situation where your program would crash without reaching thebreakpoint which you set at the beginning of main()?
A: C++ allows for dynamic initialization of global variables before main() is invoked. It is
possible that initialization of global will invoke some function. If this function crashes the crash
will occur before main() is entered. Name two cases where you MUST use initialization
list as opposed to assignment in constructors. Both non-static const data members and reference
data members cannot be assigned values; instead, you should use initialization list to initialize
them.

Q: What does it mean to declare a...(a) member function as virtual?
(b) member variable as static?
(c) function as static?
(d) destructor as static?
A:
(a)  C++ virtual function is a member function of a class, whose functionality can be overridden in its derived classes. The whole function body can be replaced with a new set of
implementation in the derived class. The concept of c++ virtual functions is different
from C++ Function overloading. The difference between a non-virtual c++ member
function and a virtual member function is, the non-virtual member functions are resolved
at compile time. This mechanism is called static binding. Where as the c++ virtual
member functions are resolved during run-time. This mechanism is known as dynamic
binding.
(b)  The static keyword allows a variable to maintain its value among different function calls.
If the value of a static variable changes when the variable has been accessed, the variable
keeps the new value. If the same variable gets accessed again, it would be holding its
most recent value. This is possible because, when the static variable is declared, the
compiler uses a separate memory area to store it. By doing this, when the value of the
static variable gets changed, it is updated in the memory it is occupying. And because this
memory is separate, the compiler can monitor its values even when its function exits.
(c)  A static member function can access only static member data, static member functions
and data and functions outside the class. A static member function can be called, even
when a class is not instantiated. A static member function cannot be declared virtual. A
static member function cannot have access to the 'this' pointer of the class.
(d)  a "static destructor" is a static member function of the class that accepts one argument - a
pointer to the object of that class to be destroyed. It is probably used along with "a
factory method", when there is a need to restrict the creation of instances of some class
to free store only and/or perform additional steps before or after creation of an object.
Similar steps may need to be taken before and/or after destroying an instance.

Q: What is faster ++i or i++, where i is an interger variable? A: The answer to this lies in the fact, how they used. With ++i(PreIncrement) the variable is
incremented and new value is returned. So it requires one instruction to increment the variable.
In case of i++(post Increment), the old value has to be returned or used in the expression and
then the variable is incrememented after the expression is evaluated. Since you need one
instruction to save the old value to be used in the expression and other instruction to increment
the variable, its comparatively slower.

Q: Find the size of an interger data type with out using sizeof() function? A: #include
int main()
{
int *i ;
int *j = i + 1;
cout << " size of an integer variable i = " << (int)j - (int)i << endl;
}

Q: How can I make it so keys pressed by users are not echoed on the screen?
A: This is not a standard C++ feature. C++ doesn't even require your system to have a keyboard
or a screen. That means every operating system and vendor does it somewhat differently.
Please read the documentation that came with your compiler for details on your particular
installation.

Q: Why can't I open a file in a different directory such as "..\test.dat"?A: Because " " is a tab character.
You should use forward slashes in your filenames, even on operating systems that use
backslashes (DOS, Windows, OS/2, etc.). For example:
#include
#include
int main()
{
#if 1
std::ifstream file("../test.dat"); // RIGHT!
#else
std::ifstream file(".. est.dat"); // WRONG!
#endif
...
}
Remember, the backslash ("\") is used in string literals to create special characters: "\n" is a
newline, "\b" is a backspace, and " " is a tab, "\a" is an "alert", "\v" is a vertical-tab, etc.
Therefore the file name "\version\next\alpha\beta est.dat" is interpreted as a bunch of very funny
characters. To be safe, use "/version/next/alpha/beta/test.dat" instead, even on systems that use a
"\" as the directory separator. This is because the library routines on these operating systems
handle "/" and "\" interchangeably.
Of course you could use "\\version\\next\\alpha\\beta\ est.dat", but that might hurt you (there's a
non-zero chance you'll forget one of the "\"s, a rather subtle bug since most people don't notice
it) and it can't help you (there's no benefit for using "\\" over "/"). Besides "/" is more portable
since it works on all flavors of Unix, Plan 9, Inferno, all Windows, OS/2, etc., but "\\" works
only on a subset of that list. So "\\" costs you something and gains you nothing: use "/" instead.
Q: How can I open a stream in binary mode?
A: Use std::ios::binary.
Some operating systems differentiate between text and binary modes. In text mode, end-of-line
sequences and possibly other things are translated; in binary mode, they are not. For example, in
text mode under Windows, "\r\n" is translated into "\n" on input, and the reverse on output.
To read a file in binary mode, use something like this:
#include
#include
#include
void readBinaryFile(const std::string& filename)
{
std::ifstream input(filename.c_str(), std::ios::in |  std::ios::binary);
char c;
while (input.get(c)) {
...do something with c here...
}
}
Note: input >> c discards leading whitespace, so you won't normally use that when reading
binary files.

Q: How can I "reopen" std::cin and std::cout in binary mode?A: This is implementation dependent. Check with your compiler's documentation.
For example, suppose you want to do binary I/O using std::cin and std::cout.
Unfortunately there is no standard way to cause std::cin, std::cout, and/or std::cerr to be opened
in binary mode. Closing the streams and attempting to reopen them in binary mode might have
unexpected or undesirable results.
On systems where it makes a difference, the implementation might provide a way to make them
binary streams, but you would have to check the implementation specifics to find out.

PREVIOUS

1 comment:

  1. Greetings Mate,


    I’ve often thought about this C++ INTERVIEW QUESTIONS. Nice to have it laid out so clearly. Great eye opener.

    How can milli second / micro second / nano second be used in gcc platform? What is the process, syntax?

    It was cool to see your article pop up in my google search for the process yesterday. Great Guide.

    Keep up the good work!


    Ciao,
    Hansy

    ReplyDelete