Sie sind auf Seite 1von 116

4.

Derived Classes, Templates & Exception Handling in C++

C++ Programming Questions and Answers - Derived Classes - Sanfoundry


by Manish

This section on C++ programming questions and answers focuses on “Derived Classes”. One
shall practice these 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++ programming questions come with detailed explanation
of the answers which helps in better understanding of C++ concepts.

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

1. Where is the derived class is derived from?


a) derived
b) base
c) both derived & base
d) None of the mentioned
View Answer

Answer: b
Explanation: Because derived inherits functions and variables from base.

2. Pick out the correct statement.


a) A derived class’s constructor cannot explicitly invokes its base class’s constructor
b) A derived class’s destructor cannot invoke its base class’s destructor
c) A derived class’s destructor can invoke its base class’s destructor
d) None of the mentioned
View Answer

Answer: b
Explanation: Destructors are automatically invoked when a object goes out of scope or when a
dynamically allocated object is deleted. Inheritance does not change this behavior. This is the
reason a derived destructor cannot invoke its base class destructor.

3. Which of the following can derived class inherit?


a) members
b) functions
c) both members & functions
d) none of the mentioned
View Answer
Answer: c
Explanation: None.

4. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. public:
6. A(int n )
7. {
8. cout << n;
9. }
10. };
11. class B: public A
12. {
13. public:
14. B(int n, double d)
15. : A(n)
16. {
17. cout << d;
18. }
19. };
20. class C: public B
21. {
22. public:
23. C(int n, double d, char ch)
24. : B(n, d)
25. {
26. cout <<ch;
27. }
28. };
29. int main()
30. {
31. C c(5, 4.3, 'R');
32. return 0;
33. }

a) 54.3R
b) R4.35
c) 4.3R5
d) None of the mentioned
View Answer

Answer: a
Explanation: In this program, We are passing the value and manipulating by using the derived
class.
Output:
$ g++ der.cpp
$ a.out
54.3R
5. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. class BaseClass
4. {
5. protected:
6. int i;
7. public:
8. BaseClass(int x)
9. {
10. i = x;
11. }
12. ~BaseClass()
13. {
14. }
15. };
16. class DerivedClass: public BaseClass
17. {
18. int j;
19. public:
20. DerivedClass(int x, int y): BaseClass(y)
21. {
22. j = x;
23. }
24. ~DerivedClass()
25. {
26. }
27. void show()
28. {
29. cout << i << " " << j << endl;
30. }
31. };
32. int main()
33. {
34. DerivedClass ob(3, 4);
35. ob.show();
36. return 0;
37. }

a) 3 4
b) 4 3
c) 4
d) 3
View Answer

Answer: b
Explanation: In this program, We are passing the values and assigning it to i and j and we are
printing it.
Output:
$ g++ der1.cpp
$ a.out
43
6. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. int m;
7. Base(int n=0)
8. : m(n)
9. {
10. cout << "Base" << endl;
11. }
12. };
13. class Derived: public Base
14. {
15. public:
16. double d;
17. Derived(double de = 0.0)
18. : d(de)
19. {
20. cout << "Derived" << endl;
21. }
22. };
23. int main()
24. {
25. cout << "Instantiating Base" << endl;
26. Base cBase;
27. cout << "Instantiating Derived" << endl;
28. Derived cDerived;
29. return 0;
30. }

a) Instantiating Base
Base
Instantiating Derived
Base
Derived
b) Instantiating Base
Instantiating Derived
Base
Derived
c) Instantiating Base
Base
Instantiating Derived
Base
d) None of the mentioned
View Answer

Answer: a
Explanation: In this program, We are printing the execution order of the program.
Output:
$ g++ der2.cpp
$ a.out
Instantiating Base
Base
Instantiating Derived
Base
Derived

7. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. class Parent
4. {
5. public:
6. Parent (void)
7. {
8. cout << "Parent()\n";
9. }
10. Parent (int i)
11. {
12. cout << "Parent("<< i << ")\n";
13. };
14. Parent (void)
15. {
16. cout << "~Parent()\n";
17. };
18. };
19. class Child1 : public Parent { };
20. class Child2 : public Parent
21. {
22. public:
23. Child2 (void)
24. {
25. cout << "Child2()\n";
26. }
27. Child2 (int i) : Parent (i)
28. {
29. cout << "Child2(" << i << ")\n";
30. }
31. ~Child2 (void)
32. {
33. cout << "~Child2()\n";
34. }
35. };
36. int main (void)
37. {
38. Child1 a;
39. Child2 b;
40. Child2 c(42);
41. return 0;
42. }
a) Parent()
Parent()
Child2()
Parent(42)
Child2(42)
~Child2()
~Parent()
~Child2()
~Parent()
~Parent()
b) error
c) runtime error
d) none of the mentioned
View Answer

Answer: b
Explanation: In this program, We got an error in overloading because we didn’t invoke the
destructor of parent.

8. What is the output of this program?

1. #include<iostream>
2. using namespace std;
3. class X
4. {
5. int m;
6. public:
7. X() : m(10)
8. {
9. }
10. X(int mm): m(mm)
11. {
12. }
13. int getm()
14. {
15. return m;
16. }
17. };
18. class Y : public X
19. {
20. int n;
21. public:
22. Y(int nn) : n(nn) {}
23. int getn() { return n; }
24. };
25. int main()
26. {
27. Y yobj( 100 );
28. cout << yobj.getm() << " " << yobj.getn() << endl;
29. }
a) 10 100
b) 100 10
c) 10 10
d) 100 100
View Answer

Answer: a
Explanation: In this program, We are passing the value and getting the result by derived class.
Output:
$ g++ der5.cpp
$ a.out
10 100

9. Which operator is used to declare the destructor?


a) #
b) ~
c) @
d) $
View Answer

Answer: b
Explanation: None.

10. Which constructor will initialize the base class data member?
a) derived class
b) base class
c) class
d) none of the mentioned
View Answer

Answer: b
Explanation: Because it is having the proper data set to initialize, Otherwise it will throw a error.

Interview Questions C++ - Abstract Classes - Sanfoundry


by Manish

This section on C++ interview questions and answers focuses on “Abstract Classes”. 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 “Abstract Classes” along with answers,
explanations and/or solutions:

1. Which class is used to design the base class?


a) abstract class
b) derived class
c) base class
d) none of the mentioned
View Answer

Answer: a
Explanation: None.

2. Which is used to create a pure virtual function ?


a) $
b) =0
c) &
d) !
View Answer

Answer: b
Explanation: For making a method as pure virtual function, We have to append ‘=0’ to the class
or method.

3. Which is also called as abstract class?


a) virtual function
b) pure virtual function
c) derived class
d) none of the mentioned
View Answer

Answer: b
Explanation: Classes that contain at least one pure virtual function are called as abstract base
classes.

4. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. class p
4. {
5. protected:
6. int width, height;
7. public:
8. void set_values (int a, int b)
9. {
10. width = a; height = b;
11. }
12. virtual int area (void) = 0;
13. };
14. class r: public p
15. {
16. public:
17. int area (void)
18. {
19. return (width * height);
20. }
21. };
22. class t: public p
23. {
24. public:
25. int area (void)
26. {
27. return (width * height / 2);
28. }
29. };
30. int main ()
31. {
32. r rect;
33. t trgl;
34. p * ppoly1 = &rect;
35. p * ppoly2 = &trgl;
36. ppoly1->set_values (4, 5);
37. ppoly2->set_values (4, 5);
38. cout << ppoly1 -> area() ;
39. cout << ppoly2 -> area();
40. return 0;
41. }

a) 1020
b) 20
c) 10
d) 2010
View Answer

Answer: d
Explanation: In this program, We are calculating the area of rectangle and
triangle by using abstract class.
Output:
$ g++ abs.cpp
$ a.out
2010

5. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. class MyInterface
4. {
5. public:
6. virtual void Display() = 0;
7. };
8. class Class1 : public MyInterface
9. {
10. public:
11. void Display()
12. {
13. int a = 5;
14. cout << a;
15. }
16. };
17. class Class2 : public MyInterface
18. {
19. public:
20. void Display()
21. {
22. cout <<" 5" << endl;
23. }
24. };
25. int main()
26. {
27. Class1 obj1;
28. obj1.Display();
29. Class2 obj2;
30. obj2.Display();
31. return 0;
32. }

a) 5
b) 10
c) 5 5
d) None of the mentioned
View Answer

Answer: c
Explanation: In this program, We are displaying the data from the two classes
by using abstract class.
Output:
$ g++ abs1.cpp
$ a.out
55

6. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. class sample
4. {
5. public:
6. virtual void example() = 0;
7. };
8. class Ex1:public sample
9. {
10. public:
11. void example()
12. {
13. cout << "ubuntu";
14. }
15. };
16. class Ex2:public sample
17. {
18. public:
19. void example()
20. {
21. cout << " is awesome";
22. }
23. };
24. int main()
25. {
26. sample* arra[2];
27. Ex1 e1;
28. Ex2 e2;
29. arra[0]=&e1;
30. arra[1]=&e2;
31. arra[0]->example();
32. arra[1]->example();
33. }

a) ubuntu
b) is awesome
c) ubuntu is awesome
d) none of the mentioned
View Answer

Answer: c
Explanation: In this program, We are combining the two statements from two classes and
printing it by using abstract class.
Output:
$ g++ abs3.cpp
$ a.out
ubuntu is awesome

7. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. virtual void print() const = 0;
7. };
8. class DerivedOne : virtual public Base
9. {
10. public:
11. void print() const
12. {
13. cout << "1";
14. }
15. };
16. class DerivedTwo : virtual public Base
17. {
18. public:
19. void print() const
20. {
21. cout << "2";
22. }
23. };
24. class Multiple : public DerivedOne, DerivedTwo
25. {
26. public:
27. void print() const
28. {
29. DerivedTwo::print();
30. }
31. };
32. int main()
33. {
34. Multiple both;
35. DerivedOne one;
36. DerivedTwo two;
37. Base *array[ 3 ];
38. array[ 0 ] = &both;
39. array[ 1 ] = &one;
40. array[ 2 ] = &two;
41. for ( int i = 0; i < 3; i++ )
42. array[ i ] -> print();
43. return 0;
44. }

a) 121
b) 212
c) 12
d) none of the mentioned
View Answer

Answer: b
Explanation: In this program, We are executing these based on the condition given in array. So it
is printing as 212.
Output:
$ g++ abs4.cpp
$ a.out
212

8. What is meant by pure virtual function?


a) Function which does not have definition of its own
b) Function which does have definition of its own
c) Function which does not have any return type
d) None of the mentioned
View Answer
Answer: a
Explanation: As the name itself implies, it have to depend on other class only.

9. Pick out the correct option.


