250+ TOP MCQs on OOPs Concept and Answers Quiz Exam

C++ Programming Objective Questions & Answers on “OOPs Concept”.

1. Which operator is overloaded for a cout object?
a) >>
b) <<
c) <
d) >

Answer: b
Clarification: cout in C++ uses << operator to print anything so << operator is overloaded for a cout object.

2. Which of the following cannot be used with the virtual keyword?
a) Class
b) Member functions
c) Constructors
d) Destructors

Answer: c
Clarification: Virtual keyword cannot be used with constructors as constructors are defined to initialized an object of particular class hence no other class needs constructor of other class.

3. Which concept is used to implement late binding?
a) Virtual functions
b) Operator functions
c) Constant functions
d) Static functions

Answer: a
Clarification: Virtual functions are used to implement the concept of late binding i.e. binding actual functions to their calls.

4. Which of the following is correct?
a) C++ allows static type checking
b) C++ allows dynamic type checking.
c) C++ allows static member function to be of type const.
d) C++ allows both static and dynamic type checking

Answer: d
Clarification: C++ allows both static and dynamic type checking i.e. types are checked by the compiler.

5. Which of the following supports the concept that reusability is a desirable feature of a language?
a) It reduces the testing time
b) It reduces maintenance cost
c) It decreases the compilation time
d) It reduced both testing and maintenance time

Answer: d
Clarification: As we will be using the existing code therefore we don’t need to check the code again and again so testing and maintenance time decreases but the compiler time may increase or remains same because though we are reusing the code but every part needs to be compiled and extra include statement needs to be executed therefore compilation time may remain same or increases.

6. Which of the following is a static polymorphism mechanism?
a) Function overloading
b) Operator overloading
c) Templates
d) All of the mentioned

Answer: d
Clarification: All the options mentioned above uses static polymorphism mechanism. As the conflicts in all these types of functions are resolved during compile-time.

7. Which of the following is true?
I) All operators in C++ can be overloaded.
II) The basic meaning of an operator can be changed.
a) I only
b) II only
c) Both I and II
d) Neither I nor II

Answer: d
Clarification: Both statements are false because all the operators of C++ cannot be overloaded and the basic meaning of an operator cannot be changed, we can only give new meaning to an operator.

8. Which of the following is not a type of inheritance?
a) Multiple
b) Multilevel
c) Distributive
d) Hierarchical

Answer: c
Clarification: Distributive is not a type of inheritance whereas others are a type of inheritance having their own meaning.

9. What happens if a class does not have a name?
a) It will not have a constructor
b) It will not have a destructor
c) It is not allowed
d) It will neither have a constructor or destructor

Answer: b
Clarification: A class without a name will not have a destructor. The object is made so constructor is required but the destructor is not. Check the code below:

#include 
using namespace std;
class
{
    public:
	void func()
        {
		cout<<"Hello world";
	}
}a;
int main(int argc, char const *argv[])
{
	a.func();
	return 0;
}

10. Which of the following statement is true?
I) In Procedural programming languages, all function calls are resolved at compile-time
II) In Object Oriented programming languages, all function calls are resolved at compile-time
a) I only
b) II only
c) Both I and II
d) Neither I nor II

Answer: a
Clarification: In Procedural programming like C we don’t have the concept of polymorphism, therefore, all the function calls are resolved at the compile-time but in case of OOP languages sue to polymorphism concept all function calls are not resolved at compile-time.

11. Which members are inherited but are not accessible in any case?
a) Private
b) Public
c) Protected
d) Both private and protected

Answer: a
Clarification: Private members of a class are inherited to the child class but are not accessible from the child class.

12. Which of the following is correct?
a) Friend functions can access public members of a class
b) Friend functions can access protected members of a class
c) Friend functions can access private members of a class
d) All of the mentioned

Answer: d
Clarification: Friend functions can access any member of a class without caring about the type of member i.e. without caring whether it is private, protected or public.

13. Which of the following is correct in C++?
a) Classes cannot have protected data members
b) Structures can have member functions
c) Class members are public by default
d) Structure members are private by default

Answer: b
Clarification: Though C does not allows member functions in structures but C++ allows structures to have member functions. Members of structures are public by default and those of classes are private by default. Classes can have protected data members.

