I'm trying to build a chess game in C++.
I have a base class gamePiece and a derived class rook. My original idea was to create a vector of gamePiece objects and insert all of the different types of gamePieces (rooks, queens, pawns) inside there. As I found out in my last question, I can't do that -- the gamePiece vector only takes base class (i.e. gamePiece) objects.
However, smart pointers and other techniques were suggested. I will try that soon.
But I'm still curious as to why the technique below won't work. What if I instead create a vector of pointers to gamePieces, and then attempt to store pointers to my derived objects inside that vector?
vector<gamePiece *> vectorOfPointersToGamePieces;
vector<gamePiece *>::iterator itOfPointersToGamePieces;
For example, suppose I insert a pointer to a rook object inside the above vector at the first location. Initially what I thought might work was this strategy:
vectorOfPointersToGamePieces.push_back( &(rook(1, "Rook", 'A', 1, "White", "Up") ) );
itOfPointersToGamePieces=vectorOfPointersToGamePieces.begin();
( * ( * (itOfPointersToGamePieces))).displayPieceInfo();
The constructors appear to run fine, everything initializes. But when it comes time to display the values of the data members onscreen with cout, the variables appear to be empty/unitialized. It's like they disappeared.
My second crack at it was to try to dynamically cast the rook pointer to a gamepiece pointer before inserting it in the vector, like this.
vectorOfPointersToGamePieces.push_back( dynamic_cast <gamePiece *> (&(rook(1, "Rook", 'A', 1, "White", "Up") ) ) );
But that yielded the exact same output as above. Empty/Unitialized variables.
On my third attempt, I took a step back and tried a simpler operation. Here, I tried to insert a pointer to a gamePiece in the vector instead of a pointer to a rook.
vectorOfPointersToGamePieces.push_back( &(gamePiece(1, "Rook", 'A', 1, "White", "Up")) );
There were issues with even this third operation-- Only some the variables I initialized in the constructor were retained when I attempted the display operation:
itOfPointersToGamePieces=vectorOfPointersToGamePieces.begin();
( * ( * (itOfPointersToGamePieces))).displayPieceInfo();
More specifically, the ints, and the char were retained and displayed properly. But the strings were empty and disappeared.
Anyone have any ideas as to why my strategy isn't working?