Search code examples
c++c++11inheritancepure-virtual

Choosing one of two pure virtual functions in c++


Is there a way for a derived class to choose to implement one of two pure virtual functions?

In my case, these pure virtual functions serve the same general purpose, but in certain settings of the class, one will require the function with an additional parameter. Of course there is always the option of making one pure virtual function with the full parameter set. However in this case there will always be the possibility of the end-user wondering about this extra parameter he isn't using.


Solution

  • All pure virtual functions must be implemented in each subclass.

    However, you can address your particular issue by defining a single pure virtual function with a full set of parameters, and adding a default for the last parameter that you consider optional:

    virtual void foo(int p1, std::string p2, double p3 = 0.0) = 0;
    

    Now the callers would have a choice of passing two or three parameters, while implementing classes that do not need p3 would be able to ignore it.