J
Josefo
Hello. Here I am again trying to understand the examples of a C++
tutorial. When compiling the original source code:
// standard exceptions
#include <iostream>
#include <exception>
using namespace std;
class myexception: public exception
{
// virtual const char* what() const
char* what()
{
return "My exception happened";
}
} myex;
int main () {
try
{
throw myex;
}
catch (exception& e)
{
cout << e.what() << endl;
}
return 0;
}
I get this:
11myexception
which obviously is not the desired answer. I modified slightly the
code, just writing as type of the argument of the "catch" function the
derived class (myexception) , instead the "parent" one (exception) in
which case I am forced to declare the object function "what" as
public (reason for the difference with respect to the former case ???):
// standard exceptions
#include <iostream>
#include <exception>
using namespace std;
class myexception: public exception
{
// virtual const char* what() const
public:
char* what()
{
return "My exception happened";
}
} myex;
int main () {
try
{
throw myex;
}
catch (myexception& e)
{
cout << e.what() << endl;
}
return 0;
}
Now I get the right answer:
My exception happened
Can someone explain to me the reason of this. I would rather expect
that the type of the parent class could be used for the argument of the
calling function . Or not?
regards
tutorial. When compiling the original source code:
// standard exceptions
#include <iostream>
#include <exception>
using namespace std;
class myexception: public exception
{
// virtual const char* what() const
char* what()
{
return "My exception happened";
}
} myex;
int main () {
try
{
throw myex;
}
catch (exception& e)
{
cout << e.what() << endl;
}
return 0;
}
I get this:
11myexception
which obviously is not the desired answer. I modified slightly the
code, just writing as type of the argument of the "catch" function the
derived class (myexception) , instead the "parent" one (exception) in
which case I am forced to declare the object function "what" as
public (reason for the difference with respect to the former case ???):
// standard exceptions
#include <iostream>
#include <exception>
using namespace std;
class myexception: public exception
{
// virtual const char* what() const
public:
char* what()
{
return "My exception happened";
}
} myex;
int main () {
try
{
throw myex;
}
catch (myexception& e)
{
cout << e.what() << endl;
}
return 0;
}
Now I get the right answer:
My exception happened
Can someone explain to me the reason of this. I would rather expect
that the type of the parent class could be used for the argument of the
calling function . Or not?
regards