pass by reference vs pass by value

I am just wondering why in a copy constructor or to any other similar function, we use pass by reference instead of pass by value. I get it that we set it to constant because we do not want the referenced variable to be modified. On the other hand,does using passed by value gives the same purpose; Since we passed a copy, we do not worry about changing the original values.

1
2
3
4
  Test(const Test& other){ //as opposed to  Test(Test other)
	//implementation
	
	}
Last edited on
for any piece of data that is larger than a pointer, you should pass by reference unless you really desire a copy, to avoid unnecessary copying of data (performance hit). If the data is not to be changed, you want to use a constant reference just for good practice.

if you have a fat class with dozens of data variables in it, you don't want to copy all that every time you do anything, you want to avoid that as much as you can.

> why in a copy constructor (...) we use pass by reference instead of pass by value
Test(Test other)
¿how do you think `other' will be created?
Yeah, the real problem here is that you need a copy constructor in order to make the copy that you want to pass into the copy constructor. It has to be a reference.

However, in general it's okay to pass the occasional object of, say, two longs or so. (E.g., struct Coord { long x, y; } ) It's no different than two separate long parameters. You can even return structs.

For performance purposes, it really counts when the object has pointer(s) to dynamic memory that also needs to be copied.
Last edited on
Ok, thanks for the responses.

@ne555
In eclipse, it does not allow me to use pass by value for copy constructor. But having some code like below
with pass by value allowed me to copy the member values.
1
2
3
Test copy(Test other){
	//implementation
	}



@jonin @tpb
I see. We do it for memory management and improve performance

Last edited on
Topic archived. No new replies allowed.