Search code examples
c++default-constructor

Why does the compiler look for a default constructor for my exception class?


I've defined a small exception hierarchy for my library. It inherits from std::runtime_error, like this:

class library_exception : public std::runtime_error {
    using std::runtime_error::runtime_error;
};

class specific_exception : public library_exception {
    int guilty_object_id;

    specific_exception(int guilty_object_id_)
        : guilty_object_id(guilty_object_id_) {}
};

The compiler says:

error: call to implicitly-deleted default constructor of 'library_exception'

and points to the specific_exception constructor.

Why is it trying to call the default constructor here?


Solution

  • library_exception inherits from std::runtime_error. The latter does not have a default constructor, which means the former isn't default constructable.

    Similarly, specific_exception isn't default constructable because its base class isn't. You need a default constructor for the base here because the base is implicitly initialized:

    specific_exception(int guilty_object_id_)
        : guilty_object_id(guilty_object_id_) {}
    

    To fix this, call the appropriate base class constructor:

    specific_exception(int guilty_object_id_)
        : library_exception("hello, world!"),
          guilty_object_id(guilty_object_id_) {}