Variable declaration with const and reference
Question
I am confused about variable declarations with references. I read some pages and that made me more confused so preferred to ask here.
I was asked 4 questions in a C++ interview; which one of them is wrong and why?
(1) int & n;
(2) const int & n=15;
(3) float x; const int & n =x;
Could some one please explain which in incorrect and why?
Solution
tl;dr References must be initialised on declaration (either directly or in the class initialisation).
int& n;
This leaves the reference n
uninitialised. References must be initialised on declaration.
const int& n = 15;
Nothing wrong here. The reference to a const int
is initialised to 15
.
float x; const int& n = x;
The float
is ok, but a bad idea to be left uninitialised. The reference n
being initialised to x
(float/integral conversions apply), it's not a great idea either.
OTHER TIPS
A reference must always be initialized.