Search code examples
c++functionclassvirtualabstract

Can I make virtual abstract class throw an exception


Currently in my project I am making a virtual abstract base class and three derived class. In the base class's pure virtual function is used in the derived classes to create an equation that will either add or subtract with two variables. My problem is that I also have to include a function to check if one of the variables put into the function is negative that will throw an exception if it is. Currently I put these functions and the exceptions into the derived classes but to me it seems a little redundant. So I am wondering if it is allowed to put the function to check to see if the variable I'm checking is negative and have the exception thrown both in the abstract base class?


Solution

  • Yes, you can do that.

    In the base class, you'll want to have two groups of functions:

    • Public, non-virtual functions that users of the class will call.
    • Protected, pure-virtual functions that will be implemented by the derived classes.

    In the base class's public non-virtual functions, you can do any necessary argument checking, e.g. making sure that the argument isn't negative. Throw exceptions as necessary. Then, if the argument checks pass, call the corresponding virtual function to let the derived class do the rest.


    Also, note that if negative numbers don't make sense for your function's arguments, it may be simper to just use unsigned types for those arguments.