I've tried searching around for the answer, but no luck so far. My question is - why must reference variables need to be initialized when they are defined? Is it a technical reason, or is it just something the standard doesn't allow?
Take this code for example:
int number = 42;
int& numberRef;
numberRef = number;
Above isn't allowed, but the code below is:
int number = 42;
int& numberRef = number;
Why can't the compiler treat an uninitialized reference variable like an uninitialized pointer? Is there something I'm missing here?
If a reference is uninitialized, there is no way to initialize it, since any attempt to assign to a reference always assigns to its referent.
int& numberRef; // pretend this is allowed
numberRef = number; // copies number into some random memory location
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