I'm about to create an exception class hierarchy which conceptually looks somewhat like this:
#include <iostream>
#include <stdexcept>
class ExceptionBase : public std::runtime_error {
public:
ExceptionBase( const char * msg ) : std::runtime_error(msg) {}
};
class OperationFailure : virtual public ExceptionBase {
public:
using ExceptionBase::ExceptionBase;
};
class FileDoesNotExistError : virtual public ExceptionBase {
public:
using ExceptionBase::ExceptionBase;
};
class OperationFailedBecauseFileDoesNotExistError
: public OperationFailure, FileDoesNotExistError {
public:
using ExceptionBase::ExceptionBase; // does not compile
};
int main() {
OperationFailedBecauseFileDoesNotExistError e("Hello world!\n");
std::cout << e.what();
}
All constructors should look the same as the constructor of the ExceptionBase
class. The derived exceptions only differ concerning their type, there's no added functionality otherwise. The last exception type mentioned in the above code should also have these constructors. Is this possible using the inheriting constructors feature of the C++11 standard? If that is not possible: what are alternatives?
(By the way: In the above code the classes OperationFailure
and FileDoesNotExistError
did not compile with gcc 4.8, but with clang 3.4. Apparently, gcc rejects inheriting constructors for virtual bases. It would be interesting to know who's right here. Both compilers rejected the class OperationFailedBecauseFileDoesNotExistError
, because the inheriting constructor does not inherit from a direct base.)
using OperationFailure::OperationFailure
? But probably it wont work because of the double inheritance. – SamaniegoOperationFailure
when creating an object (with the parametrized ctor). When replacing the virtual inheritance with a non-virtual, it work. I suggest you file a bug report for gcc, as I cannot find anything in the Standard which prohibits this, and the latest proposal N2540 explicitly allows it. – Linalool