Uncategorized

C++ programming question sets with answers

Here are 21 questions, we will be adding more soon with probable answers. This set of 21 questions on C++ would surely help students, freshers for their lab exams, IT companies written test and even in interviews.

Faculties can give these sets to their students to check their C++ proficiency too. Hope people will find it useful and will learn, share & contribute more to this community.
All the best \m/

1. What is the output of the following program?

<br />
	void main(){<br />
	char str[]&nbsp; = &quot;String continued&quot;&nbsp;<br />
	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot; at the next line&quot;;<br />
	cout &lt;&lt; str;<br />
	}<br />
	

Answer: 
String continued at the next line.
Explanation:
C++ concatenates these strings. When a new-line or white spaces separate two adjacent strings, they are concatenated to a single string. This operation is called as “stringization” operation. So str could have initialized by the single string “String continued at the next line.”.

2. Any guess for this code?

<br />
	void main(){<br />
	int a, *pa, &amp;ra;<br />
	pa = &amp;a;<br />
	ra = a;<br />
	cout &lt;&lt;&quot;a=&quot;&lt;&lt;a &lt;&lt;&quot;*pa=&quot;&lt;&lt;*pa &lt;&lt;&quot;ra&quot;&lt;&lt;ra ;<br />
	}<br />
	

Answer :
Compiler Error: 'ra', reference must be initialized
Explanation :
Pointers are different from references. One of the main differences is that the pointers can be both initialized and assigned, whereas references can only be initialized. So this code issues an error.

3. ANSI C++ introduces new style of casts (const_cast, dynamic_cast, static_cast and reinterpret_cast). For the following C style cast which of the new cast syntax should be applied?
pDerived = (Cderived *) pBase;
Answer:
   dynamic_cast.
Explanation:
dynamic_cast is used for traversing up and down in inheritance hierarchy. So it can be applied here to cast pointer type from the base class to derived class. The cast in the new syntax will look like this:
pDerived = dynamic_cast <Cderived*> (pBase);

4. Can you spot the mistake?

<br />
	const int size = 5;<br />
	void print(int *ptr){<br />
	cout&lt;&lt;ptr[0];<br />
	}<br />
	void print(int ptr[size]){<br />
	cout&lt;&lt;ptr[0];<br />
	}<br />
	void main(){<br />
	int a[size] = {1,2,3,4,5};<br />
	&nbsp; int *b = new int(size);<br />
	&nbsp; print(a);<br />
	&nbsp; print(b);<br />
	}<br />
	

Answer:
Compiler Error : function 'void print(int *)' already has a body
Explanation:
Arrays cannot be passed to functions, only pointers (for arrays, base addresses) can be passed. So the arguments int *ptr and int prt[size] have no difference as function arguments. In other words, both the functoins have the same signature and so cannot be overloaded.

5. In which of the following cases will the copy constructor of the class X be called?
X x1,Y Y!:
foo(&x1,&y2);           //function  foo already defined
X x1,x2, Y y1;
x2 = bar(x1,y1);      // function bar already defined
X x1(0.2) ,x2;x2 =x1;
X x1; X x2 =x1;
  Answer:
B, C and D
  Explanation:
In the function call foo, the address of the x1 is passed.  So there is no need for the copy constructor.  But in the other cases there is an assignment of X, which calls for a copy constructor.

6. What will be the output?

<br />
	class Sample{<br />
	public:<br />
	int *ptr;<br />
	Sample(int i){<br />
	ptr = new int(i);<br />
	}<br />
	~Sample(){<br />
	delete ptr;<br />
	}<br />
	void PrintVal(){<br />
	cout &lt;&lt; &quot;The value is &quot; &lt;&lt; *ptr;<br />
	}<br />
	};<br />
	void SomeFunc(Sample x){<br />
	cout &lt;&lt; &quot;Say i am in someFunc &quot; &lt;&lt; endl;<br />
	}<br />
	int main(){<br />
	Sample s1= 10;<br />
	SomeFunc(s1);<br />
	s1.PrintVal();<br />
	}<br />
	

  Answer:
Say i am in someFunc.
Null pointer assignment(Run-time error)
  Explanation:
As the object is passed by value to ‘SomeFunc’ the destructor of the object is called when the control returns from the function. So when PrintVal is called, it meets up with ptr  that has been freed.The solution is to pass the Sample object  by reference to SomeFunc:
void SomeFunc(Sample &x){
cout << "Say i am in someFunc " << endl;
}
because when we pass objects by refernece that object is not destroyed. while returning from the function.

