Search code examples
c++inheritanceruntime-error

How to inherit from std::runtime_error?


For example:

#include <stdexcept>
class A { };
class err : public A, public std::runtime_error("") { };
int main() {
   err x;
   return 0;
}

With ("") after runtime_error I get:

error: expected '{' before '(' token
error: expected unqualified-id before string constant
error: expected ')' before string constant

else (without ("")) I get

In constructor 'err::err()':
error: no matching function for call to 'std::runtime_error::runtime_error()'

What's going wrong?

(You can test it here: http://www.compileonline.com/compile_cpp_online.php)


Solution

  • This is the correct syntax:

    class err : public A, public std::runtime_error
    

    And not:

    class err : public A, public std::runtime_error("")
    

    As you are doing above. If you want to pass an empty string to the constructor of std::runtime_error, do it this way:

    class err : public A, public std::runtime_error
    {
    public:
        err() : std::runtime_error("") { }
    //        ^^^^^^^^^^^^^^^^^^^^^^^^
    };
    

    Here is a live example to show the code compiling.