0

Possible Duplicate:
Learning C++: polymorphism and slicing
Array of polymorphic base class objects initialized with child class objects

I've integrated object oriented classes into my OpenGL application. The base class has a function called Tick that should get called every tick (obvious) with a parameter representing the delta time. Here's how it looks like (without the irrelevant things for this question).

Headers:

class Object
{
public:
    virtual void Tick(float DeltaTime);
}
class Controller : public Object
{
public:
    virtual void Tick(float DeltaTime);
}

Then I have a class called Engine that contains the main loop, initializations and disposal (to separate it from the window creation).
In that class I need to keep track of all the objects in the game, so I created an array:
Object* Objects = new Object[10]; // for now max 10 objects

Then to call the tick function I iterated trough the array:

for (unsigned int c = 0; c < 10; c++)
    Objects[c].Tick(delta);

Being delta calculated before the loop.

The problem is that if I assign one of the objects in the array to a Controller (for example) the Tick function called is always the one that's in Object and not in the class that's actually stored.

I even tried type casting (each class has a string to identify it's type), with no avail.

I'm pretty sure that the answer is something obvious (like the answer to my last questions), but I can't find the answer.

Thank you for your time. :)

Community
  • 1
  • 1
zeluisping
  • 213
  • 7
  • 17

1 Answers1

5

You have encountered the slicing problem.

The solution is to not store polymorphic objects by value in an array; use (smart) pointers instead.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • Thank you, would have been easy to find an answer if I knew the keyword slicing. So the problem is fixed by using an array of pointers of type `Object`, thank you :) (once again, simple answer lol) – zeluisping Jul 02 '12 at 10:05