7. What is the output of the following program?

<br />
	void Sample(int x=6,int y,int z=34){<br />
	cout &lt;&lt; &quot;Say i am in sample with the values &quot; &lt;&lt;x&lt;&lt;y&lt;&lt;z;<br />
	}<br />
	void main(){<br />
	&nbsp;&nbsp; int a,b,c;<br />
	&nbsp; cin &gt;&gt;a&gt;&gt;b&gt;&gt;c;<br />
	&nbsp;&nbsp; Sample(a,b,c);<br />
	}<br />
	

Answer:
Compile Time error: Missing default parameter for parameter 2.
Explanation:
The program wouldn’t compile because, as far as default arguments are concerned, the right-most argument must be supplied with a default value before a default argument to a parameter to it’s left can be supplied.

8. 

<br />
	class base{<br />
	public:<br />
	int bval;<br />
	base(){ bval=0;}<br />
	};<br />
	class deri:public base{<br />
	public:<br />
	int dval;<br />
	deri(){ dval=1;}<br />
	};<br />
	void SomeFunc(base *arr,int size){<br />
	for(int i=0; i&lt;size; i++,arr++)<br />
	cout&lt;&lt;arr-&gt;bval;<br />
	cout&lt;&lt;endl;<br />
	}<br />
	int main(){<br />
	base BaseArr[5];<br />
	SomeFunc(BaseArr,5);<br />
	deri DeriArr[5];<br />
	SomeFunc(DeriArr,5);<br />
	}<br />
	

  Answer:
00000
01010
Explanation: 

The function SomeFunc expects two arguments.The first one is a pointer to an array of base class objects and the second one is the sizeof the array.The first call of someFunc calls it with an array of base objects, so it works correctly and prints the bval of all the objects. When SomeFunc is called the second time the argument passed is a pointer to an array of derived class objects and not the array of base class objects.
But that is what the function expects to be sent. So the derived class pointer is promoted to base class pointer and the address is sent to the function. SomeFunc() knows nothing about this and just treats the pointer as an array of base class objects. So when arr++ is met, the size of base class object is taken into consideration and is incremented by sizeof(int) bytes for bval (the deri class objects have bval and dval as members and so is of size >= sizeof(int)+sizeof(int) ).

9.

<br />
class some{<br />
public:<br />
~some(){<br />
&nbsp; cout&lt;&lt;&quot;some&#39;s destructor&quot;&lt;&lt;endl;<br />
}<br />
};<br />
void main(){<br />
some s;<br />
&nbsp; s.~some();<br />
}<br />

Answer:
some's destructor
some's destructor
Explanation:
Destructors can be called explicitly (constructors can not be). Here 's.~some()' explicitly calls the destructor of 's'. When main() returns, destructor of s is called again, hence the result.

10. 

<br />
class base{<br />
public:<br />
void baseFun(){ cout&lt;&lt;&quot;from base&quot;&lt;&lt;endl;}<br />
};<br />
class deri:public base{<br />
public:<br />
void baseFun(){ cout&lt;&lt; &quot;from derived&quot;&lt;&lt;endl;}<br />
};<br />
void SomeFunc(base *baseObj){<br />
baseObj-&gt;baseFun();<br />
}<br />
int main(){<br />
base baseObject;<br />
SomeFunc(&amp;baseObject);<br />
deri deriObject;<br />
SomeFunc(&amp;deriObject);<br />
}<br />

  Answer:
  from base
from base
  Explanation:
As we have seen in the previous case, SomeFunc expects a pointer to a base class. Since a pointer to a derived class object is passed, it treats the argument only as a base class pointer and the corresponding base function is called.

 11. Ok guess it's output?

<br />
class base{<br />
public:<br />
virtual void baseFun(){ cout&lt;&lt;&quot;from base&quot;&lt;&lt;endl;}<br />
};<br />
class deri:public base{<br />
public:<br />
void baseFun(){ cout&lt;&lt; &quot;from derived&quot;&lt;&lt;endl;}<br />
};<br />
void SomeFunc(base *baseObj){<br />
baseObj-&gt;baseFun();<br />
}<br />
int main(){<br />
base baseObject;<br />
SomeFunc(&amp;baseObject);<br />
deri deriObject;<br />
SomeFunc(&amp;deriObject);<br />
}<br />

  Answer:
  from base
