in C++ by (15.1k points)
0 like 0 dislike

What's define ampersand sign (&) when used after data type (class name for complex data type) in C++, i.e. ampersand between data type and variable name, like this:

double& dbl = val;
int &cstm = var;
Custom & cstm = instncOfCstm;
Or when ampersand used in pointing function return type:
Custom& doSomething(…);
Or when ampersand used in pointing function arguments:
bool doSomething(Custom& cstm, Bar& bar);
Or when ampersand used in overloading operators (special case of function declaration):
ostream& operator<<(…);

I know all about pointers and what ampersand means a take address operation ("address of"), but what's it mean in this case?

  • c++ ampersand after data type
  • c++ ampersand appended to a class name
  • c++ ampersand with data type
  • c++ ampersand between data type and name of variable

1 Answer

0 like 0 dislike
by (15.1k points)

It's means that the variable is a reference. It not a take address operation ("address of"). Depending on the context of the ampersand sign (&) it can mean 2 different things in C++ - "address of" and reference. They are very different things. It's very important to understand the difference. In C++ type declarations, the ampersand means "reference". Same in case when ampersand used with function return type, you are returning a reference. How you can see, strictly thinking of ampersand as "address of" will not always work. Because in C++ ampersand also denote reference variable. It's kind of like a pointer, but not really. See/read information about references in C++.

Please log in or register to answer this question.