a) We cannot make an instance of an abstract base class
b) We can make an instance of an abstract base class
c) We can make an instance of an abstract super class
d) None of the mentioned
View Answer

Answer: a
Explanation: None.

10. Where does the abstract class is used?


a) base class only
b) derived class
c) both derived & base class
d) none of the mentioned
View Answer

Answer: a
Explanation: None.

C++ Quiz - Design of Class Hierarchies - Sanfoundry


by Manish

This section on online C++ quiz focuses on “Design of Class Hierarchies”. One shall practice
these online quizzes 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++ quiz comes with detailed explanation of the answers which helps in
better understanding of C++ concepts.

Here is a listing of online C++ quiz on “Design of Class Hierarchies” along with answers,
explanations and/or solutions:

1. Which interface determines how your class will be used by other program?
a) public
b) private
c) protected
d) none of the mentioned
View Answer
Answer: a
Explanation: If we invoked the interface as public means, We can access the program from other
programs also.

2. Pick out the correct statement about override.


a) Overriding refers to a derived class function that has the same name and signature as a base
class virtual function
b) Overriding has different names
c) Overriding refers to a derived class
d) None of the mentioned
View Answer

Answer: a
Explanation: None.

3. How many ways of reusing are there in class hierarchy?


a) 1
b) 2
c) 3
d) 4
View Answer

Answer: b
Explanation: Class hierarchies promote reuse in two ways. They are code sharing and interface
sharing.

4. How many types of class are there in c++?


a) 1
b) 2
c) 3
d) 4
View Answer

Answer: c
Explanation: There are three types of classes. They are abstract base classes, concrete derived
classes, standalone classes.

5. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. class BaseClass
4. {
5. int i;
6. public:
7. void setInt(int n);
8. int getInt();
9. };
10. class DerivedClass : public BaseClass
11. {
12. int j;
13. public:
14. void setJ(int n);
15. int mul();
16. };
17. void BaseClass::setInt(int n)
18. {
19. i = n;
20. }
21. int BaseClass::getInt()
22. {
23. return i;
24. }
25. void DerivedClass::setJ(int n)
26. {
27. j = n;
28. }
29. int DerivedClass::mul()
30. {
31. return j * getInt();
32. }
33. int main()
34. {
35. DerivedClass ob;
36. ob.setInt(10);
37. ob.setJ(4);
38. cout << ob.mul();
39. return 0;
40. }

a) 10
b) 4
c) 40
d) None of the mentioned
View Answer

Answer: c
Explanation: In this program, We are multiplying the value 10 and 4 by using inheritance.
Output:
$ g++ des.cpp
$ a.out
40

6. Pick out the correct statement about multiple inheritance.


a) Deriving a class from one direct base class
b) Deriving a class from more than one direct base class
c) Deriving a class from more than one direct derived class
d) None of the mentioned
View Answer
Answer: b
Explanation: In multiple inheritance, We are able to derive a class from more than one base
class.

7. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. class BaseClass
4. {
5. int x;
6. public:
7. void setx(int n)
8. {
9. x = n;
10. }
11. void showx()
12. {
13. cout << x ;
14. }
15. };
16. class DerivedClass : private BaseClass
17. {
18. int y;
19. public:
20. void setxy(int n, int m)
21. {
22. setx(n);
23. y = m;
24. }
25. void showxy()
26. {
27. showx();
28. cout << y << '\n';
29. }
30. };
31. int main()
32. {
33. DerivedClass ob;
34. ob.setxy(10, 20);
35. ob.showxy();
36. return 0;
37. }

a) 10
b) 20
c) 1020
d) None of the mentioned
View Answer

Answer: c
Explanation: In this program, We are passing the values from the main class and printing it on
the inherited classes.
Output:
$ g++ des2.cpp
$ a.out
1020

8. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. class BaseClass
4. {
5. public:
6. virtual void myFunction()
7. {
8. cout << "1";
9. }
10. };
11. class DerivedClass1 : public BaseClass
12. {
13. public:
14. void myFunction()
15. {
16. cout << "2";
17. }
18. };
19. class DerivedClass2 : public DerivedClass1
20. {
21. public:
22. void myFunction()
23. {
24. cout << "3";
25. }
26. };
27. int main()
28. {
29. BaseClass *p;
30. BaseClass ob;
31. DerivedClass1 derivedObject1;
32. DerivedClass2 derivedObject2;
33. p = &ob;
34. p -> myFunction();
35. p = &derivedObject1;
36. p -> myFunction();
37. p = &derivedObject2;
38. p -> myFunction();
39. return 0;
40. }

a) 123
b) 12
c) 213
d) 321
View Answer
Answer: a
Explanation: We are passing the objects and executing them in a certain order and we are
printing the program flow.
Output:
$ g++ des3.cpp
$ a.out
123

9. What does inheriatance allows you to do?


a) create a class
b) create a hierarchy of classes
c) access methods
d) none of the mentioned
View Answer

Answer: b
Explanation: None.

10. What is the syntax of inheritance of class?


a) class name
b) class name : access specifer
c) class name : access specifer class name
d) none of the mentioned
View Answer

Answer: c
Explanation: None.

C++ Programming Questions and Answers - Class Hierarchies & Abstract


Classes - Sanfoundry
by Manish

This section on C++ programming questions and answers focuses on “Class Hierarchies and
Abstract Classes”. One shall practice these 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++ programming questions come
with detailed explanation of the answers which helps in better understanding of C++ concepts.

Here is a listing of C++ programming questions on “Class Hierarchies and Abstract Classes”
along with answers, explanations and/or solutions:

1. How many kinds of classes are there in c++?


a) 1
b) 2
c) 3
d) 4
View Answer

Answer: b
Explanation: There are two kinds of classes in c++. They are absolute class and concrete class.

2. What is meant by polymorphism?


a) class having many forms
b) class having only single form
c) class having two forms
d) none of the mentioned
View Answer

Answer: a
Explanation: Polymirphism is literally means class having many forms.

3. How many types of inheritance are there in c++?


a) 2
b) 3
c) 4
d) 5
View Answer

Answer: d
Explanation: There are five types of inheritance in c++. They are single, Multiple, Hierarchical,
Multilevel, Hybrid.

4. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. class stu
4. {
5. protected:
6. int rno;
7. public:
8. void get_no(int a)
9. {
10. rno = a;
11. }
12. void put_no(void)
13. {
14. }
15. };
16. class test:public stu
17. {
18. protected:
19. float part1,part2;
20. public:
21. void get_mark(float x, float y)
22. {
23. part1 = x;
24. part2 = y;
25. }
26. void put_marks()
27. {
28. }
29. };
30. class sports
31. {
32. protected:
33. float score;
34. public:
35. void getscore(float s)
36. {
37. score = s;
38. }
39. void putscore(void)
40. {
41. }
42. };
43. class result: public test, public sports
44. {
45. float total;
46. public:
47. void display(void);
48. };
49. void result::display(void)
50. {
51. total = part1 + part2 + score;
52. put_no();
53. put_marks();
54. putscore();
55. cout << "Total Score=" << total << "\n";
56. }
57. int main()
58. {
59. result stu;
60. stu.get_no(123);
61. stu.get_mark(27.5, 33.0);
62. stu.getscore(6.0);
63. stu.display();
64. return 0;
65. }

a) 66.5
b) 64.5
c) 62.5
d) 60.5
View Answer

Answer: a
Explanation: In this program, We are passing the values by using different
methods and totaling the marks to get the result.
Output:
$ g++ class.cpp
$ a.out
Total Score=66.5

5. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. class poly
4. {
5. protected:
6. int width, height;
7. public:
8. void set_values(int a, int b)
9. {
10. width = a; height = b;
11. }
12. };
13. class Coutput
14. {
15. public:
16. void output(int i);
17. };
18. void Coutput::output(int i)
19. {
20. cout << i;
21. }
22. class rect:public poly, public Coutput
23. {
24. public:
25. int area()
26. {
27. return(width * height);
28. }
29. };
30. class tri:public poly, public Coutput
31. {
32. public:
33. int area()
34. {
35. return(width * height / 2);
36. }
37. };
38. int main()
39. {
40. rect rect;
41. tri trgl;
42. rect.set_values(3, 4);
43. trgl.set_values(4, 5);
44. rect.output(rect.area());
45. trgl.output(trgl.area());
46. return 0;
47. }
a) 1212
b) 1210
c) 1010
d) none of the mentioned
View Answer

Answer: b
Explanation: In this program, We are calculating the area of rectangle and
triangle by using multilevel inheritance.
$ g++ class1.cpp
$ a.out
1210

6. What is meant by containership?


a) class contains objects of other class types as its members
b) class contains objects of other class types as its objects
c) class contains objects of other class types as its members 7 also objects
d) none of the mentioned
View Answer

Answer: a
Explanation: None.

7. How many types of constructor are there in C++?


a) 1
b) 2
c) 3
d) 4
View Answer

Answer: c
Explanation: There are three types of constructor in C++. They are Default constructor,
Parameterized constructor, Copy constructor.

8. How many constructors can present in a class?


a) 1
b) 2
c) 3
d) multiple
View Answer

Answer: d
Explanation: There can be multiple constructors of the same class, provided they have different
signatures.
9. What should be the name of constructor?
a) same as object
b) same as member
c) same as class
d) none of the mentioned
View Answer

Answer: c
Explanation: None.

10. What does derived class does not inherit from the base class?
a) constructor and destructor
b) friends
c) operator = () members
d) all of the mentioned
View Answer

Answer: d
Explanation: The derived class inherit everything from the base class except the given things.

Interview Questions on C++ - Simple String Template - Sanfoundry


by Manish

This section on C++ interview questions and answers focuses on “Simple String Template”. 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 “Simple String Template” along with answers,
explanations and/or solutions:

1. What is a template?
a) A template is a formula for creating a generic class
b) A template is used to manipulate the class
c) A template is used for creating the attributes
d) None of the mentioned
View Answer

Answer: a
Explanation: None.
2. Pick out the correct statement about string template.
a) It is used to replace a string
b) It is used to replace a string with another string at runtime
c) It is used to delete a string
d) None of the mentioned
View Answer

Answer: b
Explanation: Every string template is used to replace the string with another string at runtime.

3. How to declare a template?


a) tem
b) temp
c) template<>
d) none of the mentioned
View Answer

Answer: c
Explanation: None.

4. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. template <class T>
4. inline T square(T x)
5. {
6. T result;
7. result = x * x;
8. return result;
9. };
10. template <>
11. string square<string>(string ss)
12. {
13. return (ss+ss);
14. };
15. int main()
16. {
17. int i = 4, ii;
18. string ww("A");
19. ii = square<int>(i);
20. cout << i << ii;
21. cout << square<string>(ww) << endl;
22. }

a) 416AA
b) 164AA
c) AA416
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, We are using two template to calculate the square and to find the
addition.
Output:
$ g++ tem.cpp
$ a.out
416AA

5. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. template <typename T, typename U>
4. void squareAndPrint(T x, U y)
5. {
6. cout << x << x * x << endl;
7. cout << y << " " << y * y << endl;
8. };
9. int main()
10. {
11. int ii = 2;
12. float jj = 2.1;
13. squareAndPrint<int, float>(ii, jj);
14. }

a) 23
2.1 4.41
b) 24
2.1 4.41
c) 24
2.1 3.41
d) none of the mentioned
View Answer

Answer: b
Explanation: In this multiple templated types, We are passing two values of different types and
producing the result.
Output:
$ g++ tem1.cpp
$ a.out
24
2.1 4.41

6. What is the output of this program?

1. #include <iostream>
2. #include <string>
3. using namespace std;
4. template<typename T>
5. void print_mydata(T output)
6. {
7. cout << output << endl;
8. }
9. int main()
10. {
11. double d = 5.5;
12. string s("Hello World");
13. print_mydata( d );
14. print_mydata( s );
15. return 0;
16. }

a) 5.5
Hello World
b) 5.5
c) Hello World
d) None of the mentioned
View Answer

Answer: a
Explanation: In this program, We are passing the value to the template and printing it in the
template.
Output:
$ g++ tem2.cpp
$ a.out
5.5
Hello World

7. How many types of templates are there in c++?


a) 1
b) 2
c) 3
d) 4
View Answer

Answer: b
Explanation: There are two types of templates. They are function template and class template.

8. Which are done by compiler for templates?


a) type-safe
b) portability
c) code elimination
d) all of the mentioned
View Answer

Answer: a
Explanation: The compiler can determine at compile time whether the type associated with a
template definition can perform all of the functions required by that template definition.
9. What may be the name of the parameter that the template should take?
a) same as template
b) same as class
c) same as function
d) none of the mentioned
View Answer

Answer: a
Explanation: None.

10. How many parameters are legal for non-type template?


a) 1
b) 2
c) 3
d) 4
View Answer

Answer: d
Explanation: The following are legal for non-type template parameters: integral or enumeration
type, Pointer to object or pointer to function, Reference to object or reference to function, Pointer
to member.

C++ Programming Interview Questions - Function Templates -


Sanfoundry
by Manish

This section on C++ programming interview questions and answers focuses on “Function
Templates”. 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++ programming
interview questions come with detailed explanation of the answers which helps in better
understanding of C++ concepts.

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

1. What is a function template?


a) creating a function without having to specify the exact type
b) creating a function with having a exact type
c) all of the mentioned
d) none of the mentioned
View Answer
Answer: a
Explanation: None.

2. Which is used to describe the function using placeholder types?


a) template parameters
b) template type parameters
c) template type
d) none of the mentioned
View Answer

Answer: b
Explanation: During runtime, We can choose the appropriate type for the function
and it is called as template type parameters.

3. Pick out the correct statement.


a) you only need to write one function, and it will work with many different types
b) it will take a long time to execute
c) duplicate code is increased
d) none of the mentioned
View Answer

Answer: a
Explanation: Because of template type parameters, It will work with many types and saves a lot
of time.

4. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. template<typename type>
4. type Max(type Var1, type Var2)
5. {
6. return Var1 > Var2 ? Var1:Var2;
7. }
8. int main()
9. {
10. int p;
11. p = Max(100, 200);
12. cout << p << endl;
13. return 0;
14. }

a) 100
b) 200
c) 300
d) 100200
View Answer
Answer: b
Explanation: In this program, We are returning the maximum value by using function template.
Output:
$ g++ ftemp.cpp
$ a.out
200

5. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. template<typename type>
4. class Test
5. {
6. public:
7. Test()
8. {
9. };
10. ~Test()
11. {
12. };
13. type Funct1(type Var1)
14. {
15. return Var1;
16. }
17. type Funct2(type Var2)
18. {
19. return Var2;
20. }
21. };
22. int main()
23. {
24. Test<int> Var1;
25. Test<float> Var2;
26. cout << Var1.Funct1(200) << endl;
27. cout << Var2.Funct2(3.123) << endl;
28. return 0;
29. }

a) 200
3.123
b) 3.123
200
c) 200
d) 3.123
View Answer

Answer: a
Explanation: In this program, We are passing the values and getting it back from template. And
we are using the constructor and destructor for the function template.
Output:
$ g++ ftemp1.cpp
$ a.out
200
3.123

6. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. template<typename type>
4. class TestVirt
5. {
6. public:
7. virtual type TestFunct(type Var1)
8. {
9. return Var1 * 2;
10. }
11. };
12. int main()
13. {
14. TestVirt<int> Var1;
15. cout << Var1.TestFunct(100) << endl;
16. return 0;
17. }

a) 100
b) 200
c) 50
d) none of the mentioned
View Answer

Answer: b
Explanation: In this program, We are using class to pass the value and then we are manipulating
it.
Output:
$ g++ ftemp3.cpp
$ a.out
200

7. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. template<typename T>
4. inline T square(T x)
5. {
6. T result;
7. result = x * x;
8. return result;
9. };
10. int main()
11. {
12. int i, ii;
13. float x, xx;
14. double y, yy;
15. i = 2;
16. x = 2.2;
17. y = 2.2;
18. ii = square(i);
19. cout << i << " " << ii << endl;
20. yy = square(y);
21. cout << y << " " << yy << endl;
22. }

a) 2 4
2.2 4.84
b) 2 4
c) error
d) runtime error
View Answer

Answer: a
Explanation: In this program, We are passing the values and calculating the square of the value
by using the function template.
Output:
$ g++ ftemp4.cpp
$ a.out
24
2.2 4.84

8. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. template<typename T>
4. void loopIt(T x)
5. {
6. int count = 3;
7. T val[count];
8. for (int ii=0; ii < count; ii++)
9. {
10. val[ii] = x++;
11. cout << val[ii] << endl;
12. }
13. };
14. int main()
15. {
16. float xx = 2.1;
17. loopIt(xx);
18. }

a) 2.1
b) 3.1
c) 3.2
d) 2.1
3.1
4.1
View Answer

Answer: d
Explanation: In this program, We are using the for loop to increment the value by 1 in the
function template.
Output:
$ g++ ftemp5.cpp
$ a.out
2.1
3.1
4.1

9. What can be passed by non-type template parameters during compile time?


a) int
b) float
c) constant expression
d) none of the mentioned
View Answer

Answer: c
Explanation: Non-type template parameters provide the ability to pass a constant expression at
compile time. The constant expression may also be an address of a function, object or static class
member.

10. From where does the template class derived?


a) regular non-templated C++ class
b) templated class
c) regular non-templated C++ class or templated class
d) none of the mentioned
View Answer

Answer: c
Explanation: None.

C++ Programming Questions and Answers – Template Arguments to


Specify Policy Usage
This section on C++ MCQs (multiple choice questions) focuses on “Template Arguments to Specify Policy
Usage”. One shall practice these MCQs 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 multiple choice questions come with detailed explanation of the answers which helps
in better understanding of C++ concepts.

Here is a listing of C multiple choice questions on “Template Arguments to Specify Policy Usage” along
with answers, explanations and/or solutions:

1. What is meant by template parameter?


a) It can be used to pass a type as argument
b) It can be used to evaluate a type
c) It can of no return type
d) None of the mentioned
View Answer

Answer: a
Explanation: A template parameter is a special kind of parameter that can be used to pass a type as
argument.

2. Which keyword can be used in template?


a) class
b) typename
c) both class & typename
d) function
View Answer

Answer: c
Explanation: None.

3. What is the validity of template parameters?


a) inside that block only
b) inside the class
c) whole program
d) any of the mentioned
View Answer

Answer: a
Explanation: None.

4.What is the output of this program?

#include <iostream>

using namespace std;

template <class T, int N>

class mysequence

{
T memblock [N];

public:

void setmember (int x, T value);

T getmember (int x);

};

template <class T, int N>

void mysequence<T,N> :: setmember (int x, T value)

memblock[x] = value;

template <class T, int N>

T mysequence<T,N> :: getmember (int x)

return memblock[x];

int main ()

mysequence <int, 5> myints;

mysequence <double, 5> myfloats;

myints.setmember (0, 100);

myfloats.setmember (3, 3.1416);

cout << myints.getmember(0) << '\n';

cout << myfloats.getmember(3) << '\n';

return 0;

a) 100
b) 3.1416
c) 100
3.1416
d) none of the mentioned
View Answer
Answer: c
Explanation: In this program, We are printing the integer in the first function and float in the second
function.
Output:
$ g++ farg.cpp
$ a.out
100
3.1416

5. What is the output of this program?

#include <iostream>

using namespace std;

template <class T>

T max (T& a, T& b)

return (a>b?a:b);

int main ()

int i = 5, j = 6, k;

long l = 10, m = 5, n;

k = max(i, j);

n = max(l, m);

cout << k << endl;

cout << n << endl;

return 0;

a) 6
b) 6
10
c) 5
10
d) 6
5
View Answer

Answer: b
Explanation: In this program, We are using the ternary operator on the template function.
Output:
$ g++ farg.cpp
$ a.out
6
10

6. What is the output of this program?

#include <iostream>

using namespace std;

template <class type>

class Test

public:

Test()

};

~Test()

};

type Funct1(type Var1)

return Var1;

type Funct2(type Var2)

return Var2;

};
int main()

Test<int> Var1;

Test<double> Var2;

cout << Var1.Funct1(200);

cout << Var2.Funct2(3.123);

return 0;

a) 100
b) 200
c) 3.123
d) 2003.123
View Answer

Answer: d
Explanation: In this program, We are passing the value and returning it from template.
Output:
$ g++ farg3.cpp
$ a.out
2003.123

7. What is the output of this program?

#include <iostream>

using namespace std;

template <typename T, int count>

void loopIt(T x)

T val[count];

for(int ii = 0; ii < count; ii++)

val[ii] = x++;

cout << val[ii] << endl;

};
int main()

float xx = 2.1;

loopIt<float, 3>(xx);

a) 2.1
b) 3.1
c) 4.1
d) 2.1
3.1
4.1
View Answer

Answer: d
Explanation: In this program, We are using the non-type template parameter to increment the value in
the function template.
Output:
$ g++ farg4.cpp
$ a.out
2.1
3.1
4.1

8. Why we use :: template-template parameter?


a) binding
b) rebinding
c) both binding & rebinding
d) none of the mentioned
View Answer

Answer: c
Explanation: It is used to adapt a policy into binary ones.

9. Which parameter is legal for non-type template?


a) pointer to member
b) object
c) class
d) none of the mentioned
View Answer
Answer: a
Explanation: The following are legal for non-type template parameters:integral or enumeration type,
Pointer to object or pointer to function, Reference to object or reference to function, Pointer to
member.

