What happens when this C++ program is compiled? [code] #include <iostream> #include <string> #include <cstdlib> using namespace std; class

Stasenndb

New member
What happens when this C++ program is compiled?
Code:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class A
{
	int a;
    public:
	A(){}
};
class B: public A
{
	int b;
    public:
	B(){}
};
void func()
{
	B b;
	throw b;
}
int main()
{
	try{
		func();
	}
	catch(A a){
		cout<<"Caught A Class\n";
	}
	catch(B b){
		cout<<"Caught B Class\n";
	}
}
A. The program compiles successfully without any errors or warnings
B. Compile-time error occurs
C. The program compiles successfully with warnings
D. The program gives both errors and warnings
 
Answer: c
Explanation: Catch block of derived should always be placed before the catch block base class, hence the program gives warnings stating that exceptions of the derived class will be caught by the base class.
Output:
$ g++ check.cpp
check.cpp: In function ‘int main()’:
check.cpp:33:2: warning: exception of type ‘B’ will be caught
catch(B b){
^~~~~
check.cpp:30:2: warning: by earlier handler for ‘A’
catch(A a){
^~~~~
 

Tìm kiếm

Back
Top