May 2nd, 2010, 11:00 PM
Problem trying to make two objects access and edit same data
I am currently trying to write a board game, and I am having trouble making each GameTile on the board access the same Point on the board.
Each GameTile contains a certain number of Points, and sometimes Points overlap(the Point on a corner of one tile may be the same Point on the corner of an adjacent tile)
Each Point on the board has a boolean value to determine whether that Point is occupied or not.
In the code below, I have two GameTiles, tile1 and tile2 respectively.
I have attempted to make each GameTile contain 2 Points(which are the same Points, for testing purposes) and when I edit the boolean value for point1 through tile1, I expect this value to have be changed within tile2 as well. (For example, when I set point1's boolean to true, I expect that when I return the value of point1 from within tile2, it will return 1, without directly setting the variable within tile2.)
using namespace std;
void setOccupied(bool yesOrNo)
occupied = yesOrNo;
void addElement(int arrIndex,Point next)
pSinglePoint = &next; // Pointer points to the memory location of "next" element(in this case a "Point")
allPoints[arrIndex] = *pSinglePoint; // element of allPoints = what is located at the memory address of pSinglePoint
void setSurroundingPointOccupied(int arrIndex, bool yesOrNo)
allPoints[arrIndex].setOccupied(yesOrNo); // This should set the Point boolean value
// to true or false(not a copy, but the actual object is being edited here)
bool checkSurroundingPointOccupied(int arrIndex)
return(allPoints[arrIndex].checkOccupied()); // This should return 0 or 1.
tile1.addElement(1,point2); // tile contains 2 points
tile2.addElement(1,point2); // this tile contains 2 points(which are the same points as the above tile)
bool yes = true;
bool no = false;
cout << tile1.checkSurroundingPointOccupied(0) << endl;
cout << tile1.checkSurroundingPointOccupied(1) << endl;
cout << tile2.checkSurroundingPointOccupied(0) << endl;
cout << tile2.checkSurroundingPointOccupied(1) << endl;
The output I expected:
But the actual output on running the program:
89 (or another large number, changes each time program is run)
I believe Pointers are the way to go with this, however I am new to them, and despite reading various tutorials on Pointers, I'm still obviously doing something wrong.
Any help on how to make this program do what I want it to will be greatly appreciated.
By the way, I am running this using Code::Blocks 8.02 and the GNU GCC Compiler if this is of any help.
Tags for this Thread
Click Here to Expand Forum to Full Width
This is a CodeGuru survey question.