lital maatuk
lital maatuk

Reputation: 6241

& of a variable

I read somewhere that in C++ you can't give a definition like:

int& a;

but only:

int b;  
int& a=b;  

Since & is a reference of the other variable, it cannot be defined separately. On the other hand, I see it defined separately in code all the time.

Could someone explain to me how can you define

int & a;   

without specifying a reference to which variable it is?

Upvotes: 1

Views: 207

Answers (4)

Foo Bah
Foo Bah

Reputation: 26251

& does not define an alias; it is a reference, which is like a stripped down pointer. They cannot be reinitialized, which is why you must specify the "alias" at the beginning.

Upvotes: 1

Matthieu
Matthieu

Reputation: 4620

Considering the C++ standard, you cannot declare an unitialized reference by itself :

There shall be no references to references, no arrays of references, and no pointers to references. The declaration of a reference shall contain an initializer (8.5.3) except when the declaration contains an explicit extern specifier (7.1.1), is a class member (9.2) declaration within a class declaration, or is the declaration of a parameter or a return type (8.3.5); see 3.1. A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bitfield. ]

—ISO/IEC 14882:1998(E), the ISO C++ standard, in section 8.3.2 [dcl.ref]

Upvotes: 5

Mathieu JVL
Mathieu JVL

Reputation: 345

You would have to use a pointer. The reference notation comes down to the same as a pointer, only it cannot be null. That's why you cannot just declare a variable as int & a. Maybe there is an exception for members of a class (i.e. they can be defined as references), but the references have to be set in the constructor (see PigBen's answer).

Upvotes: -1

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

You might see it in a class, but you need to assign it upon initialization in all constructors, e.g.

class X
{
    int & a;
public:
    X(int & i) :a(i) {}
};

Upvotes: 7

Related Questions