Alex Rivera | Logout

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

Asked 2009-10-15T12:20:11.437
33

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?

Edit
Report

2 Answers

10

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.

answered 2009-10-15T12:25:00.967
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;
answered 2009-10-15T12:22:58.380

Your Answer