Derived exception does not inherit constructors

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;
}
Line

throw MyException("fatal error");does not work. Microsoft Visual Studio 2012 says the following:

error C2440: '<function-style-cast>' : cannot convert from 'const char [12]' to 'MyException'

MinGW's reaction was very similar.

This means that the constructor was std::logic_error(const string &what)not copied from the parent class to the child. Why?

Thanks for your reply.

+5
source share
1 answer

The following constructors is a C ++ 11 function that is not available in C ++ 03 (which you seem to be using, as I can tell from the specifications of dynamic exceptions).

However, even in C ++ 11, you will need an declaration usingto inherit the constructor of the base class:

class MyException : public std::logic_error {
public:
    using std::logic_error::logic_error;
};

, std::string const char* :

class MyException : public std::logic_error {
public:
    MyException(std::string const& msg) : std::logic_error(msg) { }
};
+7

All Articles