In my game (probably as in any other), I'm going to have a list containing the base class of all existing entities. Each loop, I'll iterate through the list, calling an update() function. My problem is with downcasting and/or construction. Suppose I have:
Code: Select all
class Shape
{
public:
int xPos;
int yPos;
Shape(int x=0, int y=0);
};
Shape::Shape(int x, int y)
{
xPos=x;
yPos=y;
}
class ThreeD : public Shape
{
public:
int zPos;
int getZ();
ThreeD(int x=0, int y=0, int z=0);
};
ThreeD::ThreeD(int x, int y, int z):Shape(x, y)
{
zPos=z;
}
int ThreeD::getZ()
{
return zPos;
}
Code: Select all
Shape* shapePointer=new ThreeD(10, 10, 10);
Code: Select all
cout<<shapePointer->getZ();
Code: Select all
ThreeD* threeDpointer=(ThreeD*)shapePointer;
Code: Select all
cout<<threeDpointer->getZ();
The list class can't just call the update function without downcasting (as far as I know). But downcasting is impossible, because the list object isn't aware of the children of the class that it's pointing to; it's just pointing to a base class instance. Could someone please explain how I'd do it, or point me towards such an explanation?