Monday, February 26, 2007

C++ Interview questions

Well, I will make it short and simple... my company decided not to give us sal. rise and so I started revising my C++ knowledge...

Went through couple of sites and came with these c++ questions (mainly www.coolinterviews.com). To help my fellow job searchers, here are some commonly asked questions in interviews of C++. None of the code nor explanation is mine. So if anyone finds any errors or has some more questions to add to this list please email me at goremaniac@goowy.com

a) How can you force instantiation of a template?

you can instantiat a template in two ways. 1. Implicit instantiation and 2. Explicit Instantion. implicit instatanitioan can be done by the following ways:

template class A {
public:
A(){}
~A(){}
void x();
void z();
};

void main() {
A ai;
A af;
}


External Instantion can be done the following way:

int main() {
template class A;
template class A;
}


b)
class A(){};

int main(){A a;}

Whether there will be a default contructor provided by the compiler in above case ?
yes, if the designer of the class donot define any constructor in the class. then the compiler provides the default constructor in the class.

c) Can we have "Virtual Constructors"?
Yes we cannot have virtual constructors. But if the need arises, we can simulate the implementation of virtural constructor by calling a Init method from the constructor which, should be a virtual function.


d) Can destructor be private?
Yes destructors can be private. But according to Standard Programming practise it is not advisable to have destructors to be private.

e) How do you write a program which produces its own source code as its output?

write this program and save it as pro.c....run....it will show the program to the consol and write the source code into data.txt file...................

#include
void main(){
FILE *fp,*ft;
char buff[100];
fp=fopen("pro.c","r");
if(fp==NULL)
{
printf("ERROR");
}
ft=fopen("data.txt","w+");
if(ft==NULL)
{
printf("ERROR");
}
while(getc(fp)!=EOF)
{
fscanf(fp,"%s",buff);
printf("%s\n",buff);
printf(ft,"%s\n",buff);
}
}




f) Why cant one make an object of abstract class? Give compiler
view of statement


we cant make object of abstract class becoz, in the vtable the vtable entry for the abstract class functions will be NULL, which ever are defined as pure virtual functions...even if there is a single pure virtual function in the class the class becomes as abstract class.. if there is a virtual function in your class the compiler automatically creates a table called virtual function table .. to store the virtual function addresses.... if the function is a pure virtual function the vtable entry for that function will be NULL.even if there is a single NULL entry in the function table the compiler does not allow to create the object.

g) What are Virtual Functions? How to implement virtual functions in "C"
Virtual functio is those function which is basically member function of a base class but define in derrived class .In base class its equal to zero.
For example:

class sum{
public:
void add()=0;
};

class sumderrived{
public:
void add() { cout<<"Sum is 10:"; }
};



h) What is virtual constructors/destructors?

Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object. There is a simple solution to this problem – declare a virtual base-class destructor. This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called.

In case of inheritance, objects should be destructed exactly the opposite way of their construction. If virtual keyword is not added before base class destructor declaration, then derived class destructor will not at all be called. Hence there will be memory leakage if allocated for derived class members while constructing the object.

Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error. Does c++ support multilevel and multiple inheritance? Yes. What are the advantages of inheritance? • It permits code reusability. • Reusability saves time in program development. • It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional. What is the difference between declaration and definition? The declaration tells the compiler that at some later point we plan to present the definition of this declaration. E.g.: void stars () //function declaration The definition contains the actual implementation.
E.g.:

void stars () // declarator {
for(int j=10; j>=0; j--) //function body
cout<<”*”;
}



i) Difference between "vector" and "array"?
Vector and ArrayList are very similar. Both of them represent a 'growable array', where you access to the elements in it through an index.ArrayList it's part of the Java Collection Framework, and has been added with version 1.2, while Vector it's an object that is present since the first version of the JDK. Vector, anyway, has been retrofitted to implement the List interface.The main difference is that Vector it's a synchronized object, while ArrayList it's not.While the iterator that are returned by both classes are fail-fast (they cleanly thrown a ConcurrentModificationException when the orignal object has been modified), the Enumeration returned by Vector are not.Unless you have strong reason to use a Vector, the suggestion is to use the ArrayList

j) Difference between "C structure" and "C++ structure".

They are different. C struct can only contain data while C++ struct can contain functions and access limitation such as public, private etc just as a class (not totally the same as class!)


k) What are the different types of polymorphism?

function, operator, virtual function overloading


l) What are the different types of Storage classes?