14. Which of the following is used to make an abstract class?
a) By using virtual keyword in front of a class declaration
b) By using an abstract keyword in front of a class declaration
c) By declaring a virtual function in a class
d) By declaring a pure virtual function in a class

Answer: d
Clarification: Abstract class should have at least one pure virtual function. Therefore to declare an abstract class one should declare a pure virtual function in a class.

15. Which of the following is correct?
a) A class is an instance of its objects
b) An object is an instance of its class
c) A class is an instance of the data type that the class have
d) An object is an instance of the data type of the class

Answer: b
Clarification: An object is an instance of a class i.e. an object represents a class i.e. what class has(data members) and what it can do(member functions).

250+ TOP MCQs on Pointers and Answers

This section on C++ aptitude questions and answers on “Pointers”. One shall practice these aptitude questions to improve their C++ programming skills needed for various interviews (campus interviews, walk-in interviews, company interviews), placements, entrance exams, aptitude tests and other competitive exams. These questions can be attempted by anyone focusing on learning C++ programming language. They can be a beginner, fresher, engineering graduate or an experienced IT professional. Our C++ questions come with the detailed explanation of the answers which helps in better understanding of C++ concepts.

Here is a listing of C++ aptitude questions on “Pointers” along with answers, explanations and/or solutions:

1. What does the following statement mean?

a) pointer to a pointer
b) pointer to an array of chars
c) pointer to function taking a char* argument and returns an int
d) function taking a char* argument and returning a pointer to int
Answer: c
Clarification: The (*fn) represents a pointer to a function and char* as arguments and returning int from the function. So according to that, the above syntax represents a pointer to a function taking a char* as an argument and returning int.

2. The operator used for dereferencing or indirection is ____
a) *
b) &
c) ->
d) –>>
Answer: a
Clarification: * is used as dereferencing operator, used to read value stored at the pointed address.

3. Choose the right option.

string* x, y;

a) x is a pointer to a string, y is a string
b) y is a pointer to a string, x is a string
c) both x and y are pointers to string types
d) y is a pointer to a string
Answer: a
Clarification: * is to be grouped with the variables, not the data types.

4. Which one of the following is not a possible state for a pointer.
a) hold the address of the specific object
b) point one past the end of an object
c) zero
d) point to a type
Answer: d
Clarification: A pointer can be in only 3 states a, b and c.

5. Which of the following is illegal?
a) int *ip;
b) string s, *sp = 0;
c) int i; double* dp = &i;
d) int *pi = 0;
Answer: c
Clarification: dp is initialized int value of i.

6. What will happen in the following C++ code snippet?

  1.    int a = 100, b = 200;
  2.    int *p = &a, *q = &b;
  3.    p = q;

a) b is assigned to a
b) p now points to b
c) a is assigned to b
d) q now points to a
Answer: b
Clarification: Assigning to reference changes the object to which the reference is bound.

7. What will be the output of the following C++ code?

  1.     #include 
  2.     using namespace std;
  3.     int main()
  4.     {
  5.         int a = 5, b = 10, c = 15;
  6.         int *arr[ ] = {&a, &b, &c};
  7.         cout << arr[1];
  8.         return 0;
  9.     }

a) 5
b) 10
c) 15
d) it will return some random number
Answer: d
Clarification: Array element cannot be address of auto variable. It can be address of static or extern variables.

8. The correct statement for a function that takes pointer to a float, a pointer to a pointer to a char and returns a pointer to a pointer to a integer is ____________
a) int **fun(float**, char**)
b) int *fun(float*, char*)
c) int **fun(float*, char**)
d) int ***fun(*float, **char)
Answer: c
Clarification: Function that takes pointer to a float, a pointer to a pointer to a char and returns a pointer to a pointer to a integer is int **fun(float*, char**).

9. What will be the output of the following C++ code?

  1.     #include 
  2.     using namespace std;
  3.     int main()
  4.     {
  5.         char arr[20];
  6.         int i;
  7.         for(i = 0; i < 10; i++)
  8.             *(arr + i) = 65 + i;
  9.         *(arr + i) = ' ';
  10.         cout << arr;
  11.         return(0);
  12.     }

a) ABCDEFGHIJ
b) AAAAAAAAAA
c) JJJJJJJJ
d) AAAAAAJJJJ
Answer: a
Clarification: Each time we are assigning 65 + i. In first iteration i = 0 and 65 is assigned. So it will print from A to J.
$ g++ point1.cpp
$ a.out
ABCDEFGHIJ

