Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ syntax for custom exception class [duplicate]

I am fairly new to C++ and have found the following code snippet for a custom exception extended from std::exception. The only part I don't understand is the : err_msg(msg) {} after the constructor definition. Can anyone explain why this is not in the function braces?

class my_exception : public std::exception {
  private:
    std::string err_msg;

  public:
    my_exception(const char *msg) : err_msg(msg) {};
    ~my_exception() throw() {};
    const char *what() const throw() { return this->err_msg.c_str(); };
};
like image 757
eldereko Avatar asked Oct 03 '22 13:10

eldereko


1 Answers

The member err_msg is already initialized by the initializer list.

my_exception(const char *msg) : err_msg(msg) {};
//                         here ^^^^^^^^^^^^

So nothing to do for the contructor.


Sidenote: There is a some discussion about not using std::string in exceptions. Just google for it or see here.

like image 99
user1810087 Avatar answered Oct 13 '22 12:10

user1810087