I understand as with any other variable, the type of a parameter determines the interaction between the parameter and its argument. My question is that what is the reasonin
The ability to pass by reference exists for two reasons:
Example for modifying the argument
void get5and6(int *f, int *s) // using pointers
{
*f = 5;
*s = 6;
}
this can be used as:
int f = 0, s = 0;
get5and6(&f,&s); // f & s will now be 5 & 6
OR
void get5and6(int &f, int &s) // using references
{
f = 5;
s = 6;
}
this can be used as:
int f = 0, s = 0;
get5and6(f,s); // f & s will now be 5 & 6
When we pass by reference, we pass the address of the variable. Passing by reference is similar to passing a pointer - only the address is passed in both cases.
For eg:
void SaveGame(GameState& gameState)
{
gameState.update();
gameState.saveToFile("save.sav");
}
GameState gs;
SaveGame(gs)
OR
void SaveGame(GameState* gameState)
{
gameState->update();
gameState->saveToFile("save.sav");
}
GameState gs;
SaveGame(&gs);
Also, read on const
references. When it's used, the argument cannot be modified in the function.