1 2 3
|
void byval(CVector param);
void byref(CVector& param);
void bycref(const CVector& param);
|
Here we have 3 functions which pass the parameter in different ways.
The first function passes the parameter "by value". This means that 'param' will actually be a copy of the object. So if you were to call the function like so:
1 2
|
CVector a;
byval( a );
|
... 'a' and 'param' would be two separate objects. The 'byval' function could make changes to the 'param' object, and it would not change the 'a' object because they are separate things.
On the other hand... the 'byref' function passes the object by reference. Which means 'a' and 'param' will both refer to the
same object. Changes made to 'param' inside the byref function
will change the 'a' object because they are one and the same.
The const reference version ('bycref') is the same as the 'byref' version in that both 'a' and 'param' refer to the same object. The difference is that the
const
keyword prevents you from making changes to 'param' because it's treated as a constant.
With complex objects (classes) it's typically preferred to pass them by const reference because it avoids having to copy the object. Creating a copy can be computationally expensive... so passing by value is often avoided.
However with basic/small types (like builtin types such as int/double/etc), the copy is trivial and it can possibly be faster to pass them by value. So it really all depends.