I read on a similar question on here that passing by value will create a local copy of the object in your function. When I try to do this, my original object gets altered, but I do not want it to change.
The goal of this test was to try and pass an object, to alter it locally, but leaving the original untouched.
In the ObjectList header file:
int **board;
ObjectLise class containing a constructor and a print function:
ObjectList::ObjectList()
{
board = new int*[9];
for(int i = 0; i < 9; i++)
{
board[i] = new int[9];
}
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 9; j++)
{
board[i][j] = 10;
}
}
}
void ObjectList::printB()
{
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 9; j++)
{
cout << board[i][j] << ",";
}
cout << endl;
}
}
ChangeBoard class with function that gets passed an ObjectList.
void ChangeBoard::LetsChange(ObjectList layout)
{
layout.board[0][0] = 99;
layout.board[1][0] = 99;
layout.board[2][0] = 99;
layout.board[3][0] = 99;
layout.board[4][0] = 99;
layout.board[5][0] = 99;
}
In the main I create both objects and pass the ObjectList object to the LetsChange function to try and only alter the object locally, that is in the function only:
ObjectList object = ObjectList();
ChangeBoard change = ChangeBoard();
object.printB();
change.LetsChange(object);
cout << endl;
object.printB();
The output shows that the original object gets altered:
10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,
99,10,10,10,10,10,10,10,10,
99,10,10,10,10,10,10,10,10,
99,10,10,10,10,10,10,10,10,
99,10,10,10,10,10,10,10,10,
99,10,10,10,10,10,10,10,10,
99,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,10,10,10,