Search code examples
c++pointersreferencepass-by-referencepass-by-pointer

Why, or in what situations, would you pass an argument to a function as a reference (or pointer) in C++?


I am used to passing arguments regularly in my own code but frequently stumble upon function arguments being passed by reference or pointer while reading over others' C++ code. I do not understand what is the purpose of doing so. Can somebody please explain this?


Solution

  • There are essentially three reasons why this is done.

    Reduced memory usage

    Every time you call a function the arguments are copied and passed. This isn't a big deal when you are passing around numbers. However when you are dealing with big chunks of memory, like objects, structs, arrays etc. this becomes very expensive.

    So all complex types are typically passed as pointers. If you are throwing around objects you are always working with a pointer.

    The const qualifier should be used in this instance to indicate that the variable won't be changed.

    Modify the argument

    Sometimes it is useful to modify the passed argument, though this should be avoided as bad style. The best example I think is modifying an array, for example a push() function. Another is modifying an objects public members, or when you want to return multiple values from a function.

    Note that this can be a source of bugs. If you are modifying a passed variable it should be obvious from the name of the function that this is what you are doing.

    Low level memory access

    Anything which directly works with memory will want direct access to said memory. Standard practice in C but less common in C++. Look at functions like memcpy() and anything else from <string.h>.