while I was doing hackerrank c++ exercises I stumbled upon this code in the discussions section:
class BadLengthException : public std::runtime_error
{
public:
BadLengthException(int length) : std::runtime_error{std::to_string(length)}
{ }
};
I don't really understand what is going on after the member initializer part, this part to be exact:
std::runtime_error{std::to_string(length)}
Can someone explain what this line of code does to me? I have never seen such a use of member initialization. I am used to seeing:
Foo(int num) : bar(num) {};
So please explain it as clearly as possible. Thank you for your time!
You are inheriting from the standard exception class std::runtime_error
.
In this code:
class BadLengthException : public std::runtime_error
{
public:
BadLengthException(int length) std::runtime_error{std::to_string(length)}
{ }
};
You are defining a new exception class in terms of std::runtime_error
.
std::runtime_error
takes a string message as input, which you can print with runtime_error_object.what()
in a catch
block. So, that is why the length
variable is being converted to a std::string
. You can read more about that here.
Lastly:
Foo(int num) : bar(num) {};
This is constructor list initializer syntax. That is used to initialize member variables of a class. You can read more about that here.