I have a class containing a 2d vector of type Square called chessboard:
1 2 3 4 5
class A
{
...
vector< vector<Square> > chessboard;
}
Square objects have a pointer that points to a GamePiece object which is parent to all the different chess pieces.
Here's the problem I'm having. GamePiece has to have a pointer to chessboard so that it can calculate its legal moves on the board:
1 2 3 4 5
class GamePiece
{
...
vector< vector<Square> > * chessboard; //needs to point to same chessboard as in class A
}
I (think I) fixed the circular dependency between Square and GamePiece with forward declarations, but now I cannot for the life of me initialize chessboard to an 8x8 array of Squares.
Here are my questions:
1. Does the 2d vector need to be initialized on the heap in order for GamePiece to be able to access it with a pointer? If so, how can I initialize it on the heap? I've tried this:
1 2 3 4 5 6 7 8 9 10 11
class A
{
...
vector< vector<Square> > * chessboard;
}
A::A()
{
chessboard = new vector(8, vector<Square>(8));
}
...And it doesn't compile. I can't figure it out.
Any suggestions on a better solution? All I need is an 8x8 array that both class A and GamePiece can see (and I have to manage memory manually, which is why I chose vectors to simplify things).
So if I resize my vector to 8x8 in A's constructor, and I send &chessboard over to a GamePiece object, it would be able to see the chessboard using that pointer as long as A isn't destroyed, right?
I don't see why it fail to compile. What is the error message you get? No you don't need to allocate on the heap. But don't confuse the heap with storage duration. In your first code chessboard may very well be on the heap if the A object was created with new. You can always get the pointer to an object by using the & operator.
I don't see the benefit of calling resize instead of using the constructor.
"So if I resize my vector to 8x8 in A's constructor, and I send &chessboard over to a GamePiece object, it would be able to see the chessboard using that pointer as long as A isn't destroyed, right?"
Sure. But if you are doing it like that, can't you just load the vector to whatever size your data is? I mean what if you want to have a 16x16 board?
If you use push_back when loading the board you can fill it to whatever size you want depending on how much data you have or if you store the size in a variable.