Let’s say I have the following class hierarchy in C++:
class Base;
class Derived1 : public Base;
class Derived2 : public Base;
class ParamType;
class DerivedParamType1 : public ParamType;
class DerivedParamType2 : public ParamType;
And I want a polymorphic function, func(ParamType), defined in Base to take a parameter of type DerivedParamType1 for Derived1 and a parameter of type DerivedParamType2 for Derived2.
How would this be done without pointers, if possible?
You cannot have Base::func take different parameters depending on what class inherits it. You will need to change something.
You could make them both take a ParamType and handle an unexpected parameter with whatever mechanism you like (e.g. throw an exception or return an error code instead of void):
Or template on the type of parameter they should take:
With the second solution, Derived1 and Derived2 won’t share a common base and cannot be used polymorphically.