0
votes

I was going through the differnce between catch by value/refrence in Exception handling in c++

Came across this blog https://blog.knatten.org/2010/04/02/always-catch-exceptions-by-reference/

Tried the same and i am not getting the expected output.

#include<iostream> 
using namespace std;
#include <typeinfo>

class Base {}; 
class Derived: public Base {}; 
int main() 
{ 

try 
{ 
throw Derived();
} 

catch(Base &b) 
{ 
cout<<typeid(b).name();
} 

return 0; 
}  

The output i am getting is: 4Base
As i am catching by refrence the typeid(b).name() must capture Derived ? or am i doing any thing wrong?

1
try to add a virtual function to the base - Alexander
The problem is that Base and Derived are not polymorphic types. Add some virtual functions (like a virtual destructor) and it should work better. - Some programmer dude

1 Answers

1
votes

destructor of the base class has to be virtual.

output is "7Derived"

#include<iostream> 
#include <typeinfo>

using namespace std;

class Base {
public:
    virtual ~Base(){};
}; 
class Derived: public Base {}; 

int main() 
{ 

    try 
    { 
        throw Derived();
    } 

    catch(Base &b) 
    { 
        cout<<typeid(b).name();
    } 

    return 0; 
}