There are four types of storage class: automatic, register, external, and static


m) Explain "passing by value", "passing by pointer" and "passing by reference"

There is major difference between these three are when we want to avoid making the copy of variable and we want to change value of actual argument on calling function then we use passing by pointer, passing the reference. We can not perform arithmetic operation on reference.


n) Have you heard of "mutable" keyword?

The mutable keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function.SEE FOLLOWING CODE :- ********************************************

class Mutable{
private :
int m_iNonMutVar;
mutable int m_iMutVar;

public:
Mutable();
void TryChange() const;
};

Mutable::Mutable():m_iNonMutVar(10),m_iMutVar(20) {};

void Mutable::TryChange() const{
m_iNonMutVar = 100; // THis will give ERROR
m_iMutVar = 200; // This will WORK coz it is mutable
}





o) Is there any way to write a class such that no class
can be inherited from it.


Simple, make all constructors of the class private.


p) What is RTTI?
Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type. RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing). The need came from practical experience with C++. RTTI replaces many homegrown versions with a solid, consistent approach.
RTTI as known Runtime Type Identification. If you want to cast the object of one class as the object of another class so u require to know the type of the object at the runtime and u may want to cofirm is tht object of the same class you want to change we use the typeid operator to check what is the objects type and then use dynamic cast to cast the object.

q) Can you explain the term "resource acquisition is initialization?"
Resource Acquisition is Initialisation or shortly RAII is a term closely connected with exception handling and automatic garbage collection(speaking loosely). RAII is defined as the technique of performing all necessary resource initialisation work right within the body of the constructor itself, and correspondingly doing all the deallocation within the destructor. Since during exception handling destructors of all the classes whose constructors have been successfully invoked, are called therefore all the local objects previously allocated are automatically deallocated without explicitly calling their destructors.the following example explains the RAII technique:

class X{
int *r;

public:
X(){cout<<"X is created"; r=new int[10]; }
~X(){cout<<"X is destroyed"; delete [] r; }

};


class Y{
public:
Y(){ X x; throw 44; }
~Y(){cout<<"Y is destroyed";}
};



Now since Y throws an exception right in its constructor therefore its
destructor won't get called becuse the constructor was not invoked successfully. But the destructor of the class X will definitely be called and therefore the array 'r' will be deallocated. So we didn't have to care about resource deallocation at the time exceptions are raised.


r) What is the difference between "overloading" and "overriding"?

Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.

1. Overload - two functions that appear in the same scope are overloaded if they have the same name but have different parameter list
2. main() cannot be overloaded
3. notational convenience - compiler invokes the functions that is the best match on the args – found by finding the best match between the type of arg expr and parameter
4. if declare a function locally, that function hides rather than overload the same function declared in an outer scope
5. Overriding - the ability of the inherited class rewriting the virtual method of a base class - a method which completely replaces base class FUNCTIONALITY in subclass
6. the overriding method in the subclass must have exactly the same signature as the function of the base class it is replacing - replacement of a method in a child class
7. writing a different body in a derived class for a function defined in a base class, ONLY if the function in the base class is virtual and ONLY if the function in the derived class has the same signature
8. all functions in the derived class hide the base class functions with the same name except in the case of a virtual functions which override the base class functions with the same signature


s) What happens to the member pointers when an exception occures in constructor, while allocating memory ? how can we over come this ?

Offcourse it will result memory leak.... so use auto_ptr for such thing .. see following example, i have used two types to avoid memory leaks one is auto_ptr and another is initialize function

#include
#include

class DataClass{
public:
int m_iValue;
DataClass(int i =0):m_iValue(i){}

void show(void) {
// Because of the moronic html of the blogger, i am not able to show std::cout
// statements, that's why i have converted them to printf's for now
printf ("Value :- %d \n",m_iValue);
}
};

class ResourceLeakFreeClass{
public:
std::auto_ptr m_Data1;
DataClass * m_Data2;ResourceLeakFreeClass():m_Data1(new DataClass(100)),
m_Data2(InitDataClass(200)){}

~ResourceLeakFreeClass(){
if(m_Data2){
delete m_Data2;
m_Data2 = 0; }
}

DataClass * InitDataClass(int iData) {
try{
return new DataClass(iData);
}
catch (...) {
delete m_Data2;throw;
}
}
};

int main(int argc, char* argv[]) {
ResourceLeakFreeClass RLFC;
RLFC.m_Data1->show();
RLFC.m_Data2->show();
return 0;
}



