Reputation: 1210
I have a problem with the code below.
#include <iostream>
#include <stdexcept>
class MyException : public std::logic_error {
};
void myFunction1() throw (MyException) {
throw MyException("fatal error");
};
void myFunction2() throw (std::logic_error) {
throw std::logic_error("fatal error");
};
int main() {
try {
myFunction1();
//myFunction2();
}catch (std::exception &e) {
std::cout << "Error.\n"
<< "Type: " << typeid(e).name() << "\n"
<< "Message: " << e.what() << std::endl;
}
return 0;
}
throw MyException("fatal error");
line does not work. Microsoft Visual Studio 2012 says this:
error C2440: '<function-style-cast>' : cannot convert from 'const char [12]' to 'MyException'
MinGW's reaction was very similar.
It means, that the constructor std::logic_error(const string &what)
was not copied from the parent class into the child. Why?
Thanks for your answer.
Upvotes: 5
Views: 2439
Reputation: 126522
Inheriting constructors is a C++11 feature which is not available in C++03 (which you seem to be using, as I can tell from the dynamic exception specifications).
However, even in C++11 you would need a using
declaration to inherit a base class's constructor:
class MyException : public std::logic_error {
public:
using std::logic_error::logic_error;
};
In this case, you just have to write explicitly a constructor that takes an std::string
or a const char*
and forwards it to the base class's constructor:
class MyException : public std::logic_error {
public:
MyException(std::string const& msg) : std::logic_error(msg) { }
};
Upvotes: 8