So far we always passed values to a method. This is called pass by value. We literally pass values to a function or a method. Which means we’ll be making a copy of the object containing them.
Another way to pass an object is called pass by reference. Instead of copying all values, the memory address of the object is passed. In other words: we’ll just tell our function ’Hey, the object you need can be found at this or that location.’
In code, it looks like this:
Vec som(Vec & pos1, Vec & pos2) {
return pos1 + pos2;
}
5// someplace else
Vec p1(0.1, 0.3, 0.5);
Vec p2(1.9, 2.7, 0.5);
Vec p3 = som(p1, p2);
10
Compare this to the first code example. The only difference is the & (ampersand) between the argument type and its name. That doesn’t seem like much, but let’s count the number of steps the processor needs to execute this function:
Passing the arguments to the function takes a lot less time when using references. In fact, it is almost always a good idea to pass by reference. The only exception are basic types like int, float and bool. This is because when using basic types, copying the address (32 or 64 bits) takes just as much time as copying the value itself. In some cases it might even be more work! (Consider copying a bool or the address of a bool.)