17
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.

Paweł Stawarz
  • 3,952
  • 2
  • 17
  • 26
user3435009
  • 809
  • 2
  • 8
  • 12

2 Answers2

32

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

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++.

  • The virtual keyword actually does a difference. – ciamej Mar 18 '14 at 23:41
  • 3
    @ciamej Not in the case specified. – user207421 Mar 18 '14 at 23:44
  • @EJP but, we don't know if there exists a class that derives from myexception, the code snippet might be just a small excerpt of the whole code. If so the virtual keyword is important. – ciamej Mar 18 '14 at 23:45
  • Or more precisely, we don't know if there are, somewhere in the code, pointers to myexception which may point to instances of myexception subclasses – ciamej Mar 18 '14 at 23:46
  • 3
    @ciamej You've missed the point completely. The method is already virtual in the base class, so adding virtual here does nothing. – user207421 Mar 18 '14 at 23:53
  • but what does throw() do and generally when can you put another method in the header? – user3435009 Mar 18 '14 at 23:57
  • @ciamej As I said, you've missed the point completely. Several times now. – user207421 Mar 19 '14 at 00:00
  • 2
    @ciamej: It makes no difference because `std::exception` already has a `what()` that is virtual. This virtualness is already being inherited. It is redundant to write it again here. – Lightness Races in Orbit Mar 19 '14 at 00:11