2

I am currently reading a C++ book and encountered this bit of code which I don't know how to interpret:

#include <exception>
#include <memory>
struct empty_stack: std::exception // don't know what the code after : means
{
     const char* what() const throw(); //don't understand this line either
};
  • 3
    `: std::exception` defines `public` inheritance. `throw()` means the function doesn't throw an exception (it would be a bit annoying if `what` could throw an exception). – Bathsheba Nov 13 '18 at 09:37
  • 3
    Your book seems terribly outdated, and in two year's time this example will be completely out of touch with contemporary C++. I suggest you spare a glance for [our curated book list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – StoryTeller - Unslander Monica Nov 13 '18 at 09:41
  • I guess my next question would be, what's the purpose of inheriting from std::exception if your only function does not throw an exception? – Bear Bile Farming is Torture Nov 13 '18 at 22:54

2 Answers2

4

struct empty_stack: std::exception // don't know what the code after : means

This means that empty_stack publicly inherits from std::exception which is the base class for standard exceptions.

Note: If the inheritance type is not specified, the default type of inheritance depends on the inheriting type. It's private if inheriting type is class and public if inheriting type is struct.

const char* what() const throw(); //don't understand this line either

This means that what() is a function that does not modify the non-mutable members of the class it is part of and does not throw any exception. But it is a bit misleading to have throw() at the end to mean that it does not throw.

So, from C++11 onwards, we have the noexcept specifier. Using this in a function declaration like the one below means that the function is declared not to throw any exceptions.

const char* what() const noexcept;

Note: throw() is deprecated and will be removed in C++20.

P.W
  • 26,289
  • 6
  • 39
  • 76
1
const char* what() const throw();
  • const char* means that the method returns a pointer to a const char, which is the typical type of a string in C (and C++, for backward compatibility)

  • what is the method name.

  • the second const means the method is not allowed to modify any non-mutable member of the class, or basically not allowed to modify any member if not marked as mutable

  • throw() means that the method is allowed to throw "nothing", so it's not allowed to throw. This can be reasoned that this function is supposed to be your last line of defense when an exception is thrown. Throwing an exception in it will defeat the purpose.

The Quantum Physicist
  • 24,987
  • 19
  • 103
  • 189