mchen
mchen

Reputation: 10156

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)

Upvotes: 23

Views: 22953

Answers (2)

rbento
rbento

Reputation: 11648

Would just like to add that alternatively the err class could take a string message and simply forward it to std::runtime_error, or an empty string by default, like so:

#pragma once

#include <stdexcept>

class err : public std::runtime_error
{
public:
    err(const std::string& what = "") : std::runtime_error(what) {}
};

Upvotes: 5

Andy Prowl
Andy Prowl

Reputation: 126522

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.

Upvotes: 24

Related Questions