You get this output because in the first case you create a new std::exception
object, and in the second - new std::bad_alloc
object. Instead of this you should catch exceptions by reference. The following code should show the difference:
#include <iostream>
#include <string>
class Foo
{
public:
Foo()
{
// std::cout << "Foo()" << std::endl;
}
Foo(const Foo&)
{
std::cout << "Foo(const Foo&)" << std::endl;
}
virtual ~Foo()
{
}
virtual std::string what() const
{
return "what: Foo";
}
};
class Bar: public Foo
{
public:
Bar()
{
// std::cout << "Bar()" << std::endl;
}
Bar(const Bar&)
{
std::cout << "Bar(const Bar&)" << std::endl;
}
std::string what() const
{
return "what: Bar";
}
};
int main()
{
try
{
throw Bar();
}
catch(Foo f)
{
std::cout << f.what() << std::endl;
}
try
{
throw Bar();
}
catch(const Foo& f)
{
std::cout << f.what() << std::endl;
}
return 0;
}
The output is
Foo(const Foo&)
what: Foo
what: Bar
But I don't have VS11, so I can't tell you, why is VS produces such an output. It will be nice if someone would clarify this.
Thanks to @BoPersson:
The different message in the OP's case is because VC++ implements what() by storing the message text in the exception base class. Other implementations do not.