from derived
  Explanation:
Remember that baseFunc is a virtual function. That means that it supports run-time polymorphism. So the function corresponding to the derived class object is called.

12. What is the output of the following code?

<br />
class base<br />
{<br />
public:<br />
int n;<br />
virtual void foo(){n=1;}<br />
void print(){cout &lt;&lt;n&lt;&lt;endl;}<br />
};<br />
class derived: base<br />
{<br />
public:<br />
void foo(){n=2;}<br />
void print(){cout &lt;&lt;n&lt;&lt;endl;}<br />
};<br />
void main()<br />
{<br />
derived y;<br />
base *bp =dynamic_cast&lt;base *&gt;(&amp;y);<br />
bp-&gt;foo();<br />
bp-&gt;print();<br />
}<br />

Answer:
Undefined behavior : dynamic_cast used to convert to inaccessible or ambiguous base;
Explanation:
In this program private inheritance is used (by default the inheritance is private).  There is no implicit conversion from the derived to base due to this. An explicit dynamic cast is used to overcome this. But at runtime environment may impose the restrictions on access to the code, resulting in an undefined behavior.

13.

<br />
class fig2d{<br />
&nbsp; int dim1, dim2;<br />
public:<br />
fig2d() { dim1=5; dim2=6;}<br />
virtual void operator&lt;&lt;(ostream &amp; rhs);<br />
};<br />
void fig2d::operator&lt;&lt;(ostream &amp;rhs){<br />
rhs &lt;&lt;this-&gt;dim1&lt;&lt;&quot; &quot;&lt;&lt;this-&gt;dim2&lt;&lt;&quot; &quot;;<br />
}<br />
class fig3d : public fig2d{<br />
int dim3;<br />
public:<br />
fig3d() { dim3=7;}<br />
virtual void operator&lt;&lt;(ostream &amp;rhs);<br />
};<br />
void fig3d::operator&lt;&lt;(ostream &amp;rhs){<br />
fig2d::operator &lt;&lt;(rhs);<br />
&nbsp; rhs&lt;&lt;this-&gt;dim3;<br />
}<br />
void main(){<br />
fig2d obj1;<br />
fig3d obj2;<br />
obj1 &lt;&lt; cout;<br />
obj2 &lt;&lt; cout;<br />
}<br />

Answer :
  5 6
Explanation:
In this program, the << operator is overloaded with ostream as argument. This enables the 'cout' to be present at the right-hand-side. Normally, operator << is implemented as global function, but it doesn't mean that it is not possible to be overloaded as member function. Overloading << as virtual member function becomes handy when the class in which it is overloaded is inherited, and this becomes available to be overrided. This is as opposed to global friend functions, where friend's are not inherited.

14  

<br />
class opOverload{<br />
public:<br />
bool operator==(opOverload temp);<br />
};<br />
bool opOverload::operator==(opOverload temp){<br />
&nbsp; if(*this&nbsp; == temp ){<br />
&nbsp;&nbsp; cout&lt;&lt;&quot;The both are same objects\n&quot;;<br />
&nbsp; return true;<br />
&nbsp; }<br />
&nbsp; cout&lt;&lt;&quot;The both are different\n&quot;;<br />
return false;<br />
}<br />
void main(){<br />
&nbsp; opOverload a1, a2;<br />
a1== a2;<br />
}<br />

Answer :
Runtime Error: Stack Overflow
Explanation :
Just like normal functions, operator functions can be called recursively. This program just illustrates that point, by calling the operator == function recursively, leading to an infinite loop.

15.

<br />
class complex{<br />
double re;<br />
double im;<br />
public:<br />
complex() : re(1),im(0.5) {}<br />
operator int(){}<br />
};<br />
int main(){<br />
&nbsp; complex&nbsp; c1;<br />
cout&lt;&lt; c1;<br />
}<br />

Answer :
Garbage value
Explanation:
The programmer wishes to print the complex object using output re-direction operator,which he has not defined for his class.But the compiler instead of giving an error sees the conversion function and converts the user defined object to standard object and prints some garbage value.

16. What will be the output?

