I have created an array of Position
which is a parent class of several classes : Player
, Item
, Mob
, and Map
.
I want to create an array of several types of objects in my Position
array (dynamically created object) and then want to use the methods of my objects which are unique.
I can't use the virtual type because I would have to write the methods of all my classes and it would be incoherent.
So I ask you to try to solve this problem.
Map.h :
...
static constexpr int mapColonne{14};
static constexpr int mapLigne{6};
Position *positionObject[mapLigne][mapColonne];
...
Map.cpp :
...
positionObject[i][j] = new Player("Player1");
positionObject[i][j]->infoPlayer();
...
Error: class "Position" has no member "infoPlayer
CodePudding user response:
You have following options, depending on what do you want to happen if the element doesn't contain the type you think it does:
static_cast<Player *>(positionObject[i][j])->infoPlayer();
- undefined behavior on type mismatch.dynamic_cast<Player *>(positionObject[i][j])->infoPlayer();
- cast returns null on type mismatch, which you can check for. If you don't check for null, calling a method on a null pointer might crash.dynamic_cast<Player &>(*positionObject[i][j]).infoPlayer();
- exception on type mismatch.
I would use:
- (3) if I think I know the right type.
- (1) if I'm absolutely certain I know the type.
- (2) if I want to check the type first, and do something else if it doesn't match.
dynamic_cast
is often a sign of bad design. I see no reason to use it here. All your classes should have common methods (declared in base class), such as draw()
, update()
, etc, which you would call for every object on the board.