3

Possible Duplicate:
What's the ampersand for when used after class name like ostream& operator <<(…)?

I am new to C++ and I have probably a very noobish question. I have seen a thing like this:

Vector3f & operator = (Vector3f & obj)
{
    _item[0] = obj[0];
    _item[1] = obj[1];
    _item[2] = obj[2];

    return *this;
}

And I was wondering why is there an ampersand (&) after Vector3f. What kind of magic is it doing? I couldn't find any explanations anywhere. Most importantly, what is the difference between the thing above and

Vector3f operator = (Vector3f obj)
{
    _item[0] = obj[0];
    _item[1] = obj[1];
    _item[2] = obj[2];

    return *this;
}
Community
  • 1
  • 1
Martin Marinov
  • 1,167
  • 3
  • 15
  • 25

2 Answers2

4

It's C++'s syntax for pass-by-reference & return-by-reference. It just means that the parameter is an alias of the object from the calling context, and not a copy, and, simillary, the returned object is actually *this, and not a copy.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • So is it like passing a pointer to the object? So why didn't they pass a pointer rather than a reference? – Martin Marinov Oct 02 '12 at 13:28
  • @MartinMarinov because it's C++ and not C. References provide different syntax & semantics. If you don't know what they are, I suggest you read a good introductory C++ book. – Luchian Grigore Oct 02 '12 at 13:30
2

The first one takes a Vector3f by refetence, and returns a Vec3torf by reference. The second takes and returns by value (i.e. semantically it makes a copy of the argument as well as *this).

juanchopanza
  • 223,364
  • 34
  • 402
  • 480