Sunday, 31 July 2016

C++ Interview questions and answers from Freshers to Experienced

 

C++ Interview questions

Cracking the C++ interview is not so tough. This page contains the C++ interview questions for each category.
Click on each category and respective sub-category to load the C++ interview questions.

To subscribe for latest C++ interview questions on your favorite social media visit C++ interview questions subscription

Advertisement







C++ Interview questions on Array


What is the size of the two dimensional array when some integer is added to it?
GUESS THE OUTPUT OF THE PROGRAM?
 

/*
Assume the following size 
int - 4 bytes
pointer 4 bytes
*/

#include<iostream>
int main()
{
 int b[10][10];
  
 std::cout<<sizeof(b)<<":"<<sizeof(b+1)<<std::endl;
  
 return 0;
}


400:4
Array will be decomposing to pointer at many situations. This is one of the situation here. Since we have added one integer value with array, array was decomposed to pointer in the second print, so it is returning the size of pointer instead of size of array.

Can we do an parenthesis based initialization for dynamic array?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

int main()
{
 char *s1=new char[10]('a');
 char *s2=new char[10]();
 std::cout<<s1<<":"<<s2<<std::endl;
 return 0;
}


Compilation error
parenthesized initializer in array new

Dynamic array cannot be initialized with parenthesis. So following line will give a compilation error.
char *s1=new char[10]('a');

Where as you can initialize with uniform initialization in c++11
char *s1=new char[10]{'a'};

But empty parenthesis initialization is  allowed even for dynamic array.
char *s2=new char[10]();


This is will just make all the char to 0(NULL) initially.

You could change ... = new char[10]('a'); to ... = new char[10]{'a'} and then compile using g++ -std=gnu++11, and the output is "a:".



C++ Interview questions on storage class specifier


Whether data members of the class can be initialized at declaration time?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

class ArrayNotFound
{
 public:
  static const int val=10;
};

int main()
{
 std::cout<<ArrayNotFound::val<<std::endl; 
 return 0;
}


10
Const static data members of the class can be initialized at the time of declaration. Other data members cannot be initialized during declaration of the class.

Whether const static data members of the class has to be redefined outside the class declaration as other static data members of the class?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

class ArrayNotFound
{
 public:
  static int a;
  static const int val=10;
  
};

int ArrayNotFound::a;
const int ArrayNotFound::val;

int main()
{
 std::cout<<ArrayNotFound::val<<std::endl; 
 return 0;
}


10
No. const static data members of the class no need to be declared again as other static data members of the class. Program will compile fine, without the following line,

const int ArrayNotFound::val;


But initialization of the const static data member will remain same as we declared in the class declaration.

Whether static function can be called by using the objects of the class?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

class ArrayNotFound
{
 public:
  static void callme()
  {
   std::cout<<"A"<<std::endl;
  }
};

int main()
{
 ArrayNotFound obj;
 obj.callme();
 
 return 0;
}


A
Yes, static function can be called by either by using a objects of the particular class or without objects, on the other hand non-static functions cannot be called without using objects.


C++ Interview questions on general C++ operators

Priority of comma operator between equal operator and brackets?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include <iostream>
int main()
{
   int k,m;
   k = 1, 2, 3;
   m = (1, 2, 3);
   std::cout<<k<<m<<std::endl;
   return 0;
}

13
Comma operator executes from left to right and return the right most element.

Consider the below statement
   m = (1, 2, 3);

Since brackets takes higher precedence than equal operator, first (1,2,3) will get executed. Here, it returns the 3, so m is stored with value 3.

So, why it is not happened for the below statement?
   k = 1, 2, 3;

Here equal takes the higher operator precedence than comma operator.

Look here for operator precedence table.

http://en.cppreference.com/w/cpp/language/operator_precedence
Can we place the array variable inside the array subscript operator?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>
int main()
{
 int a[]={0,1,2,3,4,5}; 
 std::cout<<a[5]<<5[a]<<std::endl;
 return 0;
}


