What's the ampersand for when used after class name like ostream& operator <<(...)?

38,135

Solution 1

In that case you are returning a reference to an ostream object. Strictly thinking of ampersand as "address of" will not always work for you. Here's some info from C++ FAQ Lite on references.

As far as const goes, const correctness is very important in C++ type safety and something you'll want to do as much as you can. Another page from the FAQ helps in that regard. const helps you from side effect-related changes mucking up your data in situations where you might not expect it.

Solution 2

Depending on the context of the ampersand it can mean 2 different things. The answer to your specific question is that it's a reference, not "the address of". They are very different things. It's very important to understand the difference.

C++ Reference

The reason to make parameters const is to ensure that they are not changed by the function. This guarantees the caller of the function that the parameters they pass in will not be changed.

Solution 3

It means that the variable is a reference. It's kind of like a pointer, but not really.

See: Reference (C++)

Solution 4

In C++ type declarations, the ampersand means "reference". In this case operator << returns a reference to an ostream object.

Since it actually returns *this it's actually the same ostream object, and means you can chain calls to operator <<, similar to this:

os << "Hello" << " " << "World" << endl;
Share:
38,135
Omar
Author by

Omar

Updated on February 23, 2020

Comments

  • Omar
    Omar about 4 years

    I know about all about pointers and the ampersand means "address of" but what's it mean in this situation?

    Also, when overloading operators, why is it common declare the parameters with const?

  • sbi
    sbi over 14 years
    The operator<< most programmers encounter the implementation of are free functions, not member functions, so there is no this involved.
  • Jesper
    Jesper over 14 years
    When you use an ampersand on a 'normal' variable, you are taking the address of the variable in memory - that's what Omar meant. With references, the & has a different meaning though.
  • nathan
    nathan over 14 years
    Jesper, you're correct. I updated my answer to make the distinction.