I understand the reference variable concept. It’s an alias to the other variable.
int varA = 100;
int &varB = varA;
Here varB is a referring to varA, both pointing to same memory location. Changes to one variable reflect in the other.
Question:
-
a)
int &c = 100;
What is the meaning of the above statement, and how does it differ from the following?
b)int c = 100; -
Is there any scenario where we need to use 1(a) rather than 1(b)?
All are correct, except this:
It will give compilation error both in C++03, and C++11. It is because it attempts to bind non-const reference to a temporary object (created out of
100) which is disallowed.In C++11, you could do this, however:
It is called rvalue-reference.
You could bind const reference to a temporary though (both in C++03, and C++11):
–
It simply defines an object called
cand initializes it with100. No reference here.