How to inherit from std::runtime_error?
17,560
Solution 1
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.
Solution 2
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) {}
};
Author by
mchen
Updated on June 06, 2022Comments
-
mchen about 2 years
For example:
#include <stdexcept> class A { }; class err : public A, public std::runtime_error("") { }; int main() { err x; return 0; }
With
("")
afterruntime_error
I get:error: expected '{' before '(' token error: expected unqualified-id before string constant error: expected ')' before string constant
else (without
("")
) I getIn 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)
-
mchen about 11 yearsI tried it on compileonline.com/compile_cpp_online.php, and your suggestion gives me
no matching function for call to 'std::runtime_error::runtime_error()'
-
Andy Prowl about 11 years@MiloChen: Are you sure you copied everything correctly? I added a link to a live example that shows the code compiles correctly
-
mchen about 11 yearsOh, I see, it won't compile if I miss out the constructor
err() : std::runtime_error("") { }
. It's not that I want to pass an empty string - I'm forced to. -
Andy Prowl about 11 years@MiloChen: If this answer solves the problem in your question, please consider marking it as accepted :)
-
gg99 over 2 yearsyou might want to simplify further and inherit std::runtime_error constructor with:
using std::runtime_error::runtime_error
;