c++pass-by-referencepass-by-valuepass-by-pointer

Does C++ pass objects by value or reference?


A simple question for which I couldn't find the answer here.

What I understand is that while passing an argument to a function during call, e.g.

void myFunction(type myVariable)
{
}

void main()
{
    myFunction(myVariable);
}

For simple datatypes like int, float, etc. the function is called by value.

But if myVariable is an array, only the starting address is passed (even though our function is a call by value function).

If myVariable is an object, also only the address of the object is passed rather than creating a copy and passing it.

So back to the question. Does C++ pass a object by reference or value?


Solution

  • Arguments are passed by value, unless the function signature specifies otherwise:

    In case of arrays, the value that is passed is a pointer to the first element of the array. If you know the size of the array at compile time, you can pass an array by reference as well: void foo(type (&arg)[10]).