user3215228
user3215228

Reputation: 313

Object by reference and without reference

I want to ask one simple question which is making me confuse. for example if I write in argument there is no reference &. but in the second case I have used & with rectangleType&, I am having confusion why we use this & when we can do it without this &. Where is this necessary and why we use it. My question is not about copy constructor.

 rectangleType rectangleType::operator+
(const rectangleType rectangle)

Case 2:

rectangleType rectangleType::operator+
(const rectangleType& rectangle)

Upvotes: 1

Views: 81

Answers (3)

SJuan76
SJuan76

Reputation: 24885

In the first method, it will receive a (complete) instance of rectangleType, that will be created using the copy constructor just to be passed as a parameter.

In the second method, it will receive a reference to an already existing instance; no copy will be made.

Upvotes: 0

TypeIA
TypeIA

Reputation: 17250

When you pass an object like rectangleType (or any other type) by value, you're making a copy of that object. This means:

  • Any changes made to the object by the function are not seen by the caller, since the changes are made on a copy, not the original object.
  • The act of copying the object incurs a performance cost.
  • Copying the object may not even be possible for some types.

So, pass by reference whenever:

  • You want the function to be able to modify the original object.
  • You want the code to run faster by not having to make a copy.
  • The object you're passing doesn't have a public copy constructor.

Pass by const reference whenever you don't need the function to be able to modify the original object.

For user-defined types, this essentially boils down to "pass by reference wherever possible."

Upvotes: 2

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 11482

How can you state that your question is not about copy construction if the answere is about it?

  1. With a const reference no copy is made, this can be crucial for very large objects
  2. There are classes wich explicitely dont provide a copy constructor, this way you can still pass them around.

So to conclude: You get benefits without disadvantages.

Upvotes: 0

Related Questions