Call by value: work on a local copy of variable (changes inside a function will not affect the object passed to it)
Call by reference: work on same variable (changes inside a function will affect the object passed to it)
Though I don't see these phrases used much in C++.
#include <iostream>
int FauxAdd (int a, int b) //Passed by values.
{
a += b;
return a;
}
int VraiAdd (int& a, int& b) //Passed by reference.
{
a += b;
return a;
}
int main()
{
int a, b;
a = 3;
b = 2;
std::cout << "Initial Values:\na:";
std::cout << a << "\nb: " << b;
std::cout << "\n\nFauxAdd:\na should be: ";
std::cout << FauxAdd(a,b) << "\nyet a is: " << a;
std::cout << "\n\nVraiAdd:\na should be:";
std::cout << VraiAdd(a,b) << "\nand a is: " << a;
std::cin.ignore(); //Pause the console.
return 0;
}
You need to learn this well if you don't want your computer doing a lot of unnecessary work.
For example, when you are passing an object as a parameter in C++ (especially a large, complex object), you usually want to use const& as much as possible (or at least &), to avoid copy-construction on the fly.
Remember, if you pass an instance by value, the compiler is going to make a copy of your instance through its copy constructor... ...make sure this is what you want before doing it!