Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why reference variable needs to initialise while declaring

Tags:

c++

It is pretty simple question i had a doubt and i thought to ask everyone,

as we know we can declare reference as

int bar;
int &foo = bar;

My question is what is the reason behind this initialisation? Why this is must? Also Why i don't need to initialise pointers while declaration?

int bar;
int *p;
p = &bar;
like image 768
Dipak Avatar asked Aug 31 '25 22:08

Dipak


2 Answers

A reference, by definition, must refer to a valid object or POD type. It's not allowed to be uninitialized, referring to nothing in particular. Also, once initialized it can't be changed to refer to something else. Thus the only place it makes sense to initialize it is in the declaration (or if it's a member variable, the initializer list of the class constructor).

Other languages allow null references and reassigning references, but that's not the way they work in C++.

like image 136
Mark Ransom Avatar answered Sep 03 '25 12:09

Mark Ransom


While pointers can be NULL (i.e., point to nothing), a reference must always point to something; it has no NULL state. Thus, it can't be created without being initialized.

like image 29
Phil M Avatar answered Sep 03 '25 13:09

Phil M