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.
In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
A parent class constructor is not inherited in child class and this is why super() is added automatically in child class constructor if there is no explicit call to super or this.
Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes. The constructors of inherited classes are called in the same order in which they are inherited.
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) { }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With