0

I wrote the following code:

class GameException : public mtm::Exception {
};

class IllegalArgument : public GameException {
public:
    const char *what() const noexcept override {
        return "A game related error has occurred: IllegalArgument";
    }
};

class IllegalCell : public GameException {
public:
    const char *what() const noexcept override {
        return "A game related error has occurred: IllegalCell";
    }
};

How may I use inheritance here to prevent some code duplication? As you can see I'm returning the same sentence but with different ending (Which is the class name). I though about implementing GameException as the following:

class GameException : public mtm::Exception {
     std::string className;
public:
    const char *what() const noexcept override {
        return "A game related error has occurred: "+className;
    }
};

But how may I change the value of className for the rest of my classes? Plus, I'm getting the error:

No viable conversion from returned value of type 'std::__1::basic_string' to function return type 'const char *'

  • 1
    FYI: [SO: Returning char * instead of string](https://stackoverflow.com/q/62573397/7478597) (Very similar question from yesterday.) – Scheff's Cat Jun 26 '20 at 10:41

1 Answers1

0

The error is because char [] + std::string yields a std::string but the method is delcared to return a const char *.

To avoid problems with returning a pointer to temporary, I would suggest this:

class GameException : public mtm::Exception {
     std::string message;
public:
    GameException(const std::string& pref) 
      : message("A game related error has occurred: " + pref)
    {}
    const char* what() const noexcept override {
        return message.c_str();
    }
};

Derived classes then only need

struct some_excpetion : GameException {
     some_exception() : GameException("some_exception") {}
};

PS: Inheriting from std::runtime_error can be more convenient, because it already implements what() and comes with a constructor that takes the message to be returned by what(). You can basically remove your GameException and inherit from std::runtime_error instead.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185