C++ Exceptions and Inheritance from std::exception

fbrereto picture fbrereto · Apr 3, 2010 · Viewed 9.1k times · Source

Given this sample code:

#include <iostream>
#include <stdexcept>

class my_exception_t : std::exception
{
public:
    explicit my_exception_t()
    { }

    virtual const char* what() const throw()
    { return "Hello, world!"; }
};

int main()
{
    try
        { throw my_exception_t(); }
    catch (const std::exception& error)
        { std::cerr << "Exception: " << error.what() << std::endl; }
    catch (...)
        { std::cerr << "Exception: unknown" << std::endl; }

    return 0;
}

I get the following output:

Exception: unknown

Yet simply making the inheritance of my_exception_t from std::exception public, I get the following output:

Exception: Hello, world!

Could someone please explain to me why the type of inheritance matters in this case? Bonus points for a reference in the standard.

Answer

GManNickG picture GManNickG · Apr 3, 2010

When you inherit privately, you cannot convert to or otherwise access that base class outside of the class. Since you asked for something from the standard:

§11.2/4:
A base class is said to be accessible if an invented public member of the base class is accessible. If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class (4.10, 4.11).

Simply put, to anything outside the class it's like you never inherited from std::exception, because it's private. Ergo, it will not be able to be caught in the std::exception& clause, since no conversion exists.