Derived Classes, Templates & Exception Handling in C++
Derived Classes, Templates & Exception Handling in C++
Derived Classes, Templates & Exception Handling in C++
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:
Answer: b
Explanation: Because derived inherits functions and variables from base.
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.
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
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.
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
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.
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:
Answer: a
Explanation: None.
Answer: b
Explanation: For making a method as pure virtual function, We have to append ‘=0’ to the class
or method.
Answer: b
Explanation: Classes that contain at least one pure virtual function are called as abstract base
classes.
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 = ▭
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
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
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
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
Answer: a
Explanation: None.
Answer: a
Explanation: None.
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.
Answer: a
Explanation: None.
Answer: b
Explanation: Class hierarchies promote reuse in two ways. They are code sharing and interface
sharing.
Answer: c
Explanation: There are three types of classes. They are abstract base classes, concrete derived
classes, standalone classes.
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
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
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
Answer: b
Explanation: None.
Answer: c
Explanation: None.
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:
Answer: b
Explanation: There are two kinds of classes in c++. They are absolute class and concrete class.
Answer: a
Explanation: Polymirphism is literally means class having many forms.
Answer: d
Explanation: There are five types of inheritance in c++. They are single, Multiple, Hierarchical,
Multilevel, Hybrid.
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
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
Answer: a
Explanation: None.
Answer: c
Explanation: There are three types of constructor in C++. They are Default constructor,
Parameterized constructor, Copy constructor.
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.
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.
Answer: c
Explanation: None.
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
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
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
Answer: b
Explanation: There are two types of templates. They are function template and class template.
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.
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.
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:
Answer: b
Explanation: During runtime, We can choose the appropriate type for the function
and it is called as template type parameters.
Answer: a
Explanation: Because of template type parameters, It will work with many types and saves a lot
of time.
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
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
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
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
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
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.
Answer: c
Explanation: None.
Here is a listing of C multiple choice questions on “Template Arguments to Specify Policy Usage” along
with answers, explanations and/or solutions:
Answer: a
Explanation: A template parameter is a special kind of parameter that can be used to pass a type as
argument.
Answer: c
Explanation: None.
Answer: a
Explanation: None.
#include <iostream>
class mysequence
{
T memblock [N];
public:
};
memblock[x] = value;
return memblock[x];
int main ()
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
#include <iostream>
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);
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
#include <iostream>
class Test
public:
Test()
};
~Test()
};
return Var1;
return Var2;
};
int main()
Test<int> Var1;
Test<double> Var2;
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
#include <iostream>
void loopIt(T x)
T val[count];
val[ii] = x++;
};
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
Answer: c
Explanation: It is used to adapt a policy into binary ones.
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.
Here is a listing of C++ interview questions on “Specialization ” along with answers, explanations and/or
solutions:
Answer: a
Explanation: In the template specialization, it will make the template to be specific for some data types.
Answer: c
Explanation: None
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.
#include <iostream>
inline T square(T x)
T result;
result = x * x;
return result;
};
template <>
return (ss+ss);
};
int main()
{
int i = 2, ii;
string ww("A");
ii = square<int>(i);
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
#include <iostream>
T multIt(T x)
x = x * x;
return x;
};
int main()
{
float xx = 2.1;
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
#include <iostream>
class XYZ
public:
void putPri();
static T ipub;
private:
static T ipri;
};
void XYZ<T>::putPri()
}
template <class T> T XYZ<T>::ipub = 1;
int main()
XYZ<int> a;
XYZ<float> b;
a.putPri();
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
#include <iostream>
#include <string>
#include <cstring>
template <>
int main()
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
#include <iostream>
public:
A();
int value;
};
public: A();
};
public: A();
};
A<>::A()
A<double, 10>::A()
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
Answer: b
Explanation: There are two types specialization. They are full specialization and partial specialization.
Answer: a
Explanation: None
Here is a listing of advanced C++ interview questions on “Derivation and Templates” along with answers,
explanations and/or solutions:
Answer: a
Explanation: None
Answer: b
Explanation: We can place the default type values in a base class and overriding some of them through
derivation.
Answer: d
Explanation: classes that contain only type members, nonvirtual function members, and static data
members do not require memory at run time.
#include <iostream>
public:
virtual ~class0(){}
protected:
char p;
public:
char getChar();
};
public:
void printChar();
};
void class1::printChar()
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
#include <iostream>
public:
T value;
clsTemplate(T i)
this->value = i;
void test()
};
public:
clsChild(): clsTemplate<char>( 0 )
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
#include <iostream>
class A
{
public:
protected:
int x;
};
public:
B(): A<char>::A(100)
};
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
class Test
public:
Test();
~Test();
type Data(type);
};
return Var0;
Test<type>::Test()
Test<type>::~Test()
int main(void)
Test<char> Var3;
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
#include <iostream>
class Base
public:
Base ( )
~Base ( )
};
public:
Derived ( )
~Derived ( )
};
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
Answer: c
Explanation: C++ allows us to parameterize directly three kinds of entities through templates: types,
constants, and templates.
Answer: c
Explanation: There are three kinds of parameters are there in C++. They are type, non-type, template.
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:
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.
Answer: a
Explanation: None.
Answer: b
Explanation: finally keyword will be executed at the end of all the exception.
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!
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
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
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
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
Answer: a
Explanation: None.
Answer: a
Explanation: bad_cast exception is thrown by dynamic_cast.
Here is a listing of C++ test questions on “Grouping of Exceptions” along with answers, explanations
and/or solutions:
Answer: b
Explanation: There are two types of exception handling in c++. They are synchronous exception handling
and asynchronous exception handling.
Answer: b
Explanation: There are four runtime error messages associated with exceptions.They are
overflow_error, range_error, system_error and underflow_error.
Answer: a
Explanation: None.
#include <iostream>
int main()
try
if (b == 0)
res = a / b;
cout << a << " / " << b << " = " << res;
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
#include <iostream>
int main()
try
throw 1;
catch (int a)
return 0;
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
#include <iostream>
int main()
float d;
try
if ((a - b) != 0)
d = c / (a - b);
cout << d;
else
throw(a - b);
catch (int 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
#include <iostream>
void test(int x)
try
if (x > 0)
throw x;
else
throw 'x';
catch(int x)
cout<<"integer:"<<x;
catch(char 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
#include <iostream>
int Num;
Num = 1;
while (true)
throw Num;
Num++;
int main(void)
{
try
PrintSequence(2);
catch(int ExNum)
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
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.
Answer: c
Explanation: None.
Here is a listing of C++ programming interview questions on “Catching Exceptions” along with answers,
explanations and/or solutions:
Answer: a
Explanation: In c++ program, We can be able to throw only one error at a time.
Answer: b
Explanation: none
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.
#include <iostream>
#include <exception>
} myex;
int main ()
try
throw myex;
catch (exception& e)
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
#include <iostream>
int main()
int age=5;
try
if (age < 0)
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
#include <iostream>
if ( b == 0 )
return (a / b);
int main ()
int x = 50;
int y = 0;
double z = 0;
try
z = division(x, y);
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!
#include <iostream>
#include <string>
int main()
char Op;
try
throw Op;
switch(Op)
case '+':
Res = Op1 + Op2;
break;
case '-':
break;
case '*':
break;
case '/':
break;
cout << "\n" << Op1 << " " << Op << " "<< Op2 << " = " << Res;
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
#include "math.h"
double MySqrt(double d)
if (d < 0.0)
return sqrt(d);
int main()
double d = 5;
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
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.
Here is a listing of advanced C++ interview questions on “Resource Management” along with answers,
explanations and/or solutions:
Answer: d
Explanation: If there is any mishap in memory or resource management means, the problems that are
mentioned above can happen.
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
#include <iostream>
#include <new>
int main ()
int i, n;
int * p;
i = 2;
if (p == 0)
else
p[n] = 5;
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
#include <iostream>
int main(void)
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>
int funcstatic(int)
int sum = 0;
return sum;
int main(void)
int r = 5, s;
s = funcstatic(r);
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
#include <iostream>
#include<string.h>
int main()
{
try
char *p;
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
Answer: b
Explanation: The garbage collectoion attempts to reclaim memory occupied by objects that are no
longer in use by the program.
Answer: d
Explanation: new and delete operators are mainly used to allocate and deallocate
during runtime.
Answer: a
Explanation: None.
Here is a listing of C multiple choice questions on “Exceptions That Are Not Errors” along with answers,
explanations and/or solutions:
Answer: c
Explanation: None.
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.
Answer: c
Explanation: This catch statement will catch all types of exceptions that arises in the program.
#include <iostream>
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
#include <iostream>
#include <typeinfo>
int main ()
try
Polymorphic * pb = 0;
typeid(*pb);
catch (exception& e)
}
return 0;
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
#include <iostream>
#include <exception>
void myunexpected ()
throw;
throw 'x';
set_unexpected (myunexpected);
try
{
myfunction();
catch (int)
catch (...)
return 0;
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
#include <iostream>
int x = -1;
char *ptr;
try
if (x < 0)
throw x;
if (ptr == NULL)
catch (...)
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
#include <iostream>
#include <exception>
void myunexpected ()
throw 0;
throw 'x';
int main ()
set_unexpected (myunexpected);
try
myfunction();
catch (int)
catch (...)
return 0;
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
Answer: b
Explanation: It will not throw an exception from the destructor but it will the process by using
terminate() function.
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:
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.
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
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
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
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. }
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
Answer: b
Explanation: None.
Here is a listing of C++ programming questions on “Uncaught Exceptions” along with answers,
explanations and/or solutions:
Answer: a
Explanation: None.
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 (…).
#include <iostream>
class Base
protected:
int a;
public:
Base()
a = 34;
Base(int i)
a = i;
virtual ~Base()
if (a < 0) throw a;
if (a < 0)
{
throw a;
};
int main()
try
Base b(-25);
catch (int)
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’
#include <iostream>
#include <exception>
using namespace std;
void terminator()
class Botch
public:
void f()
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
#include <iostream>
#include <exception>
#include <cstdlib>
void myterminate ()
abort();
set_terminate (myterminate);
throw 0;
return 0;
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
#include <iostream>
class Test1
};
void Funct();
int main()
try
Funct();
}
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
#include <iostream>
#include <cstdlib>
#include <exception>
void Funct()
exit(0);
int main()
try
set_terminate(Funct);
throw "Out of memory!";
catch(int)
return 0;
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().
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.
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.
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
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. }
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
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
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
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.
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.
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.
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.
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.
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
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
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.
Answer: a
Explanation: None.
Answer: c
Explanation: The three levels of exception safety are basic, strong and nothrow.
Answer: b
Explanation: When an error is arised means, it will be pushed into stack and it can be corrected
later by the programmer.
Answer: a
Explanation: As in the case of not using an exception, it will remain useless in the program and
increase the code complexity.
Here is a listing of C++ problems on “Standard Exceptions” along with answers, explanations and/or
solutions:
a) #include<exception>
b) #include<except>
c) #include<error>
View Answer
Answer: a
Explanation: None.
Answer: a
Explanation: As these are standard exceptions, they need to be defined in the standard block, So it is
defined under namespace std.
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.
#include <iostream>
#include <exception>
}
} myex;
int main ()
try
throw myex;
catch (exception& e)
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
#include <iostream>
#include <exception>
int main ()
try
{
catch (exception& e)
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
#include <iostream>
int main()
char* ptr;
try
{
ptr = new char[size_t(0) / 3];
delete[ ] ptr;
catch(bad_alloc &thebadallocation)
};
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
#include <typeinfo>
#include <iostream>
class shape
public:
};
public:
virtual void myvirtualfunc() const
};
};
int main()
shape shape_instance;
try
catch (bad_cast)
return 0;
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
#include <typeinfo>
#include <iostream>
class Test
public:
Test();
virtual ~Test();
};
int main()
try
catch (bad_typeid)
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.
Answer: c
Explanation: None.