0

I am designing a game in which some players cards are known and some aren't. To do this, I made a parent object "Player" with children "OpenPlayer" and "ClosedPlayer".

I want to make an array of all the players in this game to facilitate game management. However, I also want to be able to access the special methods in OpenPlayer and ClosedPlayer as appropriate. Is this possible?

Edit: I am actually thinking of using a vector from STL as this would likely be more appropriate due to variable number of players.

1

2 Answers 2

3

In general, you can't make a C++ array whose elements are of different class types; each array element must be the same size, and that won't necessarily be true of different subclasses. Putting different types in the the array can result in slicing, which is the surprising disappearance of the data members of a subclass.

But if you make an array of pointers to your different subclasses, then you'll easily be able to do what you want. You might also consider using a vector instead of an array if the number of players can vary.

Sign up to request clarification or add additional context in comments.

6 Comments

Ah I didn't think of using pointers. That's a great idea, thank you. If I make it a vector of "Player", will I be able to have it refer to both Open and Closed player? Sorry if this is a silly question, I'm new to C++.
A vector<Player*> would work; a plain vector<Player> would also suffer from the slicing problem.
I got it working with the vector, however I need to access some none virtual methods. Casting seems to work fine, but how can I tell which child to cast to? I tried comparing the typeid but that doesn't seem to be working for me.
That would be the way; maybe tell us what goes wrong exactly, and we could figure out what the problem is?
Whenever I was trying typeid, it just gave me Player* as the type, so I had no idea what to cast to. I realized I can just use dyanmic_cast. That seems to be working for me. Is that the right way to do it?
|
0

By "access special methods" I assume you mean methods in just the OpenPlayer or just the ClosedPlayer?

By array, I assume you mean some STL collection ;-)

The short answer is "No".

The long answer is "Yes you can, but you'll need to cast objects to the correct type. This implies that your design is wrong."

A different disign might be to make "Open" or "Closed" a property of the Player class rather than individual subclasses.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.