10. Which of the things does not require instantiation?


a) functions
b) non virtual member function
c) member class
d) all of the mentioned
View Answer

Answer: d
Explanation: The compiler does not generate definitions for functions, non virtual member functions,
class or member class because it does not require instantiation.

C++ Programming Questions and Answers – Specialization


This section on C++ interview questions and answers focuses on “Specialization “. 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 “Specialization ” along with answers, explanations and/or
solutions:

1. What is meant by template specialization?


a) It will have certain data types to be fixed
b) It will make certain data types to be dynamic
c) Certain data types are invalid
d) None of the mentioned
View Answer

Answer: a
Explanation: In the template specialization, it will make the template to be specific for some data types.

2. Which is similar to template specialization?


a) template
b) function overloading
c) function template overloading
d) none of the mentioned
View Answer

Answer: c
Explanation: None

3. Which is called on allocating the memory for array of objects?


a) destructor
b) constructor
c) method
d) none of the mentioned
View Answer

Answer: b
Explanation: When you allocate memory for an array of objects, the default constructor must be called
to construct each object. If no default constructor exists, you’re stuck needing a list of pointers to
objects.

4. What is the output of this program?

#include <iostream>

using namespace std;

template <class T>

inline T square(T x)

T result;

result = x * x;

return result;

};

template <>

string square<string>(string ss)

return (ss+ss);

};

int main()

{
int i = 2, ii;

string ww("A");

ii = square<int>(i);

cout << i << ": " << ii;

cout << square<string>(ww) << ":" << endl;

a) 2:4AA
b) 2:4
c) AA
d) 2:4A
View Answer

Answer: a
Explanation: Template specialization is used when a different and specific implementation is to be used
for a specific data type. In this program, We are using integer and character.
Output:
$ g++ spec.cpp
$ a.out
2:4AA

5. What is the output of this program?

#include <iostream>

using namespace std;

template <typename T = float, int count = 3>

T multIt(T x)

for(int ii = 0; ii < count; ii++)

x = x * x;

return x;

};

int main()

{
float xx = 2.1;

cout << xx << ": " << multIt<>(xx) << endl;

a) 2.1
b) 378.228
c) 2.1: 378.228
d) None of the mentioned
View Answer

Answer: c
Explanation: In this program, We specifed the type in the template function. We need to compile this
program by adding -std=c++0x.
Output:
$ g++ -std=c++0x spec1.cpp
$ a.out
2.1: 378.228

6. What is the output of this program?

#include <iostream>

using namespace std;

template <class T>

class XYZ

public:

void putPri();

static T ipub;

private:

static T ipri;

};

template <class T>

void XYZ<T>::putPri()

cout << ipri++ << endl;

}
template <class T> T XYZ<T>::ipub = 1;

template <class T> T XYZ<T>::ipri = 1.2;

int main()

XYZ<int> a;

XYZ<float> b;

a.putPri();

cout << a.ipub << endl;

b.putPri();

a) 1
b) 1.2
c) 1
1.2
d) 1
1
1.2
View Answer

Answer: d
Explanation: In this program, We are passing the value of specified type and printing it by specialization.
Output:
$ g++ spec2.cpp
$ a.out
1
1
1.2

7. What is the output of this program?

#include <iostream>

#include <string>

#include <cstring>

using namespace std;

template <class type>

type MyMax(const type Var1, const type Var2)


{

cout << "no specialization";

return Var1 < Var2 ? Var2 : Var1;

template <>

const char *MyMax(const char *Var1, const char *Var2)

return (strcmp(Var1, Var2)<0) ? Var2 : Var1;

int main()

string Str1 = "class", Str2 = "template";

const char *Var3 = "class";

const char *Var4 = "template";

const char *q = MyMax(Var3, Var4);

cout << q << endl;

return 0;

a) template
b) class
c) no specialization
d) none of the mentioned
View Answer

Answer: a
Explanation: In this program, We are computing the result in the specalized block of the program.
Output:
$ g++ spec3.cpp
$ a.out
template

8. What is the output of this program?

#include <iostream>

using namespace std;


template<class T = float, int i = 5> class A

public:

A();

int value;

};

template<> class A<>

public: A();

};

template<> class A<double, 10>

public: A();

};

template<class T, int i> A<T, i>::A() : value(i)

cout << value;

A<>::A()

cout << "default";

A<double, 10>::A()

cout << "10" << endl;

int main()

A<int, 6> x;
A<> y;

A<double, 10> z;

a) 6
b) 10
c) 6default10
d) None of the mentioned
View Answer

Answer: c
Explanation: In this program, We are defining three templates and specializing it and passing the values
to it and printing it.
Output:
$ g++ spec5.cpp
$ a.out
6default10

9. How many types of specialization are there in c++?


a) 1
b) 2
c) 3
d) 4
View Answer

Answer: b
Explanation: There are two types specialization. They are full specialization and partial specialization.

10. What is other name of full specialization?


a) explicit specialization
b) implicit specialization
c) function overloading template
d) none of the mentioned
View Answer

Answer: a
Explanation: None

C++ Programming Questions and Answers – Derivation and


Templates
This section on advanced C++ interview questions focuses on “Derivation and Templates”. One shall
practice these advanced C++ 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 advanced C++ questions come with detailed explanation of the answers which helps in
better understanding of C++ concepts.

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

1. Which is dependant on template parameter?


a) base class
b) abstract class
c) method
d) none of the mentioned
View Answer

Answer: a
Explanation: None

2. Which value is placed in the base class?


a) derived values
b) default type values
c) both default type & derived values
d) none of the mentioned
View Answer

Answer: b
Explanation: We can place the default type values in a base class and overriding some of them through
derivation.

3. How many bits of memory needed for internal representation of class?


a) 1
b) 2
c) 4
d) no memory needed
View Answer

Answer: d
Explanation: classes that contain only type members, nonvirtual function members, and static data
members do not require memory at run time.

4. What is the output of this program?

#include <iostream>

using namespace std;


class class0

public:

virtual ~class0(){}

protected:

char p;

public:

char getChar();

};

class class1 : public class0

public:

void printChar();

};

void class1::printChar()

cout << "True" << endl;

int main()

class1 c;

c.printChar();

return 1;

a) True
b) error
c) no output
d) runtime error
View Answer

Answer: a
Explanation: In this program, We are passing the values and inheriting it to the other class and printing
the result.
$ g++ dert.cpp
$ a.out
True

5. What is the output of this program?

#include <iostream>

using namespace std;

template<typename T>class clsTemplate

public:

T value;

clsTemplate(T i)

this->value = i;

void test()

cout << value << endl;

};

class clsChild : public clsTemplate<char>

public:

clsChild(): clsTemplate<char>( 0 )

clsChild(char c): clsTemplate<char>( c )

void test2()
{

test();

};

int main()

clsTemplate <int> a( 42 );

clsChild b( 'A' );

a.test();

b.test();

return 0;

a) 42
b) A
c) 42
A
d) A
42
View Answer

Answer: c
Explanation: In this program, We are passing the values by using the template inheritance and printing
it.
Output:
$ g++ dert.cpp
$ a.out
42
A

6. What is the output of this program?

#include <iostream>

using namespace std;

template <class T>

class A

{
public:

A(int a): x(a) {}

protected:

int x;

};

template <class T>

class B: public A<char>

public:

B(): A<char>::A(100)

cout << x * 2 << endl;

};

int main()

B<char> test;

return 0;

a) 100
b) 200
c) error
d) runtime error
View Answer

Answer: b
Explanation: In this program, We are passing the values and manipulating it by using the template
inheritance.
Output:
$ g++ dert2.cpp
$ a.out
200

7. What is the output of this program?


#include <iostream>

using namespace std;

template <class type>

class Test

public:

Test();

~Test();

type Data(type);

};

template <class type>

type Test<type>::Data(type Var0)

return Var0;

template <class type>

Test<type>::Test()

template <class type>

Test<type>::~Test()

int main(void)

Test<char> Var3;

cout << Var3.Data('K') << endl;

return 0;

}
a) k
b) l
c) error
d) runtime error
View Answer

Answer: a
Explanation: In this program, We are passing the values and printing it by using template inheritance.
Output:
$ g++ dert3.cpp
$ a.out
k

8. What is the output of this program?

#include <iostream>

using namespace std;

class Base

public:

Base ( )

cout << "1" << endl;

~Base ( )

cout << "2" << endl;

};

class Derived : public Base

public:

Derived ( )

cout << "3" << endl;


}

~Derived ( )

cout << "4" << endl;

};

int main( )

Derived x;

a) 1234
b) 4321
c) 1423
d) 1342
View Answer

Answer: d
Explanation: In this program, We are printing the order of execution of constructor and destructor in the
class.
Output:
$ g++ dert4.cpp
$ a.out
1342

9. How many kinds of entities are directly parameterized in c++?


a) 1
b) 2
c) 3
d) 4
View Answer

Answer: c
Explanation: C++ allows us to parameterize directly three kinds of entities through templates: types,
constants, and templates.

10. How many kinds of parameters are there in C++?


a) 1
b) 2
c) 3
d) None of the mentioned
View Answer

Answer: c
Explanation: There are three kinds of parameters are there in C++. They are type, non-type, template.

C++ Programming Questions and Answers - Error Handling - Sanfoundry


by Manish

This section on C++ programming questions and answers focuses on “Error Handling”. One
shall practice these 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++ programming questions come with detailed explanation
of the answers which helps in better understanding of C++ concepts.

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

1. Which keyword is used to handle the expection?


a) try
b) throw
c) catch
d) none of the mentioned
View Answer

Answer: c
Explanation: When we found a exception in the program, We need to throw that and we handle
that by using the catch keyword.

2. Which is used to throw a exception?


a) throw
b) try
c) catch
d) none of the mentioned
View Answer

Answer: a
Explanation: None.

3. What is the use of the ‘finally’ keyword?


a) It used to execute at the starting of the program
b) It will be executed at the end of the program even if the exception arised
c) It will be executed at the starting of the program even if the exception arised
d) none of the mentioned
View Answer

Answer: b
Explanation: finally keyword will be executed at the end of all the exception.

4. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. double division(int a, int b)
4. {
5. if (b == 0)
6. {
7. throw "Division by zero condition!";
8. }
9. return (a / b);
10. }
11. int main ()
12. {
13. int x = 50;
14. int y = 0;
15. double z = 0;
16. try
17. {
18. z = division(x, y);
19. cout << z << endl;
20. }
21. catch (const char* msg)
22. {
23. cerr << msg << endl;
24. }
25. return 0;
26. }

a) 50
b) 0
c) Division by zero condition!
d) Error
View Answer

Answer: c
Explanation: It’s a mathematical certainty, We can’t divide by zero, So we’re arising a
exception.
Output:
$ g++ excep.cpp
$ a.out
Division by zero condition!