55
Array subscript operator can be used in any of the following way,
a[5] or 5[a]

Both forms are valid syntax.

How it works?
Array subscript operator internally decomposes in to following form.
Consider a[5] in statement. Internally a[5] will be converted to a+5. Since a is a pointer adding 5 will point to 6th (Remember array starts with zero) element in the array.


Similarly 5[a] will be converted in to 5+a.

Can we use the array subscript operator for char literal without assigning in variable?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>
int main()
{
 std::cout<<5["ArrayNotFound"]<<"ArrayNotFound"[5]<<std::endl;
 return 0;
}

NN
Even though it seems to be very new think, concept behind it is very simple.
Here,

std::cout<<5["ArrayNotFound"]<<"ArrayNotFound"[5]<<std::endl;


The above statement is equal to the following one,

char *s=”ArrayNotFound”
std::cout<<5[s]<<s[5]<<std::endl;


Oh. Hope you got it. Instead of using the char pointer variable, directly used the string literal in the statement.



C++ Interview questions on Objects


What is the size of empty class?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

class ArrayNotFound
{
};

int main()
{
 ArrayNotFound b;
 std::cout<<sizeof(b)<<":"<<sizeof(ArrayNotFound)<<std::endl;
 return 0;
}


1:1
Size of the empty object is 1 even though no variable is declared inside the class. This is because when programmer takes the address of the object it should not return the invalid address. To avoid these concern compilers will allocate dummy memory of implementation defined size to the class with no data members and member functions.


C++ Interview questions on enums


What happens when we use the negative value in the enum value?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

enum NegativeEnum
{
 MinValue=-5,
 MaxValue, 
};

int main()
{
 std::cout<<"MaxValue: " <<NegativeEnum::MaxValue<<std::endl;
 return 0;
}


-4
Enum in C++ is allowed to initialize with negative values.
Now, what happens to next enum value when we initialize the enum with negative value?
Simple, it will be incremented by one.

Here MinValue value is -5, now next value MaxValue is (-5+1)=-4


C++ Interview questions on Miscellaneous Class Features


Whether public members of base class is accessible when derived one is struct and no access specifier is specified during inheritance?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>
class BaseClass
{
 public:
 int a; 
};

struct DerivedClass : BaseClass // Note here struct
{
 int b; 
};

int main()
{
 DerivedClass d;
 d.a=10;
 std::cout<<d.a<<std::endl; 
}


10
When struct is specified while deriving the base class , then all public member of  base class will be public to the derived class.
Refer Difference between class and struct in c++  for more difference between class and struct

Whether non-const function can be called by const object?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

class ArrayNotFound
{
 public:
  void callme()
  {
   std::cout<<"A"<<std::endl;
  }
};

int main()
{
 const ArrayNotFound obj;
 obj.callme();
 
 return 0;
}


Compilation error

accessing_variables_in_scope.cpp:15:13: error: passing 'const ArrayNotFound' as 'this' argument of 'void ArrayNotFound::callme()' discards qualifiers [-fpermissive]
No. Const object cannot be used to call the non-const functions.
Why it is not allowed?

It is not allowed because, non-const functions will allow to modify the members of the object, but intention of const objects is members of the object should not be modified. So it will throw an compilation error.

Can we modify the address of this pointer in member function of class?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

class ArrayNotFound
{
 public:
  char var='A';
  void callme()
  {
   const ArrayNotFound obj;
   this=&obj;
   this->var='B';
   std::cout<<var<<std::endl;
  }
};

int main()
{
  ArrayNotFound obj;
 obj.callme();
 
 return 0;
}


Compilation error
error: lvalue required as left operand of assignment
this pointer cannot be modified in the member function.
Why this pointer is not allowed to modify?
Because this is an purely prvalue. It will be replaced as address of the object during compilation phase

Can we change the object which is referred by the this pointer?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

