If you call foo(scalar a)
, the argument a
of type scalar
will be COPIED from the caller and foo will have it's own COPY of the original object.
If you call foo(scalar &b)
, the argument b
will be just a reference to the original object, so you will be able to modify it.
It's faster to pass an object by reference using the &name syntax, since it avoids creating a copy of the given object, but it can be potentially dangerous and sometimes the behavior is unwanted because you simply want an actual copy.
That being said, there's actually an option that disallows the ability to modify the original object for the called function yet avoids creating a copy. It's foo(const scalar &x)
which explicitly states that the caller does not want the function foo
to modify the object passed as an argument.
Optional reading, carefully:
There's also a way of passing an argument as a raw pointer which is very rare in modern C++. Use with caution: foo(scalar *a)
. The caller has got to provide the address of an object instead of the object itself in this scenario, so the caller would call foo(&a)
. For the called function foo
to be able to modify the object itself in this case, it would need to dereference the pointer a
, like this in foo
: *a =
. The star in front of the variable name in this case says that we don't want to modify the address that we have received (as a direct result of the calling function providing &a
, that is, the address of the object a).