Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

exception

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.

like image 795
user3435009 Avatar asked Mar 18 '14 23:03

user3435009


2 Answers

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.

like image 62
user207421 Avatar answered Oct 18 '22 02:10

user207421


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

like image 1
user3353219 Avatar answered Oct 18 '22 03:10

user3353219