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;
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++.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With