10. What will be the output of the following C++ code?

  1.     #include 
  2.     using namespace std;
  3.     int main()
  4.     {
  5.         char *ptr;
  6.         char Str[] = "abcdefg";
  7.         ptr = Str;
  8.         ptr += 5;
  9.         cout << ptr;
  10.         return 0;
  11.     }

a) fg
b) cdef
c) defg
d) abcd
Answer: a
Clarification: Pointer ptr points to string ‘fg’. So it prints fg.
Output:

$ g++ point.cpp
$ a.out
fg

250+ TOP MCQs on Value Return and Answers

This section on C++ interview questions and answers on “Value Return”. One shall practice these interview questions to improve their C++ programming skills needed for various interviews (campus interviews, walkin interviews, company interviews), placements, entrance exams and other competitive exams. These questions can be attempted by anyone focusing on learning C++ programming language. They can be a beginner, fresher, engineering graduate or an experienced IT professional. Our C++ interview questions come with detailed explanation of the answers which helps in better understanding of C++ concepts.

Here is a listing of C++ interview questions on “Value Return” along with answers, explanations and/or solutions:

1. How many types of returning values are present in c++?
a) 1
b) 2
c) 3
d) 4
Answer: c
Clarification: The three types of returning values are return by value, return by reference and return by address.

2. What will you use if you are not intended to get a return value?
a) static
b) const
c) volatile
d) void
Answer: d
Clarification: Void is used to not to return anything.

3. Where does the return statement returns the execution of the program?
a) main function
b) caller function
c) same function
d) block function
Answer: b
Clarification: The execution of the program is returned to the point from where the function was called and the function from which this function was called is known as caller function.

4. What will be the output of the following C++ code?

  1.     #include 
  2.     using namespace std;
  3.     int max(int a, int b )
  4.     {
  5.         return ( a > b ? a : b );
  6.     }
  7.     int main()
  8.     {
  9.         int i = 5;
  10.         int j = 7;
  11.         cout << max(i, j );
  12.         return 0;
  13.     }

a) 5
b) 7
c) either 5 or 7
d) 13
Answer: b
Clarification: In this program, we are returning the maximum value by using conditional operator.
Output:

5. What will be the output of the following C++ code?

  1.     #include 
  2.     using namespace std;
  3.     double & WeeklyHours()
  4.     {
  5.         double h = 46.50;
  6.         double &hours = h;
  7.         return hours;
  8.     }
  9.     int main()
  10.     {
  11.         double hours = WeeklyHours();
  12.         cout << "Weekly Hours: " << hours;
  13.         return 0;
  14.     }

a) 46.5
b) 6.50
c) compile time error
d) 26.5
Answer: a
Clarification: We are returning the value what we get as input.
Output:

$ g++ ret1.cpp
$ a.out
46.5

6. What will be the output of the following C++ code?

  1.     #include 
  2.     using namespace std;
  3.     int mult (int x, int y)
  4.     {
  5.         int result;
  6.         result = 0;
  7.         while (y != 0) 
  8.         {
  9.             result = result + x;
  10.             y = y - 1;
  11.         }
  12.         return(result);
  13.     }
  14.     int main ()
  15.     {
  16.         int x = 5, y = 5;
  17.         cout  << mult(x, y) ;
  18.         return(0);
  19.     }

a) 20
b) 25
c) 30
d) 35
Answer: b
Clarification: We are multiplying these values by adding every values.
Output:

7. When will we use the function overloading?
a) same function name but different number of arguments
b) different function name but same number of arguments
c) same function name but same number of arguments
d) different function name but different number of arguments
Answer: a
Clarification: We use function overloading when we want the same name function to perform different procedure for different types of parameters or different number of parameters provided to the function.

8. What will be the output of the following C++ code?

  1.     #include 
  2.     using namespace std;
  3.     int gcd (int a, int b)
  4.     {
  5.         int temp;
  6.         while (b != 0) 
  7.         {
  8.             temp = a % b;
  9.             a = b;
  10.             b = temp;
  11.         }
  12.         return(a);
  13.     }
  14.     int main ()
  15.     {
  16.         int x = 15, y = 25;
  17.         cout << gcd(x, y);
  18.         return(0);
  19.     }

