Here is a listing of C++ interview questions on “References” along with answers, explanations and/or solutions:
1. Which value can we not assign to reference?
a) integer
b) floating
c) unsigned
d) null
Answer: d
Clarification: If it can be assigned with a null value means, it is a copy of the pointer.
2. Identify the incorrect statement.
a) Reference is the alternate name of the object
b) A reference value once defined can be reassigned
c) A reference value once defined cannot be reassigned
d) Reference is the alternate name of the variable
Answer: b
Clarification: Reference is a thing which points to the valid memory address, so it can’t be redesigned.
3. Which reference modifier is used to define the reference variable?
a) &
b) $
c) #
d) @
Answer: a
Clarification: & aka ‘ampersand’ used to define a reference variable.
4. What will be the output of the following C++ code?
-
#include -
using namespace std;
-
void swap(int &a, int &b);
-
int main()
-
{ -
int a = 5, b = 10;
-
swap(a, b);
-
cout << "In main " << a << b;
-
return 0;
-
} -
void swap(int &a, int &b)
-
{ -
int temp;
-
temp = a;
-
a = b;
-
b = temp;
-
cout << "In swap " << a << b;
-
}
a) In swap 105 In main 105
b) In swap 105 In main 510
c) In swap 510 In main 105
d) In swap 510 In main 510
Answer: a
Clarification: As the function is called by reference i.e. all the changes are done directly into the memories of a and b. Therefore changes made to a and b in swap function is reflected back to main function. Hence the values of a and b in swap as well as in main function is changed.
Output:
$ g++ ref.cpp $ a.out In swap 105 In main 105
5. What does a reference provide?
a) Alternate name for the class
b) Alternate name for the variable
c) Alternate name for the pointer
d) Alternate name for the object
Answer: b
Clarification: Because we are pointing memory address using the temp variable.
6. What will be the output of the following C++ code?
-
#include -
using namespace std;
-
int main()
-
{ -
int a = 9;
-
int & aref = a;
-
a++;
-
cout << "The value of a is " << aref;
-
return 0;
-
}
a) 9
b) 10
c) error
d) 11
Answer: b
Clarification: The value is declared and it isincrementedrement, so it’s value is 10.
$ g++ ref1.cpp $ a.out 10
