I have made my own exception class which derives from runtime_error and is getting an int in the c’tor.
I would like to make a base class for this exception, in order to use polymorphism, so I could catch only the base class and basically I would be catching the derived class.
So, this is the base class: (and in another cpp file I got baseException::~baseException(){})
class baseException
{
virtual ~baseException()=0 {}
};
And this is the derived class:
class myException: public runtime_error, public baseException
{
public:
myException(int): runtime_error("Error occured") {}
};
Note that I do not have any actual error in the base class, it’s only role is to enable me polymorphism on my future custom exception classes I will make.
That is why it only has a pure virtual d’tor. I do not need any “actual” object of this BaseException class.
Though, when I try to catch baseException in the main and call what(), I can not.
How do I make it work?
The first problem is that you’re missing the
()from the destructor’s declaration, and there’s a rogue:after the class name.Once you’ve fixed that, you’ll probably get an error like:
For some reason known only to the C++ standards committee, pure virtual functions cannot be implemented within the class definition like that. If you want it to be pure virtual, then you’ll need to move the definition outside the class:
You’ll also need to decide whether
myExceptionderives fromruntime_exceptionorruntime_error: you use one in the class header, and the other in the constructor’s initialiser list. Assuming you’re using the standard exception types, it should probably bystd::runtime_error(and, if there’s ausing namespace std;in your header file, then you should remove it to avoid breaking code that doesn’t expect the global namespace to be polluted like that).