a) 15
b) 25
c) 375
d) 5
Answer: d
Clarification: In this program, we are finding the gcd of the number.
Output:

250+ TOP MCQs on Operator Functions and Answers

This section on C++ questions and puzzles on “Operator Functions”. One shall practice these questions and puzzles to improve their C++ programming skills needed for various interviews (campus interviews, walk-in interviews, company interviews), placements, entrance exams and other competitive exams. These programming puzzles can be attempted by anyone focusing on learning C++ programming language. They can be a beginner, fresher, engineering graduate or an experienced IT professional. Our C++ questions come with the detailed explanation of the answers which helps in better understanding of C++ concepts.

Here is a listing of C++ questions and puzzles on “Operator Functions” along with answers, explanations and/or solutions:

1. Pick the other name of operator function.
a) function overloading
b) operator overloading
c) member overloading
d) object overloading
Answer: b
Clarification: Operator function means operation defined for that operator so if user defines a function for an operator then that is called operator overloading i.e. overloading already present operator function.

2. Which of the following operators can’t be overloaded?
a) ::
b) +
c) –
d) []
Answer: a
Clarification: :: operator cannot be overloaded because this operator operates on names rather than values and C++ has no syntax for writing codes that works on names than values so using syntax these operators cannot be overloaded.

3. How to declare operator function?
a) operator sign
b) operator
c) name of the operator
d) name of the class
Answer: a
Clarification: We have to declare the operator function by using the operator, operator sign. Example “operator +” where the operator is a keyword and + is the symbol need to be overloaded.

4. What will be the output of the following C++ code?

  1.     #include 
  2.     using namespace std;
  3.     class sample 
  4.     {
  5.         public:
  6.         int x, y;
  7.         sample() {};
  8.         sample(int, int);
  9.         sample operator + (sample);
  10.     };
  11.     sample::sample (int a, int b) 
  12.     {
  13.         x = a;
  14.         y = b;
  15.     }
  16.     sample sample::operator+ (sample param) 
  17.     {
  18.         sample temp;
  19.         temp.x = x + param.x;
  20.         temp.y = y + param.y;
  21.         return (temp);
  22.     }
  23.     int main () 
  24.     {
  25.         sample a (4,1);
  26.         sample b (3,2);
  27.         sample c;
  28.         c = a + b;
  29.         cout << c.x << "," << c.y;
  30.         return 0;
  31.     }

a) 5, 5
b) 7, 3
c) 3, 7
d) 3, 5
Answer: b
Clarification: In this program, we are adding the first number of a with first number of b by using operator function and also we are adding second number by this method also.
Output:

$ g++ oper.cpp
$ a.out
7, 3

5. What will be the output of the following C++ code?

  1.     #include 
  2.     using namespace std;
  3.     class Box
  4.     {   
  5.         double length;
  6.         double breadth;
  7.         double height;
  8.         public:
  9.         double getVolume(void)
  10.         {  
  11.             return length * breadth * height;
  12.         }
  13.         void setLength( double len )
  14.         {   
  15.             length = len;
  16.         }
  17.         void setBreadth( double bre )
  18.         {   
  19.             breadth = bre;
  20.         }
  21.         void setHeight( double hei )
  22.         {   
  23.             height = hei;
  24.         }
  25.         Box operator+(const Box& b)
  26.         {  
  27.             Box box;
  28.             box.length = this->length + b.length;
  29.             box.breadth = this->breadth + b.breadth;
  30.             box.height = this->height + b.height;
  31.             return box;
  32.         } 
  33.     };
  34.     int main( )
  35.     {  
  36.         Box Box1;
  37.         Box Box2;
  38.         Box Box3;
  39.         double volume = 0.0;
  40.         Box1.setLength(6.0);
  41.         Box1.setBreadth(7.0);
  42.         Box1.setHeight(5.0);
  43.         Box2.setLength(12.0);
  44.         Box2.setBreadth(13.0);
  45.         Box2.setHeight(10.0);
  46.         volume = Box1.getVolume();
  47.         cout << "Volume of Box1 : " << volume <<endl;
  48.         volume = Box2.getVolume();
  49.         cout << "Volume of Box2 : " << volume <<endl;
  50.         Box3 = Box1 + Box2;
  51.         volume = Box3.getVolume();
  52.         cout << "Volume of Box3 : " << volume <<endl;
  53.         return 0;
  54.     }

