0

This is something that's been bugging me for a while now.

So let's say you have your baseClass and derivedClass. You also have a container object of baseClass pointers that holds pointers to all the objects you're managing.

The problem comes when there's an overloaded function with arguments of the derived class.

Example:

function foo(baseClass, baseClass);
function foo(baseClass, derivedClass);
function foo(derivedClass, derivedClass);

vector<baseClass*> objectList;

objectList.push_back(new derivedClass());
objectList.push_back(new derivedClass());

foo(objectList[0], objectList[1]); // <-- Here's the problem.

Until now I've been doing something hackish, and that's static_cast-ing to the "correct" type based on a "getType()" enum member variable I've defined. It's really ugly and I'd like to know the correct way to pass these arguments as the derived class.

Or is this just bad design as a whole?

And no, the container class can't be of type derivedClass... baseClass is the base for several different classes. While it's in the vector, I don't care what object type it is. When I pass it into an argument, I'd like for the compiler to know what type it is.

RayBatts
  • 255
  • 1
  • 9
  • If `foo` has to know the difference between a base and a derived, then you're misusing OOP. Why not make `foo` a virtual function in base, so that it can be overridden in derived types? – ildjarn May 29 '12 at 23:13
  • Because in my code, foo is a static function being called from another class. Forgot to mention that : ( – RayBatts May 30 '12 at 01:06
  • And you can't make it an instance function? Making a function that needs virtual dispatch `static` doesn't sound very useful... – ildjarn May 30 '12 at 01:20

1 Answers1

0

You're trying to do multiple dispatch.

Neil
  • 54,642
  • 8
  • 60
  • 72