Hello guys, I have a weird question. Given this scenario:
we have a base class called letters;
and three derived classes, called A, B, and C that all share the same
functions.
Then lets say we have one more class called AddingThings. The AddingThings
class has a 9 static function that accepts two parameters (every combination that the three derived classes A,B, and C can make) and it runs the same set of commands for every class. The function looks similar to the line below except there are 9 of them, and the parameters change.
The question I am asking is, would it be possible to make just one function that could have the potential to accepts different classes as parameters (since they all are derived from a base class). That way, it would eliminate the need to have nine of these functions.
Sorry for my rambling, it's late where I am at, any input you guys may have would be appreciated, I'm doubting if this is even possible, but worth a try I suppose.
Why bother with polymorphism when you have templates? As long as you know what methods any object passed to the function should have, you can safely go ahead and use a template method instead of accepting the base class type and risk object slicing.
1 2 3 4 5 6 7 8 9 10
class AddThings
{
public:
template <typename A, typename B>
staticvoid the_function( const A &A_object, const B &B_object )
{
A_object.DoSomething;
B_object.DoSomething;
}
};
> would it be possible to make just one function that could have the potential to accepts different classes as parameters
> (since they all are derived from a base class).
> That way, it would eliminate the need to have nine of these functions.
If your design involves an object-oriented hierarchy of base and derived classes:
Write one function which accepts a pair of references (or pointers) to the base class.
(Which then calls virtual functions on the objects passed to it).