a)

   Volume of Box1 : 210
   Volume of Box2 : 1560
   Volume of Box3 : 5400

b)

   Volume of Box1 : 200
   Volume of Box2 : 1560
   Volume of Box3 : 5400

c)

   Volume of Box1 : 210
   Volume of Box2 : 1550
   Volume of Box3 : 5400

d)

   Volume of Box1 : 200
   Volume of Box2 : 1000
   Volume of Box3 : 5260

View Answer

Answer: a
Clarification: In this program, we finding the box3 area by adding box1 and box2.
Output:

$ g++ oper1.cpp
$ a.out
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

6. What will be the output of the following C++ code?

  1.     #include 
  2.     using namespace std;
  3.     class Integer 
  4.     {
  5.         int i;
  6.         public:
  7.         Integer(int ii) : i(ii) {}
  8.         const Integer
  9.         operator+(const Integer& rv) const 
  10.         {
  11.             cout << "operator+" << endl;
  12.             return Integer(i + rv.i);
  13.         }
  14.         Integer&
  15.         operator+=(const Integer& rv) 
  16.         {
  17.             cout << "operator+=" << endl;
  18.             i += rv.i;
  19.             return *this;
  20.         }
  21.     };
  22.     int main() 
  23.     {
  24.         int i = 1, j = 2, k = 3;
  25.         k += i + j;
  26.         Integer ii(1), jj(2), kk(3);
  27.         kk += ii + jj;
  28.     }

a)

   operator+
   operator+=

b)

   operator+=
   operator+

c)

   operator+
   operator+

d)

   operator+
   operator=

View Answer

Answer: a
Clarification: We are using two operator functions and executing them and the result is printed according to the order.
Output:

$ g++ oper2.cpp
$ a.out
operator+
operator+=

7. What will be the output of the following C++ code?

  1.     #include 
  2.     using namespace std;
  3.     class myclass
  4.     {
  5.         public:
  6.         int i;
  7.         myclass *operator->()
  8.         {return this;}
  9.     };
  10.     int main()
  11.     {
  12.         myclass ob;
  13.         ob->i = 10; 
  14.         cout << ob.i << " " << ob->i;
  15.         return 0;
  16.     }

a) 10 10
b) 11 11
c) error
d) runtime error
Answer: a
Clarification: In this program, -> operator is used to describe the member of the class and so we are getting this output.
Output:

$ g++ char4.cpp
$ a.out
10 10

8. Which of the following statements is NOT valid about operator overloading?
a) Only existing operators can be overloaded
b) The overloaded operator must have at least one operand of its class type
c) The overloaded operators follow the syntax rules of the original operator
d) None of the mentioned
Answer: b
Clarification: The overloaded operator must not have at least one operand of its class type.

9. Operator overloading is ___________
a) making c++ operator works with objects
b) giving new meaning to existing operator
c) making the new operator
d) adding operation to the existing operators
Answer: d
Clarification: Operator overloading is the way adding operation to the existing operators.

10. What will be the output of the following C++ code?

  1.     #include 
  2.     using namespace std;
  3.     ostream & operator<<(ostream & i, int n)
  4.     {
  5.         return i;
  6.     }
  7.     int main()
  8.     {
  9.         cout << 5 << endl;
  10.         cin.get();
  11.         return 0;
  12.     }

a) 5
b) 6
c) error
d) runtime error
Answer: c
Clarification: In this program, there will arise an ambiguous overload for 5.

250+ TOP MCQs on Constructors and Destructors – 1 and Answers

C++ Programming Multiple Choice Questions & Answers (MCQs) on “Constructors and Destructors – 1”.

1. What is the role of a constructor in classes?
a) To modify the data whenever required
b) To destroy an object
c) To initialize the data members of an object when it is created
d) To call private functions from the outer world
Answer: c
Clarification: A constructor is used in classes to initialize data members of class in order to avoid errors/segmentation faults.

2. Why constructors are efficient instead of a function init() defined by the user to initialize the data members of an object?
a) Because user may forget to call init() using that object leading segmentation fault
b) Because user may call init() more than once which leads to overwriting values
c) Because user may forget to define init() function
d) All of the mentioned
Answer: d
Clarification: We cannot use init() because as mentioned in options that user may forget to initialize the members which will lead to a segmentation fault. Also if the user calls the init() function more than once it may overwrite the values and may result into disastrous results. Also if any user forgets to define init() function then no object will be initialized whereas if any constructor is not defined in any class the class provides a default constructor for initialization.

