Im having trouble understanding the difference in formal and reference parameters.. If anyone could help better explain these to me, I'd greatly appreciate it
okay basically when you send arguments to a function you arent sending the actual variables, unless you specify too. otherwise you are sending a COPY of the variable, not the actual thing. you can see so in this example:
// Ex5_02.cpp
// A futile attempt to modify caller arguments
#include <iostream>
using std::cout;
using std::endl;
int incr10(int num); // Function prototype
int main(void)
{
int num = 3;
cout << endl
<< "incr10(num) = " << incr10(num)
<< endl
<< "num = " << num;
cout << endl;
return 0;
}
// Function to increment a variable by 10
int incr10(int num) // Using the same name might help...
{
num += 10; // Increment the caller argument – hopefully
return num; // Return the incremented value
}
number remains unchanged because you the function never had access to the variable, it just had a copy of the number (which held a value of 10). ofcourse the variable num had the value 20 because the function did its thing and increased the COPY by 10.
there are two basic ways to solve this. the simplest way is to specify in the function parameters that you are getting a reference of the number not a copy. you can do this by adding the ampersand symbol & after the data type. here is the previous example except this time you are passing by reference instead of by value:
// Ex5_07.cpp
// Using a reference to modify caller arguments
#include <iostream>
using std::cout;
using std::endl;
int incr10(int& num); // Function prototype
int main(void)
{
int num = 3;
int value = 6;
int result = incr10(num);
cout << endl
<< "incr10(num) = " << result;
cout << endl
<< "num = " << num;
result = incr10(value);
cout << endl
<< "incr10(value) = " << result;
cout << endl
<< "value = " << value;
cout << endl;
return 0;
}
// Function to increment a variable by 10
int incr10(int& num) // Function with reference argument
{
cout << endl
<< "Value received = " << num;
num += 10; // Increment the caller argument
// - confidently
return num; // Return the incremented value
}
hopefully you get it better now :)
p.s. i ripped these examples from a book and take no claim to owning them xD