Passing by value is better described as pass by copy. A copy of the value is made and sent to a function. This means that if you change the value in the function, the original remains the same:
#include <iostream>
void foo ( int copy )
{
std::cout<<"In foo the copy is "<< copy <<'\n';
copy = 54321;
std::cout<<"Changing the copy to "<< copy <<'\n';
}
int main()
{
int original = 12345;
std::cout<<"In main the value is "<< original <<'\n';
foo ( original );
std::cout<<"Back in main the value is "<< original <<'\n';
} Passing by reference means that instead of a copy of the value, you pass the actual object that contains the value. That way when you change the value, the change is also made in the original object:
#include <iostream>
void foo ( int& reference )
{
std::cout<<"In foo the reference is "<< reference <<'\n';
reference = 54321;
std::cout<<"Changing the reference to "<< reference <<'\n';
}
int main()
{
int original = 12345;
std::cout<<"In main the value is "<< original <<'\n';
foo ( original );
std::cout<<"Back in main the value is "<< original <<'\n';
} Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401