5. What is the output of this program?


1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. try
6. {
7. throw 20;
8. }
9. catch (int e)
10. {
11. cout << "An exception occurred " << e << endl;
12. }
13. return 0;
14. }

a) 20
b) An exception occurred
c) Error
d) An exception occurred 20
View Answer

Answer: d
Explanation: We are handling the exception by throwing that number. So the output is printed
with the given number.
Output:
$ g++ excep1.cpp
$ a.out
An exception occurred 20

6. What is the output of this program?

1. #include <iostream>
2. #include <exception>
3. using namespace std;
4. class myexception: public exception
5. {
6. virtual const char* what() const throw()
7. {
8. return "My exception";
9. }
10. } myex;
11. int main ()
12. {
13. try
14. {
15. throw myex;
16. }
17. catch (exception& e)
18. {
19. cout << e.what() << endl;
20. }
21. return 0;
22. }
a) Exception
b) Error
c) My exception
d) runtime error
View Answer

Answer: c
Explanation: This is a standard exception handler used in the class.
Output:
$ g++ excep2.cpp
$ a.out
My exception

7. What is the output of this program?

1. #include <iostream>
2. #include <exception>
3. using namespace std;
4. int main ()
5. {
6. try
7. {
8. int* myarray = new int[1000];
9. cout << "allocated";
10. }
11. catch (exception& e)
12. {
13. cout << "Standard exception: " << e.what() << endl;
14. }
15. return 0;
16. }

a) Allocated
b) Standard exception
c) Depends on the memory
d) Error
View Answer

Answer: c
Explanation: In this program, We are allocating the memory for array. If it is allocated means, no
exception will arise and if there is no size in memory means, Exception will arise.
Output:
$ g++ excep3.cpp
$ a.out
allocated

8. What is the output of this program?

1. #include <iostream>
2. #include <exception>
3. using namespace std;
4. struct MyException : public exception
5. {
6. const char * what () const throw ()
7. {
8. return "C++ Exception";
9. }
10. };
11. int main()
12. {
13. try
14. {
15. throw MyException();
16. }
17. catch(MyException& e)
18. {
19. cout << "Exception caught" << std::endl;
20. cout << e.what() << std::endl;
21. }
22. catch(std::exception& e)
23. {
24. }
25. }

a) C++ Exception
b) Exception caught
c) Exception caught
C++ Exception
d) Error
View Answer

Answer: c
Explanation: We are defining the user-defined exception in this program.
Output:
$ g++ excep4.cpp
$ a.out
C++ Exception
Exception caught

9. How do define the user-defined exceptions?


a) inheriting and overriding exception class functionality
b) overriding class functioality
c) inheriting class functionality
d) none of the mentioned
View Answer

Answer: a
Explanation: None.

10. Which exception is thrown by dynamic_cast?


a) bad_cast
b) bad_typeid
c) bad_exception
d) bad_alloc
View Answer

Answer: a
Explanation: bad_cast exception is thrown by dynamic_cast.

C++ Programming Questions and Answers – Grouping of Exceptions


This section on C++ test focuses on “Grouping of Exceptions”. One shall practice these test 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++ test questions come
with detailed explanation of the answers which helps in better understanding of C++ concepts.

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

1. How many types of exception handling are there in c++?


a) 1
b) 2
c) 3
d) 4
View Answer

Answer: b
Explanation: There are two types of exception handling in c++. They are synchronous exception handling
and asynchronous exception handling.

2. How many runtime error messages associated with exception?


a) 2
b) 4
c) 5
d) infinite
View Answer

Answer: b
Explanation: There are four runtime error messages associated with exceptions.They are
overflow_error, range_error, system_error and underflow_error.

3. Which block should be placed after try block?


a) catch
b) throw
c) either catch or throw
d) none of the mentioned
View Answer

Answer: a
Explanation: None.

4. What is the output of this program?

#include <iostream>

using namespace std;

int main()

double a = 10, b = 5, res;

char Operator = '/';

try

if (b == 0)

throw "Division by zero not allowed";

res = a / b;

cout << a << " / " << b << " = " << res;

catch(const char* Str)

cout << "\n Bad Operator: " << Str;

return 0;

a) 10
b) 2
c) Bad Operator
d) 10 / 5 = 2
View Answer
Answer: d
Explanation: In this program, We are dividing the two variables and printing the result. If any one of the
operator is zero means, it will arise a exception.
Output:
$ g++ gex.cpp
$ a.out
10 / 5 =2

5. What is the output of this program?

#include <iostream>

using namespace std;

int main()

try

throw 1;

catch (int a)

cout << "exception number: " << a << endl;

return 0;

cout << "No exception " << endl;

return 0;

a) No exception
b) exception number
c) exception number: 1
d) none of the mentioned
View Answer

Answer: c
Explanation: If we caught a integer value means, there will be an exception, if it is not a integer, there
will not be a exception.
Output:
$ g++ gex1.cpp
$ a.out
exception number: 1

6. What is the output of this program?

#include <iostream>

using namespace std;

int main()

int a = 10, b = 20, c = 30;

float d;

try

if ((a - b) != 0)

d = c / (a - b);

cout << d;

else

throw(a - b);

catch (int i)

cout<<"Answer is infinite "<<i;

a) 10
b) -3
c) 15
d) none of the mentioned
View Answer

Answer: b
Explanation: We are manipulating the values, if there is any infinite value means, it will raise an
exception.
Output:
$ g++ gex2.cpp
$ a.out
-3

7. What is the output of this program?

#include <iostream>

using namespace std;

void test(int x)

try

if (x > 0)

throw x;

else

throw 'x';

catch(int x)

cout<<"integer:"<<x;

catch(char x)

cout << "character:" << x;

int main()
{

test(10);

test(0);

a) integer:10character:x
b) integer:10
c) character:x
d) none of the mentioned
View Answer

Answer: a
Explanation: We are passing the integer and character and catching it by using multiple catch statement.
Output:
$ g++ gex3.cpp
$ a.out
integer:10character:x

8. What is the output of this program?

#include <iostream>

using namespace std;

void PrintSequence(int StopNum)

int Num;

Num = 1;

while (true)

if (Num >= StopNum)

throw Num;

cout << Num << endl;

Num++;

int main(void)

{
try

PrintSequence(2);

catch(int ExNum)

cout << "exception: " << ExNum << endl;

return 0;

a) 1
b) exception: 2
c) 1
exception: 2
d) none of the mentioned
View Answer

Answer: c
Explanation: In this program, We are printing one and raising a exception at 2.
Output:
$ g++ gex4.cpp
$ a.out
1
exception: 2

9. Pick out the correct Answer.


a) Exceptions are not suitable for critical points in code
b) Exception are suitable for critical points in code
c) All of the mentioned
d) None of the mentioned
View Answer

Answer: a
Explanation: If there is many number of exceptions in the program means, We have to use multiple
catch statement and it is hard to keep track of the program.

10. When exceptions are used?


a) To preserve the program
b) Exceptions are used when postconditions of a function cannot be satisfied
c) Exceptions are used when postconditions of a function can be satisfied
d) None of the mentioned
View Answer

Answer: c
Explanation: None.

C++ Programming Questions and Answers – Catching Exceptions


This section on C++ programming interview questions and answers focuses on “Catching Exceptions”.
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++ programming interview questions come with detailed explanation of the answers
which helps in better understanding of C++ concepts.

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

1. How many parameters does the throw expression can have?


a) 1
b) 2
c) 3
d) 4
View Answer

Answer: a
Explanation: In c++ program, We can be able to throw only one error at a time.

2. Where exception are handled?


a) inside the program
b) outside the regular code
c) both inside or outside
d) none of the mentioned
View Answer

Answer: b
Explanation: none

3. Which is used to check the error in the block?


a) try
b) throw
c) catch
d) none of the mentioned
View Answer

Answer: a
Explanation: The try block is used to check for errors, if there is any error means, it can throw it to catch
block.

4. What is the output of this program?

#include <iostream>

#include <exception>

using namespace std;

class myexception: public exception

virtual const char* what() const throw()

return "exception arised";

} myex;

int main ()

try

throw myex;

catch (exception& e)

cout << e.what() << endl;

return 0;

a) exception arised
b) error
c) exception
d) runtime error
View Answer

Answer: a
Explanation: In this program, We are arising a standard exception and catching that and returning a
statement.
Output:
$ g++ goe.cpp
$ a.out
exception arised

5. What is the output of this program?

#include <iostream>

using namespace std;

int main()

int age=5;

try

if (age < 0)

throw "Positive Number Required";

cout << age << "\n\n";

catch(const char* Message)

cout << "Error: " << Message;

return 0;

a) 5
b) 10
c) 15
d) Positive Number Required
View Answer

Answer: a
Explanation: In this program, We are checking the age of a person, If it is zero means, We will arise a
exception.
Output:
$ g++ goe1.cpp
$ a.out
5

6. What is the output of this program?

#include <iostream>

using namespace std;

double division(int a, int b)

if ( b == 0 )

throw "Division by zero condition!";

return (a / b);

int main ()

int x = 50;

int y = 0;

double z = 0;

try

z = division(x, y);

cout << z << endl;

catch (const char* msg)


{

cout << msg << endl;

return 0;

a) 50
b) 0
c) Division by zero condition!
d) None of the mentioned
View Answer

Answer: c
Explanation: We are dividing the values and if one of the values is zero means, We are arising an
exception.
Output:
$ g++ goe2.cpp
$ a.out
Division by zero condition!

7. What is the output of this program?

#include <iostream>

#include <string>

using namespace std;

int main()

double Op1 = 10, Op2 = 5, Res;

char Op;

try

if (Op != '+' && Op != '-' && Op != '*' && Op != '/')

throw Op;

switch(Op)

case '+':
Res = Op1 + Op2;

break;

case '-':

Res = Op1 - Op2;

break;

case '*':

Res = Op1 * Op2;

break;

case '/':

Res = Op1 / Op2;

break;

cout << "\n" << Op1 << " " << Op << " "<< Op2 << " = " << Res;

catch (const char n)

cout << n << " is not a valid operator";

return 0;

a) 15
b) 5
c) 2
d) is not a valid operator
View Answer

Answer: d
Explanation: It will arise a exception because we missed a operator.
Output:
$ g++ goe3.cpp
$ a.out
is not a valid operator

8. What is the output of this program?


#include<iostream>

#include "math.h"

using namespace std;

double MySqrt(double d)

if (d < 0.0)

throw "Cannot take sqrt of negative number";

return sqrt(d);

int main()

double d = 5;

cout << MySqrt(d) << endl;

a) 5
b) 2.236
c) Error
d) Cannot take sqrt of negative number
View Answer

Answer: b
Explanation: We are finding the square root of the number, if it is a positive number, it can manipulate,
Otherwise it will arise a exception.
Output:
$ g++ goe4.cpp
$ a.out
2.236

