What is the difference between pass by value, pass by reference, and pass by pointer?
Last updated
Pass by value copies the argument into the parameter; pass by reference gives the function an alias to the caller's variable; pass by pointer passes the address, so the function works through it. References and pointers let the callee modify the original and avoid copying; the difference is mainly syntax and nullability.
Pass by value:
Callee gets its own copy; changes don't affect the caller. Safe but can be expensive for large objects.
For read-only large objects prefer
const T&to skip the copy.
Pass by reference:
An alias to the original (
T&); modifications are visible to the caller and no copy is made.Cannot be null and cannot be reseated; cleaner syntax (
obj.method()notptr->method()).
Pass by pointer:
Passes an address (
T*); can be null to mean optional, and can be made to point elsewhere.Requires dereferencing and a null check; common in C-style and ownership-transfer code.
Rule of thumb: Default to
const T&for non-trivial inputs, by value for small/cheap types, and a pointer when null is a meaningful value.