t) Can we take "main function" as of type float,char etc?

Its possible only with int.If a function is declared as void that it may return anything by default.


u) what are auto static variables and auto extern variables?

In theory these are called storage classes. These will define the scope and life time of variables or functions.There are mainly 4 of them:auto is the default storage class for local variables. register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size say a word.static can also be defined within a function or as a global variable. If this is done, the variable is initialized at compilation time and retains its value between calls ie, inside the function. Because it is initialed at compilation time, the initialization value must be a constant. This is serious stuff - tread with care. extern defines a variable as global one ie, that is visable to all files irrespective of where it is defined. When you use 'extern' the variable cannot be initalized as all it does is point the variable name at a storage location that has been previously defined.


v) What will happen if I say delete this

if you say "delete this", you are effectively calling the destructor twice, which could well be a disaster if your class uses heap. The destructor will be called when you say " delete this " and again when that object goes out of scope. Since this is the language behavior, there is no way to prevent the destructor from being called twice. Please refrain from forcibly calling a destructor or using clause like this. For more information, visit the following link: http://www.parashift.com/c++-faq-lite/dtors.html

destructor executed, but memory will not be freed (other than work done by destructor). If we have class Test and method Destroy { delete this } the destructor for Test will execute, if we have Test *var = new Test()
1. pointer var will still be valid
2. object created by new exists until explicitly destroyed by delete
3. space it occupied can be reused by new
4. delete may only be applied to a pointer by new or zero, applying delete to zero = no FX
5. delete = delete objects
6. delete[] – delete array
7. delete operator destroys the object created with new by deallocating the memory assoc. with the object
8. if a destructor has been defined fir a class delete invokes that desructor


w) We can overload assignment operator as a normal function. But we can not overload assignment operator as friend function why?

If the operation modifies the state of the class object, it operates on, it must be a member function, not a friend function. Thus all operator such as =, *=, +=, etc are naturally defined as member functions not friend functions. Conversely, if the operator does not modify any of its operands, but needs only a representation of the object, it does not have to be a member function and often less confusing. This is the reason why binary operators are often implemented as friend functions such as + , *, -, etc..


x) What do you mean by binding of data and functions?

Encapsulation


y) Difference between a "assignment operator" and a "copy constructor"

Copy constructor is called every time a copy of an object is made. When you pass an object by value, either into a function or as a function's return value, a temporary copy of that object is made. Assignment operator is called whenever you assign to an object. Assignment operator must check to see if the right-hand side of the assignment operator is the object itself. It executes only the two sides are not equal

1. constructor with only one parameter of its same type that assigns to every nonstatic class member variable of the object a copy of the passed object
2. copy assignment operator must correctly deal with a well constructed object - but copy constructor initializes uninitialized memory
3. copy constructor takes care of initialization by an object of the same type x
4. for a class for which the copy assignment and copy constructor not explicitly declared missing operation will be generated by the compiler. Copy operations are not inherited - copy of a class object is a copy of each member
5. memberwise assignment: each member of the right hand object is assigned to the corresponding member of the left hand object
6. if a class needs a copy constructor it will also need an assignment operator
7. copy constructor creates a new object, assignment operator has to deal w/ existing data in the object
8. assignment is like deconstruction followed by construction
9. assignment operator assigns a value to a already existing object
10. copy constructor creates a new object by copying an existing one
11. copy constructor initializes a freshly created object using data from an existing one. It must allocate memory if necessary then copy the data
12. the assignment operator makes an already existing object into a copy of an existing one.
13. copy constructor always creates a new object, assignment never does


z) What are the things contains in .obj file ? ( compiled result of .cpp file )

C++ .obj file holds code and data suitable for linking with other object files to create an executable or a shared object file.


a1) What is importance of const. pointer in copy constructor?

Because otherwise you will pass the object to copy as an argument of copy constructor as pass by value which by definition creates a copy and so on... an infinite call chain....


b1) What is the Basic nature of "cin" and "cout" and what concept or principle we are using on those two?

Basically "cin and cout" are INSTANCES of istream and ostream classes respectively.And the concept which is used on cin and cout is operator overloading. Extraction and Insertion operators are overloaded for input and ouput operations.


c1) What is abstraction?
Abstraction is of the process of hiding unwanted details from the user.


d1) What is the difference between macro and inline()?

