user3435009
user3435009

Reputation: 859

What is the meaning of this header (virtual const char* what() const throw())?

class myexception: public exception
{
  virtual const char* what() const throw()
  {
    return "My exception happened";
  }
};

Sorry, this question may sound dumb, but I have trouble parsing the header. Can someone describe in English what the header actually means? The first thing that seems odd to me is the keyword virtual. The myexception class is not a base class and inherits from the already implemented exception class, so why use virtual here? I guess const is for the return type which is a c-style string that is const, and the other const is to make sure nothing that the this object cannot be modified (can someone tell me what that object could be?). I have no idea what throw() does exactly, never seen this syntax before.

Upvotes: 17

Views: 9464

Answers (2)

user207421
user207421

Reputation: 310980

virtual

Adds nothing, as the method being overridden is already virtual. You are correct: it can be omitted.

const char* what()

A member function named what() that takes no arguments and returns a pointer to const char.

const

The member function can be called via a const pointer or reference to an instance of this class or a derived class.

throw()

Throws no exceptions.

Upvotes: 32

user3353219
user3353219

Reputation: 29

The virtual keyword is optional (you can skip it or explicitly write down - no difference) when you override an already virtual method from a base class (like in this case). Your remarks about the two const keywords are almost correct. It's basic C++.

Upvotes: 1

Related Questions