What's the difference?

call-by-value parameters
call-by-reference parameters
Generally:

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++.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#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;
}


See what this does, and then you'll know. ;)

-Albatross
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!
Topic archived. No new replies allowed.