3. What is a copy constructor?
a) A constructor that allows a user to move data from one object to another
b) A constructor to initialize an object with the values of another object
c) A constructor to check the whether to objects are equal or not
d) A constructor to kill other copies of a given object.
Answer: b
Clarification: Copy constructor allows the user to initialize an object with the values of another object instead of supplying the same set of values again to initialize the object.

4. What will be the output of the following C++ code?

#include 
#include 
using namespace std;
class A{
	int a;
public:
	A(int i){
		a = i;
	}
	void assign(int i){
		a = i;
	}
	int return_value(){
		return a;
	}
};
int main(int argc, char const *argv[])
{
	A obj;
	obj.assign(5);
	cout<<obj.return_value();
}

a) 5
b) 55
c) Error
d) Segmentation Fault
Answer: c
Clarification: As we have defined a constructor which takes an int parameter, so when we are trying to declare an object obj of class A without supplying any parameter then as a constructor is overwritten it will give an error saying that no matching function found. So whenever one writes a constructor then the default constructor is overwritten hence if you want to declare an object without parameter then you also have to define that constructor.

5. What will be the output of the following C++ code?

#include 
#include 
using namespace std;
class A{
	int a;
	A(){
		a = 5;
	}
 
public:
	void assign(int i){
		a = i;
	}
	int return_value(){
		return a;
	}
};
int main(int argc, char const *argv[])
{
	A obj;
	obj.assign(10);
	cout<<obj.return_value();
}

a) 5
b) 10
c) Error
d) Segmentation fault
Answer: c
Clarification: Here the constructor is made private and as no object can access any private object directly therefore the program will give error. One should always define a constructor as public.

6. In the following C++ code how many times the string “A’s constructor called” will be printed?

#include 
#include 
using namespace std;
class A{
	int a;
public:
	A(){
		cout<<"A's constructor called";
	}
};
class B{
	static A a;
public:
	B(){
		cout<<"B's constructor called";
	}
	static A get(){
		return a;
	}
};
A B::a;
int main(int argc, char const *argv[])
{
	B b;
	A a1 = b.get();
	A a2 = b.get();
	A a3 = b.get();
}

a) 3
b) 4
c) 2
d) 1
Answer: d
Clarification: As the object is defined ony once in the program at line A B::a, so the constructor of A is called only once. For objects a1, a2 and a3 copy constructor is called so the string will not be printed for them.

7. What happens if a user forgets to define a constructor inside a class?
a) Error occurs
b) Segmentation fault
c) Objects are not created properly
d) Compiler provides a default constructor to avoid faults/errors
Answer: d
Clarification: The C++ compiler always provides a default constructor if one forgets to define a constructor inside a class.

8. How many parameters does a default constructor require?
a) 1
b) 2
c) 0
d) 3
Answer: c
Clarification: A default constructor does not require any parameters for object creation that’s why sometimes we declare an object without any parameters.

9. How constructors are different from other member functions of the class?
a) Constructor has the same name as the class itself
b) Constructors do not return anything
c) Constructors are automatically called when an object is created
d) All of the mentioned
Answer: d
Clarification: All the above mention are the reasons where constructor differs from other normal member functions of a class.

10. How many types of constructors are there in C++?
a) 1
b) 2
c) 3
d) 4
Answer: c
Clarification: There are three types of constructors in C++ namely default, parameterized and copy constructor.

11. What will be the output of the following C++ code?

#include 
#include 
using namespace std;
class A{
	mutable int a;
public:
	A(){
		cout<<"Default constructor calledn";
	}
	A(const A& a){
		cout<<"Copy Constructor calledn";
	}
};
int main(int argc, char const *argv[])
{
	A obj;
	A a1 = obj;
	A a2(obj);
}

a)

Default constructor called
Copy Constructor called

b)

Default constructor called
Copy Constructor called
Copy Constructor called

c)

Default constructor called
Default constructor called
Copy Constructor called

d)

Copy Constructor called
Default constructor called
Copy Constructor called

View Answer

