Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 248
mchen Avatar asked May 13 '13 00:05

mchen


People also ask

What is std :: Runtime_error?

class runtime_error; Defines a type of object to be thrown as exception. It reports errors that are due to events beyond the scope of the program and can not be easily predicted. Exceptions of type std::runtime_error are thrown by the following standard library components: std::locale::locale and std::locale::combine.

What is a C++ runtime error?

Runtime Error: A runtime error in a program is an error that occurs while the program is running after being successfully compiled.


2 Answers

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.

like image 175
Andy Prowl Avatar answered Oct 27 '22 11:10

Andy Prowl


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) {}
};
like image 25
rbento Avatar answered Oct 27 '22 10:10

rbento