<br />
class complex{<br />
double re;<br />
double im;<br />
public:<br />
complex() : re(0),im(0) {}<br />
complex(double n) { re=n,im=n;};<br />
complex(int m,int n) { re=m,im=n;}<br />
void print() { cout&lt;&lt;re; cout&lt;&lt;im;}<br />
};<br />
void main(){<br />
&nbsp; complex c3;<br />
double i=5;<br />
&nbsp; c3 = i;<br />
c3.print();<br />
}<br />

Answer:
  5,5
Explanation:
There is no operator= function taking double as an argument is defined.  So the compiler creates a ‘complex’ object using the single argument constructor that takes double as an argument.  This temporary object is assigned to c3.

17.  Consider the following piece of code.

<br />
String s(&ldquo;hello!&rdquo;);<br />
String s2 = s1+ &ldquo;how are You&rdquo;;<br />

Will this code compile for this class declaration:

class String {
public:
String(char *);
String & operator=(String &);
String operator+(String);
friend  operator+(String,String);
};
Answer:
  No, this code will not compile.
Explanation:
Because there is an ambiguity between the overloading of the + operator as a member function and friend function. Given the statement:
String s2 = s1+ “how are You”;
the compiler doesn’t know to which function should it resolve to and call.

18. What is the output of the following code?

<br />
class base {/*....*/};<br />
class derived :public base{/*....*/};<br />
void foo()<br />
{ try<br />
{<br />
&nbsp; throw derived();<br />
}<br />
catch (base b)<br />
{<br />
&nbsp; cout&lt;&lt;&quot;Received exception, but can&#39;t handle\n&quot;;<br />
throw;<br />
}<br />
};<br />
void main()<br />
{<br />
try<br />
{<br />
&nbsp; foo();<br />
}<br />
catch (derived d)<br />
{<br />
&nbsp; cout&lt;&lt;&quot;In derived handler&quot;;<br />
}<br />
catch (base b)<br />
{<br />
&nbsp; cout &lt;&lt; &quot;In Base handler&quot;;<br />
}<br />
}<br />

Answer:
   Received exception, but can't handle
   In derived handler
Explanation:
When the function foo is called, the exception object of type derived is thrown. Now the catch block for that ‘derived’ exception object is searched but it is found that there is a catch block for ‘base’ is available. Since exception objects of type ‘base’ can handle all such exceptions in its hierarchy, this exception is caught.
A plain ‘throw’ inside a catch indicates a re-throw of the exception caught. So the ‘derived’ exception object is again thrown and is caught by the catch block in main().  Although both the catch blocks are eligible to handle the exception, this time the derived which is defined first will catch the exception.

19. What is the output of the following program?

<br />
void main(){<br />
vector&lt;int&gt; vec1,vec2;<br />
&nbsp; vec1.push_back(12);<br />
vec1.push_back(13);<br />
&nbsp; vec2.push_back(12);<br />
vec2.push_back(13);<br />
&nbsp; cout &lt;&lt; (vec1&lt;vec2);<br />
}<br />

Answer:
0
Explanation:
The values contained in both the containers are equal. Therefore the comparison returns 0. Each container supports a set of comparison operators. The comparison is based on a pair-wise comparison of the elements of the two containers. If all the elements are equal and if both the containers contain the same number of elements, the two containers are equal; otherwise, they are unequal. A comparison of the first unequal element determines the less-than or greater-than relationship of the 2 containers.

20. Consider the following lines of code:

<br />
list&lt;int&gt; aList;<br />
list&lt;int&gt;::iterator anIterator(&amp;aList);<br />

what can  you say about the relationship between ‘aList’ and ‘anIterator’?
Answer:
The class iterator is a friend of class list.
Explanation:
Iterators are always friend functions.

21.

<br />
#include &lt;list&gt;<br />
#include &lt;algorithm&gt;<br />
#include &lt;iostream&gt;<br />
using namespace std;<br />
void main()<br />
{<br />
list&lt;int&gt; ilist;<br />
list&lt;int&gt;::iterator iiter;<br />
for (int i=0;i&lt;10;i++) ilist.push_back(i);<br />
iiter = find(ilist.begin(),ilist.end(),3);<br />
if ( *(iiter+1) ==4) cout &lt;&lt;&quot;yeah ! found&quot;;<br />
}<br />

Output:
Compile –time error:
Explanation:
The code won’t compile because , iterators associated with list containers do not support the operator + used in the expression (*(iter+1) ==4 ), because iterators associated with list are of type bi-directional iterator, which doesn’t support the + operator.

Share your comment