1

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)
user3215228
  • 313
  • 1
  • 3
  • 13
  • 1
    http://stackoverflow.com/questions/2564873/reference-parameters-in-c-very-basic-example-please – 001 Mar 03 '14 at 19:36

3 Answers3

2

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."

TypeIA
  • 16,916
  • 1
  • 38
  • 52
  • The OP asks about const references – Sebastian Hoffmann Mar 03 '14 at 19:37
  • @Paranaix No he didn't; `const` only appears in his example code, and from his question I suppose his confusion is more general than specifically regarding `const`. All the same I added a note about `const` to my answer. – TypeIA Mar 03 '14 at 19:39
0

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.

Sebastian Hoffmann
  • 11,127
  • 7
  • 49
  • 77
0

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.

SJuan76
  • 24,532
  • 6
  • 47
  • 87