9. How to handle the exception in constructor?


a) We have to throw an exception
b) We have to return the exception
c) We have to throw an exception & return the exception
d) none of the mentioned
View Answer

Answer: a
Explanation: As a constructor don’t have a return type, We have to throw the exception.
10. What should present when throwing a object?
a) constructor
b) copy-constructor
c) destructor
d) none of the mentioned
View Answer

Answer: b
Explanation: None.

C++ Programming Questions and Answers – Resource Management


This section on advanced C++ interview questions focuses on “Resource Management”. One shall
practice these advanced C++ 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 advanced C++ questions come with detailed explanation of the answers which helps in
better understanding of C++ concepts.

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

1. What can go wrong in resource management on c++?


a) Leakage
b) Exhaustion
c) Dangling
d) All of the mentioned
View Answer

Answer: d
Explanation: If there is any mishap in memory or resource management means, the problems that are
mentioned above can happen.

2. When we call that resource is leaked?


a) Arise of compile time error
b) It cannot be accessed by any standard mean
c) Arise of runtime error
d) None of the mentioned
View Answer

Answer: b
Explanation: Resource is said to be leaked when it cannot by accessed by any means of standard mean.
3. What kind of error can arise when there is problem in memory?
a) Segmentation fault
b) Produce an error
c) Both Segmentation fault & Produce an error
d) none of the mentioned
View Answer

Answer: a
Explanation: None

4. What is the output of this program?

#include <iostream>

#include <new>

using namespace std;

int main ()

int i, n;

int * p;

i = 2;

p= new (nothrow) int[i];

if (p == 0)

cout << "Error: memory could not be allocated";

else

for (n=0; n<i; n++)

p[n] = 5;

for (n = 0; n < i; n++)

cout << p[n];

delete[] p;

return 0;
}

a) 5
b) 55
c) 555
d) Error: memory could not be allocated
View Answer

Answer: b
Explanation: As we had given i value as 2, It will print the 5 for two times.
Output:
$ g++ res.cpp
$ a.out
55

5. What is the output of this program?

#include <iostream>

using namespace std;

int main(void)

const char *one = "Test";

cout << one << endl;

const char *two = one;

cout << two << endl;

return 0;

a) Test
b) TestTest
c) Te
d) None of the mentioned
View Answer

Answer: b
Explanation: We are copying the values from one variable to other, So it is printing is TestTest
Output:
$ g++ res1.cpp
$ a.out
TestTest
6. What is the output of this program?

#include <iostream>

using namespace std;

int funcstatic(int)

int sum = 0;

sum = sum + 10;

return sum;

int main(void)

int r = 5, s;

s = funcstatic(r);

cout << s << endl;

return 0;

a) 10
b) 15
c) error
d) none of the mentioned
View Answer

Answer: a
Explanation: Eventhough we passed the value, we didn’t caught to manipulate it, So it is printing as 10.
Output:
$ g++ res2.cpp
$ a.out
10

7. What is the output of this program?

#include <iostream>

#include<string.h>

using namespace std;

int main()
{

try

char *p;

strcpy(p, "How r u");

catch(const exception& er)

a) How r u
b) segmentation fault
c) error
d) runtime error
View Answer

Answer: b
Explanation: As we are using a pointer value to copy a string, So it will be producing a runtime error.
Output:
$ g++ res3.cpp
$ a.out
segmentation fault

8. What is meant by garbage collection?


a) Form of manual memory management
b) Form of automatic memory management
c) Used to replace the variables
d) None of the mentioned
View Answer

Answer: b
Explanation: The garbage collectoion attempts to reclaim memory occupied by objects that are no
longer in use by the program.

9. What are the operators available in dynamic memory allocation?


a) new
b) delete
c) compare
d) both new & delete
View Answer

Answer: d
Explanation: new and delete operators are mainly used to allocate and deallocate
during runtime.

10. Which is used to solve the memory management problem in c++?


a) smart pointers
b) arrays
c) stack
d) none of the mentioned
View Answer

Answer: a
Explanation: None.

C++ Programming Questions and Answers – Exceptions That Are Not


Errors
This section on C++ MCQs (multiple choice questions) focuses on “Exceptions That Are Not Errors”. One
shall practice these MCQs 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 multiple choice questions come with detailed explanation of the answers which helps
in better understanding of C++ concepts.

Here is a listing of C multiple choice questions on “Exceptions That Are Not Errors” along with answers,
explanations and/or solutions:

1. Which is used to handle the exceptions in c++?


a) catch handler
b) handler
c) exception handler
d) none of the mentioned
View Answer

Answer: c
Explanation: None.

2. Which type of program is recommended to include in try block?


a) static memory allocation
b) dynamic memory allocation
c) const reference
d) pointer
View Answer

Answer: b
Explanation: While during dynamic memory allocation, Your system may not have sufficient resources to
handle it, So it is better to use it inside the try block.

3. Which statement is used to catch all types of exceptions?


a) catch()
b) catch(Test t)
c) catch(…)
d) none of the mentioned
View Answer

Answer: c
Explanation: This catch statement will catch all types of exceptions that arises in the program.

4. What is the output of this program?

#include <iostream>

using namespace std;

int main()

int x = -1;

try

if (x < 0)

throw x;

else

cout<<x;

catch (int x )
{

cout << "Exception occurred: Thrown value is " << x << endl;

return 0;

a) -1
b) 0
c) Exception occurred: Thrown value is -1
d) Error
View Answer

Answer: c
Explanation: As the given value is -1 and according to the condition, We are arising an exception.
Output:
$ g++ etae.cpp
$ a.out
Exception occurred: Thrown value is -1

5. What is the output of this program?

#include <iostream>

#include <typeinfo>

using namespace std;

class Polymorphic {virtual void Member(){}};

int main ()

try

Polymorphic * pb = 0;

typeid(*pb);

catch (exception& e)

cerr << "exception caught: " << e.what() << endl;

}
return 0;

a) exception caught: std::bad_typeid


b) exception caught: std::bad_alloc
c) exception caught: std::bad_cast
d) none of the mentioned
View Answer

Answer: a
Explanation: In this program, We used a bad type id for the polymorphic operator, So it is arising an
bad_typeid exception.
Output:
$ g++ etae.cpp
$ a.out
exception caught: std::bad_typeid

6. What is the output of this program?

#include <iostream>

#include <exception>

using namespace std;

void myunexpected ()

cout << "unexpected handler called\n";

throw;

void myfunction () throw (int,bad_exception)

throw 'x';

int main (void)

set_unexpected (myunexpected);

try

{
myfunction();

catch (int)

cout << "caught int\n";

catch (bad_exception be)

cout << "caught bad_exception\n";

catch (...)

cout << "caught other exception \n";

return 0;

a) unexpected handler called


b) caught bad_exception
c) caught other exception
d) both unexpected handler called & caught bad_exception
View Answer

Answer: d
Explanation: In this program, We are calling set_unexpected and myfunction, So it is printing the output
as the given.
Output:
$ g++ etae.cpp
$ a.out
unexpected handler called
caught bad_exception

7. What is the output of this program?

#include <iostream>

using namespace std;


int main()

int x = -1;

char *ptr;

ptr = new char[256];

try

if (x < 0)

throw x;

if (ptr == NULL)

throw " ptr is NULL ";

catch (...)

cout << "Exception occurred: exiting "<< endl;

return 0;

a) -1
b) ptr is NULL
c) exception occured: exiting
d) none of the mentioned
View Answer

Answer: c
Explanation: catch(…) is used to catch all types of exceptions arising in the program.
Output:
$ g++ etea.cpp
$ a.out
Exception occured: exiting

8. What is the output of this program?

#include <iostream>

#include <exception>

using namespace std;

void myunexpected ()

cout << "unexpected called\n";

throw 0;

void myfunction () throw (int)

throw 'x';

int main ()

set_unexpected (myunexpected);

try

myfunction();

catch (int)

cout << "caught int\n";

catch (...)

cout << "caught other exception\n";


}

return 0;

a) caught other exception


b) caught int
c) unexpected called
d) both caught int & unexpected called
View Answer

Answer: d
Explanation: As we are calling set_unexpected (myunexpected) function, this is printing as unexpected
called and because of operator compliance it is arising an exception.
Output:
$ g++ etea.cpp
$ a.out
unexpected called
caught int

9. How to handle error in the destructor?


a) throwing
b) terminate
c) both throwing & terminate
d) none of the mentioned
View Answer

Answer: b
Explanation: It will not throw an exception from the destructor but it will the process by using
terminate() function.

10. What kind of exceptions are available in c++?


a) handled
b) unhandled
c) static
d) dynamic
View Answer

Answer: b
Explanation: None.
Advanced C++ Interview Questions - Exception Specifications -
Sanfoundry
by Manish

This section on advanced C++ interview questions focuses on “Exception Specifications”. One
shall practice these advanced C++ 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 advanced C++ questions come with detailed
explanation of the answers which helps in better understanding of C++ concepts.

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

1. What is meant by exception specification?


a) A function is limited to throwing only a specified list of exceptions
b) A catch can catch all types of exceptions
c) A function can throw any type of exceptions
d) None of the mentioned
View Answer

Answer: a
Explanation: C++ provides a mechanism to ensure that a given function is limited to throwing
only a specified list of exceptions. It is called as exception specification.

2. Identify the correct statement about throw(type).


a) A function can throw any type of exceptions
b) A function can throw an exception of certain type only
c) A function can’t throw any type of exception
d) None of the mentioned
View Answer

Answer: b
Explanation: None.

3. What will happen when a programs throws any other type of exception other than specified?
a) terminate
b) arise an error
c) run
d) none of the mentioned
View Answer

Answer: b
Explanation: None.
4. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. void empty() throw()
4. {
5. cout << "In empty()";
6. }
7. void with_type() throw(int)
8. {
9. cout << "Will throw an int";
10. throw(1);
11. }
12. int main()
13. {
14. try
15. {
16. empty();
17. with_type();
18. }
19. catch (int)
20. {
21. cout << "Caught an int";
22. }
23. }

a) In empty()
b) Will throw an int
c) Caught an int
d) All of the mentioned
View Answer

Answer: d
Explanation: It will print all three because we are calling all functions in the main().
Output:
$ g++ exs.cpp
$ a.out
In empty()Will throw an intCaught an int

5. What is the output of this program?

1. #include <iostream>
2. #include <exception>
3. #include <typeinfo>
4. using namespace std;
5. class Test1
6. {
7. virtual int Funct()
8. {
9. }
10. };
11. int main ()
12. {
13. try
14. {
15. Test1 * var = NULL;
16. typeid (*var);
17. }
18. catch (std::exception& typevar)
19. {
20. cout << "Exception: " << typevar.what() << endl;
21. }
22. return 0;
23. }

