ampersand (&) at the end of variable etc

snipor picture snipor · Jan 1, 2014 · Viewed 38.4k times · Source

I am a C++ noob and i've a problem of understanding c++ syntax in a code. Now I am quite confused.

class date
{
private:
int day, month, year;
int correct_date( void );
public:
void set_date( int d, int m, int y );
void actual( void );
void print( void );
void inc( void );
friend int date_ok( const date& );
};

Regarding to the '&' character, I understand its general usage as a reference, address and logical operator...

for example int *Y = &X

What is the meaning of an & operator at end of parameter?

friend int date_ok( const date& );

Thanks

edit:

Thanks for the answers. If I have understood this correctly, the variable name was simply omitted because it is just a prototype. For the prototype I don't need the variable name, it's optional. Is that correct?

However, for the definition of the function I definitely need the variable name, right?

Answer

Aniket Inge picture Aniket Inge · Jan 1, 2014

const date& being accepted by the method date_ok means that date_ok takes a reference of type const date. It works similar to pointers, except that the syntax is slightly more .. sugary

in your example, int* Y = &x makes Y a pointer of type int * and then assigns it the address of x. And when I would like to change the value of "whatever it is at the address pointed by Y" I say *Y = 200;

so,

int x = 300;
int *Y = &x;
*Y = 200; // now x = 200
cout << x; // prints 200

Instead now I use a reference

int x = 300;
int& Y = x;
Y = 200; // now x = 200
cout << x; // prints 200