Answer: b
Clarification: When object obj is declared then the default constructor is called. When we are declaring the a1 object as we are equating obj to a1 object obj will be copied to a1 hence copy constructor is called, similarly when object a2 is created obj is passed as a parameter to function which is available as copy constructor function, hence copy constructor will be called. So one time Default constructor and two times copy constructor.

 
 

12. What will be the output of the following C++ code?

#include 
#include 
using namespace std;
class A{
	mutable int a;
public:
	A(){
		cout<<"A's default constructor calledn";
	}
	A(const A& a){
		cout<<"A's copy Constructor calledn";
	}
};
class B{
	A obj;
public:
	B(){
		cout<<"B's Constructor calledn";
	}
};
int main(int argc, char const *argv[])
{
	B b1;
	B b2;
}

a)

B's Constructor called
B's Constructor called

b)

B's Constructor called
A's default constructor called
B's Constructor called
A's default constructor called

c)

A's default constructor called
B's Constructor called
A's default constructor called
B's Constructor called

d)

A's default constructor called
B's Constructor called
A's copy Constructor called

View Answer

Answer: c
Clarification: Here when we are declaring the object b1 of class B then first the constructor of class B will be called, in which first it will initialize all the members of class B and as obj from class A is member of class B and it should be initialized so the A’s default constructor will be called and terminates after that B’s constructor terminates hence A’s default constructor called is printed before B’s constructor called.

 
 

13. What is the role of destructors in Classes?
a) To modify the data whenever required
b) To destroy an object when the lifetime of an object ends
c) To initialize the data members of an object when it is created
d) To call private functions from the outer world
Answer: b
Clarification: Destructors are used in Classes to destroy an object after its lifetime is over i.e. to free resources occupied by that object.

14. What is syntax of defining a destructor of class A?
a) A(){}
b) ~A(){}
c) A::A(){}
d) ~A(){};
Answer: b
Clarification: A destructor starts with a ~(tilde) symbol, has the same name as the class.

15. When destructors are called?
a) When a program ends
b) When a function ends
c) When a delete operator is used
d) All of the mentioned
Answer: d
Clarification: Destructors are called at the following time:
i) at the end of the program to destroy objects declared in the main() or global scope.
ii) at the end of a function to destroy objects declared at that function scope.
iii) when user by himself tries to delete an object using the delete operator.
iv) at the end of a block to destroy objects declared at that block scope.

250+ TOP MCQs on Templates and Answers

C++ Programming Multiple Choice Questions & Answers (MCQs) on “Templates”.

1. Which of the following is used for generic programming?
a) Virtual functions
b) Modules
c) Templates
d) Abstract Classes
Answer: c
Clarification: Templates are used for generic programming. They help in making generic functions and classes hence achieving the generic codes.

2. Which of the following is correct about templates?
a) It is a type of compile time polymorphism
b) It allows the programmer to write one code for all data types
c) Helps in generic programming
d) All of the mentioned
Answer: d
Clarification: Templates are used for generic programming hence allowing to write a single function for all data types. It is a type of compile time polymorphism.

3. What will be the output of the following C++ code?

#include 
using namespace std; 
template <typename T>
void fun(const T&x)
{
    static int count = 0;
    cout << "x = " << x << " count = " << count;
    ++count;
    return;
}
 
int main()
{
    fun<int> (1); 
    cout << endl;
    fun<int>(1); 
    cout << endl;
    fun<double>(1.1);
    cout << endl;
    return 0;
}

a)

x = 1 count = 0
x = 1 count = 1
x = 1.1 count = 0

b)

x = 1 count = 0
x = 1.0 count = 1.0
x = 1.1 count = 0

c)

x = 1.0 count = 0.0
x = 1 count = 1
x = 1.1 count = 0

d)

x = 1.0 count = 0.0
x = 1.0 count = 1.0
x = 1.1 count = 0.0

View Answer

Answer: a
Clarification: As template is a type of polymorphism so count becomes 1 for int type because we have called the function for int twice but as we have called it only once for double therefore value of count is 0 for double i.e. for last call.

 
 

4. What will be the output of the following C++ function?

#include 
using namespace std; 
template <typename T>
T max(T x, T y)
{
    return (x > y)? x : y;
}
int main()
{
    cout << max(3, 7) << std::endl;
    cout << max(3.0, 7.0) << std::endl;
    cout << max(3, 7.0) << std::endl;
    return 0;
}

a)

7
7.0
7.0

b)

7
7
7

c)

7.0 
7.0
7.0