a) NULL
b) Exception:bad_alloc
c) Exception:std:bad_typeid
d) None of the mentioned
View Answer

Answer: c
Explanation: As we are using a bad type on pointers, So it is arising an error.
Output:
$ g++ exs1.cpp
$ a.out
Exception:std:bad_typeid

6. What is the output of this program?

1. #include <iostream>
2. #include <string>
3. #include<typeinfo>
4. using namespace std;
5. int main( )
6. {
7. try
8. {
9. string strg1("Test");
10. string strg2("ing");
11. strg1.append(strg2, 4, 2);
12. cout << strg1 << endl;
13. }
14. catch (exception &e)
15. {
16. cout << "Caught: " << e.what() << endl;
17. cout << "Type: " << typeid(e).name() << endl;
18. };
19. return 0;
20. }

a) out of range
b) bad type_id
c) bad allocation
d) none of the mentioned
View Answer

Answer: a
Explanation: As we are using out of bound value on strings, So it arising an exception.
Output:
$ g++ exs2.cpp
$ a.out
Caught: basic_string::append
Type: St12out_of_range
#include

7. What is the output of this program?

1. #include <typeinfo>
2. #include <iostream>
3. using namespace std;
4. class Myshape
5. {
6. public:
7. virtual void myvirtualfunc() const {}
8. };
9. class mytriangle: public Myshape
10. {
11. public:
12. virtual void myvirtualfunc() const
13. {
14. };
15. };
16. int main()
17. {
18. Myshape Myshape_instance;
19. Myshape &ref_Myshape = Myshape_instance;
20. try
21. {
22. mytriangle &ref_mytriangle =
dynamic_cast<mytriangle&>(ref_Myshape);
23. }
24. catch (bad_cast)
25. {
26. cout << "Can't do the dynamic_cast lor!!!" << endl;
27. cout << "Caught: bad_cast exception. Myshape is not
mytriangle.\n";
28. }
29. return 0;
30. }

a) Can’t do the dynamic_cast lor!!!


b) Caught: bad_cast exception. Myshape is not mytriangle.
c) Can’t able to create the dynamic instance for the triangle, So it is arising an exception
d) None of the mentioned
View Answer
Answer: c
Explanation: As we can’t able to create the dynamic instance for the triangle, So it is arising an
exception.
Output:
$ g++ exs3.cpp
$ a.out
Can’t do the dynamic_cast lor!!!
Caught: bad_cast exception. Myshape is not mytriangle.

8. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. char* ptr;
6. unsigned long int Test = sizeof(size_t(0) / 3);
7. cout << Test << endl;
8. try
9. {
10. ptr = new char[size_t(0) / 3];
11. delete[ ] ptr;
12. }
13. catch (bad_alloc &thebadallocation)
14. {
15. cout << thebadallocation.what() << endl;
16. };
17. return 0;
18. }

a) 4
b) 2
c) bad_alloc
d) depends on compiler
View Answer

Answer: d
Explanation: The size of unsigned long int always depends on compiler.
Output:
$ g++ exs4.cpp
$ a.out
4

9. What do you mean by “No exception specification”?


a) It throws nothing
b) It can throw anything
c) It can catch anything
d) None of the mentioned
View Answer
Answer: b
Explanation: None.

10. Which operations don’t throw anything?


a) Operations which are reversible
b) Operations which are irreversible
c) Operations which are static
d) Operations which are dynamic
View Answer

Answer: b
Explanation: None.

C++ Programming Questions and Answers – Uncaught Exceptions


This section on C++ programming questions and answers focuses on “Uncaught Exceptions”. One shall
practice these 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++
programming questions come with detailed explanation of the answers which helps in better
understanding of C++ concepts.

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

1. What will happen when an exception is uncaught?


a) arise an error
b) program will run
c) exceute continuously
d) none of the mentioned
View Answer

Answer: a
Explanation: None.

2. Which handler is used to handle all types of exception?


a) catch handler
b) catch-all handler
c) catch-none hendler
d) none of the mentioned
View Answer

Answer: b
Explanation: To catch all types of exceptions, we use catch-all handler.
3. Which operator is used in catch-all handler?
a) ellipses operator
b) ternary operator
c) string operator
d) unary operator
View Answer

Answer: a
Explanation: The ellipses operator can be represented as (…).

4. What is the output of this program?

#include <iostream>

using namespace std;

class Base

protected:

int a;

public:

Base()

a = 34;

Base(int i)

a = i;

virtual ~Base()

if (a < 0) throw a;

virtual int getA()

if (a < 0)
{

throw a;

};

int main()

try

Base b(-25);

cout << endl << b.getA();

catch (int)

cout << endl << "Illegal initialization";

a) Illegal initialization
b) Terminate called after throwing an instance of ‘int’
c) Illegal initialization & terminate called after throwing an instance
d) None of the mentioned
View Answer

Answer: b
Explanation: As we are throwing an negative number and we are using only integer, So it is arising an
error.
Output:
$ g++ uce.cpp
$ a.out
terminate called after throwing an instance of ‘int’

5. What is the output of this program?

#include <iostream>

#include <exception>
using namespace std;

void terminator()

cout << "terminate" << endl;

void (*old_terminate)() = set_terminate(terminator);

class Botch

public:

class Fruit {};

void f()

cout << "one" << endl;

throw Fruit();

~Botch()

throw 'c';

};

int main()

try

Botch b;

b.f();

catch(...)

{
cout << "inside catch(...)" << endl;

a) one
b) inside catch
c) one
terminate
d) one
terminate
Aborted
View Answer

Answer: d
Explanation: This program uses set_terminate as it is having an uncaught exception.
Output:
$ g++ uce1.cpp
$ a.out
one
terminate
Aborted

6. What is the output of this program?

#include <iostream>

#include <exception>

#include <cstdlib>

using namespace std;

void myterminate ()

cerr << "terminate handler called";

abort();

int main (void)

set_terminate (myterminate);

throw 0;
return 0;

a) terminate handler called


b) aborted
c) both terminate handler & Aborted
d) none of the mentioned
View Answer

Answer: c
Explanation: In this program, We are using set_terminate to abort the program.
Output:
$ g++ uce2.cpp
$ a.out
terminate handler called
Aborted

7. What is the output of this program?

#include <iostream>

using namespace std;

class Test1

};

class Test2 : public Test1 { };

void Funct();

int main()

try

Funct();

catch (const Test1&)

cerr << "Caught a exception" << endl;

}
return 0;

void Funct()

throw Test2();

a) Caught an exception
b) NULL
c) Both Caught an exception & NULL
d) None of the mentioned
View Answer

Answer: a
Explanation: In this program, We are arising the exception by using the method in the class.
Output:
$ g++ uce3.cpp
$ a.out
Caught a exception

8. What is the output of this program?

#include <iostream>

using namespace std;

#include <cstdlib>

#include <exception>

void Funct()

cout << "Funct() was called by terminate()." << endl;

exit(0);

int main()

try

set_terminate(Funct);
throw "Out of memory!";

catch(int)

cout << "Integer exception raised." << endl;

return 0;

a) Integer exception raised


b) Funct() was called by terminate()
c) Integer exception not raised
d) none of the mentioned
View Answer

Answer: b
Explanation: As there is no integer in this program, We are printing Funct() was called by terminate().
Output:
$ g++ uce4.cpp
$ a.out
Funct() was called by terminate().

9. What function will be called when we have a uncaught exception?


a) catch
b) throw
c) terminate
d) none of the mentioned
View Answer

Answer: c
Explanation: If we have an uncaught exception means, compiler will throw the control of program to
terminate function.

10. What will not be called when the terminate() is arised in constructor?
a) main()
b) class
c) destructor
d) none of the mentioned
View Answer
Answer: c
Explanation: None.

C++ Test - Exceptions and Efficiency - Sanfoundry


by Manish

This section on C++ test focuses on “Exceptions and Efficiency”. One shall practice these test
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++ test questions come with detailed explanation of the answers which
helps in better understanding of C++ concepts.

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

1. What will happen when we move try block far away from catch block?
a) Reduces the amount of code in cache
b) Increases the amount of code in cache
c) Don’t alter anything
d) None of the mentioned
View Answer

Answer: a
Explanation: compilers may try to move the catch-code far away from the try-code, which
reduces the amount of code to keep in cache normally, thus enhancing performance.

2. What will happen if an excpetion that is thrown may causes a whole load of objects to go out
of scope?
a) Terminate the program
b) Produce a runtime error
c) It will be added to the overhead
d) None of the mentioned
View Answer

Answer: c
Explanation: None.

3. What operation can be performed by destructor?


a) Abort the program
b) Resource cleanup
c) Exit from the current block
d) None of the mentioned
View Answer
Answer: b
Explanation: It will be used to free all the resources that are used by block of code during
execution.

4. What is the output of this program?

1. #include <iostream>
2. #include <exception>
3. using namespace std;
4. int main ()
5. {
6. try
7. {
8. double* i= new double[1000];
9. cout << "Memory allocated";
10. }
11. catch (exception& e)
12. {
13. cout << "Exception arised: " << e.what() << endl;
14. }
15. return 0;
16. }

a) Memory allocated
b) Exception arised
c) Depends on the computer memory
d) None of the mentioned
View Answer

Answer: c
Explanation: The value will be allocated, if there is enough memory in the system.
Output:
$ g++ expef.cpp
$ a.out
Memory allocated

5. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. void test(int x)
4. {
5. try
6. {
7. if (x > 0)
8. throw x;
9. else
10. throw 'x';
11. }
12. catch(char)
13. {
14. cout << "Catch a integer and that integer is:" << x;
15. }
16. }
17. int main()
18. {
19. cout << "Testing multiple catches\n:";
20. test(10);
21. test(0);
22. }

a) Catch a integer and that integer is:10


b) Error
c) Runtime error
d) None of the mentioned
View Answer

Answer: c
Explanation: As the catch is created with a wrong type, So it will
arise a runtime error.
Output:
$ g++ expef.cpp
$ a.out
Testing multiple catches
terminate called after throwing an instance of ‘int’
:Aborted

6. What is the output of this program?

1. #include <stdexcept>
2. #include <limits>
3. #include <iostream>
4. using namespace std;
5. void func(int c)
6. {
7. if (c < numeric_limits<char> :: max())
8. throw invalid_argument("MyFunc argument too large.");
9. else
10. {
11. cout<<"Executed";
12. }
13. }
14. int main()
15. {
16. try
17. {
18. func(256);
19. }
20. catch(invalid_argument& e)
21. {
22. cerr << e.what() << endl;
23. return -1;
24. }
25. return 0;
26. }

a) Invalid arguments
b) Executed
c) Error
d) Runtime error
View Answer

