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):
struct ParamType;
struct Base {
void func(ParamType&);
}
struct Derived1 : Base {};
//...
Or template on the type of parameter they should take:
struct ParamType;
struct DerivedParamType1 : ParamType {};
struct DerivedParamType2 : ParamType {};
template<class ParamT>
struct Base {
void func(ParamT&);
};
struct Derived1 : Base<DerivedParamType1> {};
struct Derived2 : Base<DerivedParamType2> {};
With the second solution, Derived1 and Derived2 won't share a common base and cannot be used polymorphically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With