class ArrayNotFound
{
 public:
  char var='A';
  void callme()
  {
   const ArrayNotFound obj;
   *this=obj;
   this->var='B';
   std::cout<<var<<std::endl;
  }
};

int main()
{
  ArrayNotFound obj;
 obj.callme();
 
 return 0;
}


B
Yes we can change the object which is referred by the this pointer.
How it is allowed to change. This pointer is nothing but an address of the object. As you think here object will not be modified.  Below statement calls the overloaded assignment operator for 
ArrayNotFound class.

*this=obj;




C++ Interview questions on inheritance


what is the size of the derived class when it inherits the classes which have common base class?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>


/*
Assume the following size 
int - 4 bytes
pointer 4 bytes
char 1 byte
*/


class Language
{
 char a;
};

class C : public Language
{
  
};

class CPP : public Language
{
 
};

class Program : C,CPP
{
 
};

class SpecialProgram : virtual C, CPP
{
 
};

int main()
{
 std::cout<<sizeof(Program)<<":"<<sizeof(SpecialProgram)<<std::endl;
 return 0;
}

2:8
This is called as diamond problem in OOPS concept.

sizeof(Program) returns 2 because Program inherits C and CPP, which have common base class and it is not informed to the compiler.

How to solve this problem?

By using the virtual inheritance.

Even though we used virtual inheritance why it have returned the size as 8 for SpecialProgram?

Since we used the virtual inheritance it will add one hidden virtual pointer inside the SpecialProgram class. Eventhough pointer size is 4, it returned as 8 because we have one char variable in C’s base class and size will become 5 now. Due to the structure padding size is returned as 8. One char variable in CPP’s base class will be ignored since Language is inherited as part of C’s inheritance


What happens when we miss the virtual keyword for one class in diamond problem?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>


/*
Assume the following size 
int - 4 bytes
pointer 4 bytes
char 1 byte
Structure padding 4 Bytes
*/

class m
{
 int b;
 int c;
 int d;
};

class n: virtual m{};

class o:  m{};

class x: n, o {};


int main()
{
 std::cout<<sizeof(x)<<std::endl;
 return 0;
}

28
During diamond problem, when virtual inheritance is missed for one class then virtual inheritance will not be applied properly. So size is returned as 28.
For class n, because of class m size is 4+4+4+4=16.  (3 int and 1 hidden virtual pointer)
For class o, since virtual keyword is missed, class m size is 4+4+4=12 (3 int)
Ultimately class x size is 16+12=28
When virtual keyword is used in class o then size of x will be 20.

What is size of the empty class which has diamond problem?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>


/*
Assume the following size 
int - 4 bytes
pointer 4 bytes
char 1 byte
*/

class Language{};

class C : public Language{};

class CPP : public Language{};

class Program : C,CPP{};

int main()
{
 std::cout<<sizeof(Program)<<std::endl;
 return 0;
}

2
Usually when class has no members, then size of the class will be 1. Here due to the diamond problem for Program class, size of the Program class is 2(1 byte for C class due to inheriting the Language class and 1 byte for CPP class due to inheriting the Language class). 


C++ Interview questions on constructor and destructor


Whether constructor will get called when we declare the object for non-parameterized constructor with empty paranthesis?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

class ArrayNotFound
{
 private:

 public: 
  
  ArrayNotFound(int a)
  {
   std::cout<<"A"<<std::endl; 
  } 
  
  ArrayNotFound()
  {
   std::cout<<"B"<<std::endl; 
  }  
};

int main()
{
 ArrayNotFound a(10); 
 ArrayNotFound b; 
 ArrayNotFound c(); 
 
 return 0;
}


A

B
Constructor will not be called for the following line

ArrayNotFound c();     


Actually this will not create an object c. C++ compiler will treat this like an function c which returns the ArrayNotFound as return value.


Whether data member of the class can be accessed when object is declared with empty parenthesis?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

class ArrayNotFound
{
 private:
 

 public: 
  bool learnSomethingNew;
  
