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:
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 withruntime_error_object.what()
in acatch
block. So, that is why thelength
variable is being converted to astd::string
. You can read more about that here.Lastly:
This is constructor list initializer syntax. That is used to initialize member variables of a class. You can read more about that here.