1. Inline follows strict parameter type checking, macros do not.
2. treated like macro definitions by C++ compiler
3. meant to be used if there’s a need to repetitively execute a small block if code which is smaller
4. always evaluates every argument once
5. defined in header file
6. avoids function call overload because calling a function is slower than evaluating the equivalent expression
7. it’s a request to the compiler, the compiler can ignore the request
2. Macros are always expanded by preprocessor, whereas compiler may or may not replace the inline definitions.


e1) what is the use of volatile keyword? Give me one example?

(P876 from textbook C++ How To Program:)The volatile type qualifier is applied to a definition of a variable that may be altered from outside the program (i.e., the variable is not completely under the control of the program). Thus, the compiler cannot perform optimizations (such as speeding program execution or reducing memory consumption, for example) that depend on "knowing a variable's behavior is influenced only by program activities the compiler can observe."(notes:)1) volatile indicate the object is modified by something not directly under the compiler's control (i.e., the hardware itself)2) one use of volatile qualifier is to provide access to memory locations used by asynchronous processes such as interrupt handlers.3) Another example might be the global variables that keeps track of the total number of timer interrupts.


f1) Dynamic Binding

· delaying until runtime the selection of which function to run
· refers to the runtime choice of which virtual function to run based on the underlying type of the object to which a reference or a pointer is based
· applies only to functions declared as virtual when called thru reference or ptr
· in C++ dynamic binding happens when a virtual function is called through a reference ( ptr) to a base class. The face that ref or ptr might refer to either a base or a derived class object is the key to dynamic binding. Calls to virtual functions made thru a reference or ptr are resolved at run time: the function that is called is the one defined by the actual type of the object to which the reference or pointer refers


g1) Rule of 3

· if a class needs a destructor, it will also need an assignment operator and copy constructor
· compiler always synthesizes a destructor for us
· destroys each nonstatic member in the reverse order from that in which the object was created
· it destroys the members in reverse order from which they are declared in the class1. if someone will derive from your class2. and if someone will say new derived where derived is derived from your class3. and if someone will say delete p, where the actual objects type is derived but the pointer ps type is your class
· make destructor virtual if your class has any virtual functions



h1) Why is the pre-increment operator faster than the post-increment operator?

pre is more efficient that post because for post the object must increment itself and then return a temporary containing its old value. True for even built in types


i1) How to implement virtual functions in C

keep function pointers in function and use those function ptrs to perform the operation


j1) Find minimum and maximum of two numbers

int x; // we want to find the minimum of x and y
int y;
int r; // the result goes here
r = y + ((x - y) & -(x < y)); // min(x, y)
r = x - ((x - y) & -(x < y)); // max(x, y)


The above solution is taken from site Bit Twiddling Hacks By Sean Eron Anderson
On his site, Sean Eron Anderson has given many bit twiddling hacks for C. Do refer to the following site for it.

http://graphics.stanford.edu/~seander/bithacks.html


k1) Can you return by Reference in a function? What are advantages of References as Function Return Types ?

Yes.
Functions may return references. The formats are

Type & function_name(signature);
const Type & function_name(signature);


The compiler actually returns a pointer in both formats, but a
caller does not use pointer notation (*, ->) with the result. In the second format, const makes the compiler report errors if a caller tries to modify the result as an lvalue. Returning references from functions is important with structure types for improving performance. When you return a reference to a structure type from a function call, the compiler returns a pointer instead of a copy.

Another use of references with function returns is cascading. This technique allows you to embed function calls, as follows.

function_name(function_name(function_name(args)));


To see why references are appealing with cascading, consider following code

inline int *bump(int *p) {
++*p; // increment by one
return p; // return pointer
}

int num = 10;
cout << *bump(bump(&num)) << endl; // displays 12


We embed bump() calls in the cout statement because bump() now
returns its first argument, which is a pointer to an integer. We must, however, use & to pass the address of num in the first call to bump() and use * to dereference the return value from the second bump() call. If we forget to dereference (*), the program still compiles and runs, but displays an address (pointer to an integer) instead of the correct answer 12.

References make this simple. Here's the code.

inline int & bump(int & m) {
return ++m; // increment by one
}

int num = 10;
cout << bump(bump(num)) << endl; // displays 12


With references, the compiler supplies the pointers to pass function
arguments and return values. Embedded calls to bump(), therefore, do not require pointer notation.

For further details refer
http://www.phptr.com/articles/article.asp?p=31783&seqNum=3&rl=1

All together, refer this link to find 100 interview questions.
http://www.techinterviews.in/?p=18


Cheers
-Goremaniac !!!


Programming Ring - New Post