Answer: b
Explanation: As we are throwing the function and catching it with a correct data type, So this
program will execute.
Output:
$ g++ expef.cpp
$ a.out
Executed

7. What is the output of this program?

1. #include <iostream>
2. #include <string>
3. using namespace std;
4. int main ()
5. {
6. int num = 3;
7. string str_bad = "wrong number used";
8. try
9. {
10. if ( num == 1 )
11. {
12. throw 5;
13. }
14. if ( num == 2 )
15. {
16. throw 1.1f;
17. }
18. if ( num != 1 || num != 2 )
19. {
20. throw str_bad;
21. }
22. }
23. catch (int a)
24. {
25. cout << "Exception is: " << a << endl;
26. }
27. catch (float b)
28. {
29. cout << "Exception is: " << b << endl;
30. }
31. catch (...)
32. {
33. cout << str_bad << endl;
34. }
35. return 0;
36. }

a) Exception is 5
b) Exception is 1.1f
c) Wrong number used
d) None of the mentioned
View Answer

Answer: c
Explanation: As we are giving 3 to num, It is arising an exception named
“wrong number used”.
Output:
$ g++ expef.cpp
$ a.out
wrong number used

8. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. double division(int a, int b)
4. {
5. if (b == 0)
6. {
7. throw "Division by zero condition!";
8. }
9. return (a / b);
10. }
11. int main ()
12. {
13. int x = 50;
14. int y = 0;
15. double z = 0;
16. try
17. {
18. z = division(x, y);
19. cout << z << endl;
20. }
21. catch (const msg)
22. {
23. cerr << msg << endl;
24. }
25. return 0;
26. }

a) 50
b) 0
c) Division by zero condition
d) Error
View Answer
Answer: d
Explanation: As we missed the data type in the catch block, It will arise an error.

9. What is the main purpose of the constructor?


a) Begin the execution of the class
b) Include the macros for the program
c) Establish the class invariant
d) None of the mentioned
View Answer

Answer: c
Explanation: The purpose of a constructor is to establish the class invariant. To do that, it often
needs to acquire system resources or in general perform an operation that may fail.

10. Why is it expensive to use objects for exception?


a) Exception object is created only if an error actually happens
b) Because of execution time
c) Memory space involved in creating an exception object
d) None of the mentioned
View Answer

Answer: a
Explanation: If an error occurs in program, then only exception object is created otherwise, It
will not be created. So it’s expensive to use in the program.

C++ Programming Interview Questions - Error Handling Alternatives -


Sanfoundry
by Manish

This section on C++ programming interview questions and answers focuses on “Error Handling
Alternatives”. 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++ programming
interview questions come with detailed explanation of the answers which helps in better
understanding of C++ concepts.

Here is a listing of C++ programming interview questions on “Error Handling Alternatives”


along with answers, explanations and/or solutions:

1. Which alternative can replace the throw statement?


a) for
b) break
c) return
d) exit
View Answer

Answer: c
Explanation: throw and return does the same job like return a value. So it can be replaced.

2. What are the disadvantages if use return keyword to return error codes?
a) You have to handle all exceptional cases explicitly
b) Your code size increases dramatically
c) The code becomes more difficult to read
d) All of the mentioned
View Answer

Answer: d
Explanation: As we are using return for each and every exception, It will definetly increase the
code size.

3. What is most suitable for returning the logical errors in the program?
a) Use contructor and destructor
b) Set a global error indicator
c) Use break keyword
d) None of the mentioned
View Answer

Answer: b
Explanation: None.

4. What is the output of this program?

1. #include <iostream>
2. #include <typeinfo>
3. using namespace std;
4. class A
5. {
6. };
7. int main()
8. {
9. char c; float x;
10. if (typeid(c) != typeid(x))
11. cout << typeid(c).name() << endl;
12. cout << typeid(A).name();
13. return 0;
14. }

a) c
1A
b) x
c) Both c & x
d) None of the mentioned
View Answer

Answer: a
Explanation: We are checking the type id of char and float as they are not equal, We are printing
c.
Output:
$ g++ eal.cpp
$ a.out
c
1A

5. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. void Division(const double a, const double b);
4. int main()
5. {
6. double op1=0, op2=10;
7. try
8. {
9. Division(op1, op2);
10. }
11. catch (const char* Str)
12. {
13. cout << "\nBad Operator: " << Str;
14. }
15. return 0;
16. }
17. void Division(const double a, const double b)
18. {
19. double res;
20. if (b == 0)
21. throw "Division by zero not allowed";
22. res = a / b;
23. cout << res;
24. }

a) 0
b) Bad operator
c) 10
d) None of the mentioned
View Answer

Answer: a
Explanation: We are dividing 0 and 10 in this program and we are using the throw statement in
the function block.
Output:
$ g++ eal.cpp
$ a.out
0

6. What is the output of this program?

1. #include <stdexcept>
2. #include <limits>
3. #include <iostream>
4. using namespace std;
5. void MyFunc(char c)
6. {
7. if (c < numeric_limits<char>::max())
8. return invalid_argument;
9. }
10. int main()
11. {
12. try
13. {
14. MyFunc(256);
15. }
16. catch(invalid_argument& e)
17. {
18. cerr << e.what() << endl;
19. return -1;
20. }
21. return 0;
22. }

a) 256
b) Invalid argument
c) Error
d) None of the mentioned
View Answer

Answer: c
Explanation: We can’t return a statement by using the return keyword, So it is arising an error.

7. What is the use of RAII in c++ programing?


a) Improve the exception safety
b) Terminate the program
c) Exit from the block
d) None of the mentioned
View Answer

Answer: a
Explanation: None.

8. How many levels are there in exception safety?


a) 1
b) 2
c) 3
d) 4
View Answer

Answer: c
Explanation: The three levels of exception safety are basic, strong and nothrow.

9. Pick out the correct statement for error handling alternatives.


a) Terminate the program
b) Use the stack
c) Exit from the block
d) None of the mentioned
View Answer

Answer: b
Explanation: When an error is arised means, it will be pushed into stack and it can be corrected
later by the programmer.

10. What will happen when an exception is not processed?


a) It will eat up lot of memory and program size
b) Terminate the program
c) Crash the compiler
d) None of the mentioned
View Answer

Answer: a
Explanation: As in the case of not using an exception, it will remain useless in the program and
increase the code complexity.

C++ Programming Questions and Answers – Standard Exceptions


This section on C++ problems focuses on “Standard Exceptions”. One shall practice these problems to
improve their C++ programming skills needed for various interviews (campus interviews, walkin
interviews, company interviews), placements, entrance exams and other competitive exams. These
problems 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++ problems come with
detailed explanation of the answers which helps in better understanding of C++ concepts.

Here is a listing of C++ problems on “Standard Exceptions” along with answers, explanations and/or
solutions:

1. Which header file is used to declare the standard exception?

a) #include<exception>

b) #include<except>
c) #include<error>

d) none of the mentioned

View Answer

Answer: a
Explanation: None.

2. Where are standard exception classes grouped?


a) namespace std
b) error
c) catch
d) none of the mentioned
View Answer

Answer: a
Explanation: As these are standard exceptions, they need to be defined in the standard block, So it is
defined under namespace std.

3. How many types of standard exception are there in c++?


a) 9
b) 5
c) 6
d) 7
View Answer

Answer: a
Explanation: There are nine standard exceptions in c++. They are bad_alloc, bad_cast, bad_exception,
bad_function_call, bad_typeid, bad_weak_ptr, ios_base::failure, logic_error and runtime_error.

4. What is the output of this program?

#include <iostream>

#include <exception>

using namespace std;

class myexc: public exception

virtual const char* what() const throw()

return "My exception";

}
} myex;

int main ()

try

throw myex;

catch (exception& e)

cout << e.what() << endl;

return 0;

a) My
b) My exception
c) No exception
d) None of the mentioned
View Answer

Answer: b
Explanation: This is a type of exception arising in the class. We can call this
also as a standard exception.
Output:
$ g++ std.cpp
$ a.out
My exception

5. What is the output of this program?

#include <iostream>

#include <exception>

using namespace std;

int main ()

try
{

int* myarray= new int[1000];

cout << "Allocated";

catch (exception& e)

cout << "Standard exception: " << e.what() << endl;

return 0;

a) Allocated
b) Standard exception:
c) bad_alloc
d) Depends on memory
View Answer

Answer: d
Explanation: Variable will be allocated depends on the available space in the memory, If there is no
space means, It will throw an exception.
Output:
$ g++ std1.cpp
$ a.out
Allocated

6. What is the output of this program?

#include <iostream>

using namespace std;

int main()

char* ptr;

unsigned long int a = (size_t(0) / 3);

cout << a << endl;

try

{
ptr = new char[size_t(0) / 3];

delete[ ] ptr;

catch(bad_alloc &thebadallocation)

cout << thebadallocation.what() << endl;

};

return 0;

a) 0
b) 2
c) bad_alloc
d) depends on compiler
View Answer

Answer: a
Explanation: As we are dividing the zero by three, it is returning 0.
Output:
$ g++ std2.cpp
$ a.out
0

7. What is the output of this program?

#include <typeinfo>

#include <iostream>

using namespace std;

class shape

public:

virtual void myvirtualfunc() const {}

};

class mytriangle: public shape

public:
virtual void myvirtualfunc() const

};

};

int main()

shape shape_instance;

shape &ref_shape = shape_instance;

try

mytriangle &ref_mytriangle = dynamic_cast<mytriangle&>(ref_shape);

catch (bad_cast)

cout << "Caught: bad_cast exception\n";

return 0;

a) Caught standard exception


b) No exception arises
c) Caught: bad_cast exception
d) None of the mentioned
View Answer

Answer: c
Explanation: As we are not able to allocate the values by using dynamic cast,
So it is arising an exception.
Output:
$ g++ std3.cpp
$ a.out
Caught: bad_cast exception

8. What is the output of this program?

#include <typeinfo>
#include <iostream>

using namespace std;

class Test

public:

Test();

virtual ~Test();

};

int main()

Test *ptrvar = NULL;

try

cout << typeid(*ptrvar).name() << endl;

catch (bad_typeid)

cout << "The object is null" << endl;

return 0;

a) No exception arises
b) The object is null
c) Error
d) None of the mentioned
View Answer

Answer: b
Explanation: As there is no object in the class, It is arising an exception in the program.
Output:
$ g++ std4.cpp
$ a.out
The object is null
9. Which of the following is best to include under try block?
a) static values
b) const values
c) dynamic allocations
d) none of the mentioned
View Answer

Answer: c
Explanation: Because the dynamic allocations can change at any time, So it is best to include in try block.

10. What are the perdefined exceptions in c++?


a) Memory allocation errors
b) I/O errors
c) Both Memory allocation errors & I/O errors
d) None of the mentioned
View Answer

Answer: c
Explanation: None.

Das könnte Ihnen auch gefallen