  ArrayNotFound()
  {
   learnSomethingNew=true; 
  }  
};

int main()
{
 ArrayNotFound a(); 
 std::cout<<a.learnSomethingNew<<std::endl; 
 
 return 0;
}


Compilation error

error: request for member 'learnSomethingNew' in 'a', which is of non-class type 'ArrayNotFound()'
Below line will not create object a. This is equal to declaring the function a which returns 

ArrayNotFound as return value. So the member learnSomethingNew cannot be accessed since object is not created newly.


ArrayNotFound a();

Whether conversion constructor will act as a conversion operator?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

class ArrayNotFound
{

 public:
  ArrayNotFound(int a)
  {
   std::cout<<"C";   
  } 
};


int main()
{
 ArrayNotFound obj=5;
 obj = 10;
  
 return 0;
}


CC
It will not give any error even though assignment operator is not overloaded with the integer value.

Conversion constructor will act as a conversion operator.

Whether conversion constructor will acts as conversion operator when assignment operator is overloaded to its specific type?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

class ArrayNotFound
{

 public:
  ArrayNotFound(int a)
  {
   std::cout<<"A";
  }
  
  void operator=(int a)
  {
   std::cout<<"B";
  }
};


int main()
{
 ArrayNotFound obj=5;
 obj = 10;
  
 return 0;
}


AB

No, conversion constructor will not act as conversion operator when assignment operator is overloaded to its specific type


Whether copy constructor will get called when object is returned in the local function?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>


class ArrayNotFound
{

public:
 ArrayNotFound()
 {
  std::cout<<"C";   
 }
 
 ArrayNotFound(const ArrayNotFound& obj)
 {
  std::cout<<"D"; 
 }

};



ArrayNotFound callme()
{
 return ArrayNotFound();
}


int main()
{
 ArrayNotFound obj = callme();
 return 0;
}


Output depends on the compiler
GNU compilers output:
C
Here copy constructor is supposed to be called two times,
1.       While returning the object in callme function
2.       While copying the return value to obj in main function.

But here compiler hasn’t called the copy constructor for even single time. This is because of optimization done by the compiler. Explore more on copy elision technique.


C++ Interview questions on Member functions


Whether member of base class can be accessed in the derived class when base class member functions are overloaded or overrided?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>


class Language
{
 
 public:
  void callme(int a)
  {
   std::cout<<"A";
  }
};

class cpp : public Language
{
 
 public:
  void callme()
  {
   std::cout<<"B";
  }
};

int main()
{
 cpp l_c11;
 l_c11.callme(10);
 
 
 return 0;
}


test.cpp: In function 'int main()':
test.cpp:27:17: error: no matching function for call to 'cpp::callme(int)'
  l_c11.callme(10);
                 ^
test.cpp:27:17: note: candidate is:
test.cpp:18:8: note: void cpp::callme()
   void callme()
When a member function in derived class is created with same name as base class, then all the base class member function will be hidden to the derived class object.


C++ Interview questions on Function pointers


What happen when we dereference the function pointer?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>
int callme()
{
 std::cout<<"#"<<std::endl;
}
int main()
{
 int (*functionPtr)()=callme;
 (************functionPtr)();
 return 0;
}

#
Dereferencing the function pointer has no effect. It means it remains the same after dereferencing, unlike other pointers will get its value in the specified location.

How to return the function?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

int* PostInArrayNotFound(int *p)
{
 return p; 
}

int *(*broker(int*))(int* p)
{
 return PostInArrayNotFound;
}

int main()
{
 int i=40; 
 int j=10;
 
 std::cout<< *((*broker(&j))(&i)) << ":" << *broker(&j)(&i) << std::endl;  
 
 return 0;
}


40:40
Program just returns the function  pointer. Further study here FUNCTION POINTERS


C++ Interview questions on Miscellaneous Functions


What happens when variable is initialized with function which returns void?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

void callMe()
{
 std::cout<<"A"<<std::endl;
}
int main()
{
 int a=callMe();
 return 0;
}


