-2

First of all, I did indeed do a quick search on google, and none of it explained what I am shooting for.

Edit: For instance, I looked here.

The class std::runtime_error is an exception class that signals an error that occurs at runtime. Unless I'm mistaken, it has no default constructor (I got an error when trying to derive from it without explicitly calling a parent constructor) but it does have string(-ish) constructors that allow you to specify a message.

My question is how would you access that message in a member function such as what() (virtual function in std::exception)? There is no getMessage() or similar function defined in the parent class, and calling what() is rather useless if that happens to be the function I am overriding.

I am using Visual Studio Community 2015, so a compiler-specific method is okay, but I would prefer a portable solution.

Community
  • 1
  • 1
Isaiah
  • 685
  • 2
  • 15
  • 28

1 Answers1

3

Specify that you want the base class's what instead of your own:

const char* what() const noexcept override {
    auto base_msg = std::runtime_error::what();
    return /* something using base_msg */;
}

However, there's not much you can really do in what while keeping true to const and noexcept, and also returning a pointer to data that will outlive the function call. You can do formatting in the constructor and return a buffer your class contains. Just be aware that the last thing you want while trying to throw an exception is another error.

chris
  • 60,560
  • 13
  • 143
  • 205