Search code examples
c++oopinheritancedefault-constructor

The default constructor in an child of std::runtime_error


I have two exception classes that inherit from std::runtime_error. The first one, AError, works just fine.

class AError : public std::runtime_error {
public:
    const char* what() const noexcept
    {
        return "Error of type A!";
    }
};

The second one, BError, does not compile because std::runtime_error does not have a default constructor.

class BError : public std::runtime_error {
public:
    const int num_;

    BError(int n) : num_(n) {}; // ERROR: no default constructor for runtime_error

    const char* what() const noexcept
    {
        return "Error of type B!";
    }
};

It seems to me that AError should not compile because the default constructor of AError should call the default constructor of std::runtime_error in the default constructor AError. What is happening in the default constructor of AError that allows that example to compile?


Solution

  • It seems to me that AError should not compile because the default constructor of AError should call the default constructor of std::runtime_error in the default constructor AError.

    The default ctor of AError is deleted because it inherits from a class that has no default ctor. try the following and the code won't compile

    AError er;