Boost logo

Boost Users :

Subject: Re: [Boost-users] [Exception] How do I inherit custom exception hierarchy from std::runtime_error rather than from std::exception?
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2013-11-27 13:41:20


AMDG

On 11/27/2013 08:19 AM, Egor Tensin wrote:
> <snip>
>
> #include <iostream>
> #include <stdexcept>
>
> #include <boost/exception/all.hpp>
>
> typedef boost::error_info<struct tag_foo_info, unsigned long> foo_info;
>
> struct foo_error : virtual boost::exception, virtual std::runtime_error
> {
> explicit foo_error(const char *const what)
> : std::runtime_error(what)
> { }
>
> explicit foo_error(const std::string& what)
> : std::runtime_error(what)
> { }
> };
> <snip>
>
> It says that there's no default constructor available for
> std::runtime_error. How do I fix this or should I use the idiomatic
> approach? The interesting thing is that if I erase the "virtual"
> keyword, the program compiles flawlessly. I wonder what is the reason
> for that, e.g. why the original code doesn't work and why the new code
> does, what are the consequences of making boost::exception and
> std::runtime_error base (non-virtual) classes, etc. I'm confused as
> the docs clearly recommends I build exception classes hierarchy using
> virtual inheritance. Could somebody please give me an insight into the
> inner workings of the library & inheritance mechanisms?
>

The reason that this causes a problem is that
BOOST_THROW_EXCEPTION creates a class derived
from its argument's type. The constructor of
a virtual base is always called from the most
derived class. Since Boost.Exception doesn't
know that your exception type derives from
std::runtime_error, it just calls the default
constructor of std::runtime_error, which doesn't
exist.

In Christ,
Steven Watanabe


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net