d) Error
Answer: d
Clarification: Here in the template function as both the argument have same type T but in third called of max function we are using 2 types int and float while calling the function hence the program gives error.

5. What will be the output of the following C++ code?

#include 
using namespace std;
template <class T>
class Test
{
  private:
    T val;
  public:
    static int count;
    Test()  {   
    	count++;   
    }
};
template<class T>
int Test<T>::count = 0;
int main()
{
    Test<int> a;
    Test<int> b;
    Test<double> c;
    cout << Test<int>::count << endl;
    cout << Test<double>::count << endl;
    return 0;
}

a)

2
1

b)

1
2

c)

1
1

d)

2
2

View Answer

Answer: a
Clarification: In this as we have first used int to define the objects of class Test so count is increased to 2 for int types and declared the double object once therefore the constructor is called only once hence value of count is 1.

 
 

6. What will be the output of the following C++ code?

#include
#include
using namespace std; 
template<class T, class U>
class A  
{
    T x;
    U y;
};
 
int main()  
{
   A<char, char> a;
   A<int, int> b;
   cout << sizeof(a) << endl;
   cout << sizeof(b) << endl;
   return 0;
}

a)

2
8

b)

8
2

c)

1
4

d)

4
1

View Answer

Answer: a
Clarification: In this we have made class with two template arguments which are used in defining one variable of each type inside the class. So the total size of the class will depend on the type of U and T. So when we have defined the object with type then the class have two variable of char hence making the size of class = 2 which in case of = 8.

 
 

7. What will be the output of the following C++ code?

#include
#include
using namespace std; 
template<class T, class U, class V=double>
class A  
{
    T x;
    U y;
    V z;
};
 
int main()
{
   A<int, int> a;
   A<double, double> b;
   cout << sizeof(a) << endl;
   cout << sizeof(b) << endl;
   return 0;
}

a)

16
24

b)

24
16

c) Error
d) Segmentation fault
Answer: a
Clarification: In this case the class has three variables of type T, U and V = double by default. Now as we have defined objects with types so its size is 4+4+8 = 16 and second object of which leads to 8+8+8 = 24.

8. What will be the output of the following C++ code?

#include 
using namespace std; 
template <class T, int max>
int arrMin(T arr[], int n)
{
   int m = max;
   for (int i = 0; i < n; i++)
      if (arr[i] < m)
         m = arr[i];
 
   return m;
}
 
int main()
{
   int arr1[]  = {10, 20, 15, 12};
   int n1 = sizeof(arr1)/sizeof(arr1[0]);
 
   char arr2[] = {1, 2, 3};
   int n2 = sizeof(arr2)/sizeof(arr2[0]);
 
   cout << arrMin<int, 10000>(arr1, n1) << endl;
   cout << arrMin<char, 256>(arr2, n2);
   return 0;
}

a)

10
1

b)

12
2

c)

10000
256

d) Error
Answer: a
Clarification: In this, we are passing arr and its size in the template function. Now during first call value of m becomes 10 as it is the minimum in the array. In second call the value of m becomes 1 which is minimum in 2nd array.

9. What will be the output of the following C++ code?

#include 
using namespace std; 
template <class T>
T max (T &a, T &b)
{
	cout << "Template Called ";
    return (a > b)? a : b;
}
 
template <>
int max <int> (int &a, int &b)
{
    cout << "Called ";
    return (a > b)? a : b;
}
 
int main ()
{
    int a = 10, b = 20;
    cout << max <int> (a, b);
}

a) Template Called 20
b) Called 20
c) Error
d) Segmentation fault
Answer: b
Clarification: For T = int we have created a separate definition for the above template function. Hence the call using int takes the newly defined function.

10. What will be the output of the following C++ code?

#include 
using namespace std;  
template<int n> 
struct funStruct
{
    static const int val = 2*funStruct<n-1>::val;
};
 
template<> 
struct funStruct<0>
{
    static const int val = 1 ;
};
 
int main()
{
    cout << funStruct<10>::val << endl;
    return 0;
}

a) 1
b) 1024
c) Error
d) Segmentation fault
Answer: b
Clarification: The above call for struct will call the first struct for n > 0 and second one when n = 0. Therefore when value of n = 10 the until n becomes 0 first struct is called so we will call 2*2*2…10 times*1 which will give the result 210 = 1024.