Compilation error
error: void value not ignored as it ought to be
When a variable is initialized with function which return void, then compiler will thrown an error.



C++ Interview questions on General Standard template library (STL)


How capacity of the standard template library is incremented?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>
#include<vector>

int main()
{
 std::vector<int> a(10);
 std::cout<<a.size()<<":"<<a.capacity()<<std::endl;
 return 0;
}


10:<Implementation defined value>
Size of the vector will grow based on the implementation defined value.

Standard haven’t said about how much vector size should be incremented when it reaches the maximum capacity. It depends on the implementation, how size has to be incremented



C++ Interview questions on Template utility


Whether objects can be used to compare the two things in is_same template class?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>
#include<utility>

template<typename T1,typename T2>
class ArrayNotFound
{
 public:
 
 static void callme()
 {
  int a;
  float b;
  std::cout<<std::is_same<T1,T2>::value<<":"<<std::is_same<a,b>::value<<std::endl;
 }
};

int main()
{
 ArrayNotFound<int,int>::callme();
 
 return 0;
}


Compilation Error

error: type/value mismatch at argument 1 in template parameter list for 'template<class, class> struct std::is_same'
Only data type should be used to compare two things in is_same utility. So, why objects should not be used in the is_same utility template class.  Possible implementation of is_class can be

template<typename T1,typename T2>
class is_same
{
};
Since objects cannot be passed as template parameter, it will give compilation error.



C++ Interview questions on Macro


Difference between # and ## in macro expansion?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>
#define expand(a,b) a##b
#define singles(bs) (#bs)

int main()
{ 
 int expand(hello,world)=10;
 int object =11;
 std::cout<<helloworld<<":"<<singles(object)<<std::endl;
 return 0;
}


10:object
# will get expanded as string literal. Here singles(object) will expand as “object”.
## is used to merge two literals in macro.

Refer C++ - STRINGNIFY OPERATION IN MACRO for more information.

Whether stringnification operation will be converted to string literal?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>
#define myFunc(a,b) a##b

int main()
{ 
 std::cout<<myFunc(hello,vinoth); 
 return 0;
}


Compilation error
macro_expansions.cpp:6:20: error: 'hellovinoth' was not declared in this scope
## will merge two literal and it will convert to string. Since it is not converted to string literal it is throwing error like 'hellovinoth' was not declared in scope.

Where as, use of single # will be convert to string literals.

Whether macros used after # will expand further?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

#define inner(a,b) 10
#define outer(a) #a


int main()
{ 
 std::cout<<outer(inner(a,b))<<std::endl;
 return 0;
}

inner(a,b)
Macro which is used after # will not expand further. Unlike functions, outer macro will expand first and inner macro will expand next.

Whether macros can be defined within local scope?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

int main()
{
 #define MAX 20
 
 {
  #define MAX 30
 }
 
 std::cout<<MAX<<std::endl;  

 return 0;
}


30
#define can be declared in the local scope or global scope. But it is not similar to variable in accessing the macros.

When macro is re-defined with same name, compiler will not throw error, it will just throw a compiler warning.



C++ Interview questions on GO TO statements


Whether label which is declared in other functions can be accessed in the current function?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

void PostInArrayNotFound()
{
 goto myLabel;
}

int main()
{
 PostInArrayNotFound();
 
 myLabel:
  std::cout<<"A"<<std::endl;  
  
 return 0;
}


Compilation error

 error: label 'myLabel' used but not defined
Labels can be accessed only to its local scope as similar to accessing the normal variables and objects.

Whether labels which are declared within the inner block scope of function can be accessed by the same function?
GUESS THE OUTPUT OF THE PROGRAM?
 

#include<iostream>

int main()
{

 goto myLabel;
 
 { 
  myLabel:
  std::cout<<"A"<<std::endl;  
 }
 
 return 0;
}


A
Yes it can be accessed, whereas labels which are declared outside the function cannot be accessed from other functions.