Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 333
user3041058 Avatar asked Jan 19 '14 10:01

user3041058


People also ask

Is C pass by value or reference?

C always uses 'pass by value' to pass arguments to functions (another term is 'call by value', which means the same thing), which means the code within a function cannot alter the arguments used to call the function, even if the values are changed inside the function.

Are objects passed by reference in C?

There are references in C, it's just not an official language term like it is in C++. "reference" is a widely used programming term that long predates the C++ standardizing of it. Passing a pointer to an object is passing that object by reference.

Is C pass by value by default?

By default, C programming uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function.


1 Answers

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

  • in void foo(type arg), arg is passed by value regardless of whether type is a simple type, a pointer type or a class type,
  • in void foo(type& arg), arg is passed by reference.

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]).

like image 185
Oswald Avatar answered Oct 05 '22 23:10

Oswald