-3

I understand that the & character has various uses in c++, but I'm having trouble understanding what its function is in the code sample below (taken from here) (not its use in the left argument, but its use in std ostream&.

std::ostream& operator<< (std::ostream &out, const Point &point)
{
    // Since operator<< is a friend of the Point class, we can access Point's members directly.
    out << "Point(" << point.m_x << ", " << point.m_y << ", " << point.m_z << ")";

    return out;
}

I think I understand the use of & when it represents a pass by reference inside a function parameter, but I can't see what it would do outside a function.

As far as I can see (which isn't very far at all), std::ostream is an class, which, when instantiated, can, via the operator <<, can be fed strings etc. to output to console. Then &out in the code above is a reference to an instance of std::ostream, (which will be std::cout?), which inside the function is fed point.m_x etc. and then returned so that multiple << operations can be performed.

I'm guessing the first instance of the & character is somehow communicating that the << operator defined in std::ostream is to be modified in some way, in order to allow it to function with members of the example Point class, but I want to have a better understanding than that.

Lammey
  • 179
  • 7
  • 2
    `std::ostream&` is a type which means _reference to `std::ostream`_. You should read a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), that explains these sorts of things. _which will be `std::cout`?_ Not necessarily. `std::cout` is just an object of type `std::ostream`. Any object of such type is accepted to this operator (e.g. any `std::ofstream` objects created by you). – Algirdas Preidžius Mar 29 '17 at 15:26
  • @AlgirdasPreidžius I thought objects were instances of classes? I guess I'm not clear on the distinction between types and classes. – Lammey Mar 29 '17 at 19:23
  • @JamesMachin `std::ostream` _is_ a class. In C++, objects are instances of _any_ (non-reference) type (not just classes). Classes are types declared with the `struct` or `class` keywords. All other types (e.g. `int`) are not classes. – Emil Laine Mar 29 '17 at 19:40
  • @JamesMachin Yes, objects are instances of classes. – Algirdas Preidžius Mar 29 '17 at 20:21
  • @tuple_cat Oh I see! Thanks a lot. – Lammey Mar 30 '17 at 05:26

2 Answers2

2

It means you are returning a reference to the object (in this case, it's the same object, out, that was passed in.

This is useful in chaining, it's what lets you do things like a << b << c .... without having to create a copy of the object in question.

Eyal Cinamon
  • 939
  • 5
  • 16
1

I think I understand the use of & when it represents a pass by reference inside a function parameter, but I can't see what it would do outside a function.

It means that the function returns an std::ostream by reference.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157