Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 751
Artur Iwan Avatar asked Apr 13 '13 11:04

Artur Iwan


People also ask

Do derived classes inherit constructors?

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.

Why are constructors not inherited?

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.

Which constructor Cannot inherit?

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.

Can we inherit constructor in C++?

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.


1 Answers

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) { }
};
like image 153
Andy Prowl Avatar answered Oct 12 '22 12:10

Andy Prowl