Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 540
Omar Avatar asked Oct 15 '09 12:10

Omar


People also ask

What does & mean after a class name?

What does '&' after class name mean? The ampersand is part of the type in the declaration and signifies that the type is a reference. Reference is a form of indirection, similar to a pointer.

What does the ampersand (&) signify C++?

The ampersand symbol & is used in C++ as a reference declarator in addition to being the address operator. The meanings are related but not identical. If you take the address of a reference, it returns the address of its target. Using the previous declarations, &rTarg is the same memory address as &target .

What is the use of ampersand operator?

The ampersand is the address of operator. It returns the memory location of a variable and that's the only way it's used, prefixed to a variable like the engine on a train.

What symbol is appended to the end of a variable type name?

In computer programming, a sigil (/ˈsɪdʒəl/) is a symbol affixed to a variable name, showing the variable's datatype or scope, usually a prefix, as in $foo , where $ is the sigil.


2 Answers

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.

like image 145
Kyle Walsh Avatar answered Oct 07 '22 20:10

Kyle Walsh


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.

like image 32
nathan Avatar answered Oct 07 '22 20:10

nathan