Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a pointer to a sub-class (C++)

Tags:

c++

pointers

I'm developing a game and I need to find a way of getting the value of a certain 'map block' in the game (in char format). I have a class DisplayableObject which takes care of all sprites, and a sub-class ThreeDCubePlayer which takes care of the player object. For ease of rendering/updating everything, all DisplayableObjects are stored in an array, with the 0th cell containing the player (which is of type ThreeDCubePlayer). ThreeDCubePlayer has a different constructor from DisplayableObject (it takes two additional arguments) and only ThreeDCubePlayer has the GetMap() functions that I need. So, here is what I have done so far:

ThreeDCubePlayer* cubePlayer = &((ThreeDCubePlayer &)m_ppDisplayableObjects[0]);

char mapEntry = GetMapEntry((int)*(cubePlayer->GetMapX()), (int)*(cubePlayer->GetMapY()));

This is the part of ThreeDCubeGame.cpp (the function which controls the map and keyboard input). The problem I've had is that both of these lines give an 'illegal indirection' error at compilation. I thought this error is when I try to dereference something that isn't a pointer, and I'm sure cubePlayer looks like a pointer...

Does anyone have an idea as to what I should do?

like image 532
benwad Avatar asked Dec 23 '22 07:12

benwad


1 Answers

Use one of the type safe casts, e.g. dynamic_cast instead of the C-style cast.

If m_ppDisplayableObjects is a DisplayableObject**, then it would look something like this:

ThreeDCubePlayer* cubePlayer = dynamic_cast<ThreeDCubePlayer*>(m_ppDisplayableObjects[0]);

if (cubePlayer != NULL)
{
    char mapEntry = GetMapEntry(cubePlayer->GetMapX(), cubePlayer->GetMapY());
}
else // Not a ThreeDCubePlayer* ...
like image 100
richj Avatar answered Dec 24 '22 21:12

richj