C++ Programmer Question:

Download Job Interview Questions and Answers PDF

Explain how to create a reference variable in C++?

C++ Programmer Interview Question
C++ Programmer Interview Question

Answer:

Appending an ampersand (&) to the end of datatype makes a variable eligible to use as reference variable.

int a = 20;
int& b = a;

The first statement initializes a an integer variable a. Second statement creates an integer reference initialized to variable a
Take a look at the below example to see how reference variables work.

int main ()
{
int a;
int& b = a;

a = 10;
cout << "Value of a : " << a << endl;
cout << "Value of a reference (b) : " << b << endl;

b = 20;
cout << "Value of a : " << a << endl;
cout << "Value of a reference (b) : " << b << endl;

return 0;
}
Above code creates following output.

Value of a : 10
Value of a reference (b) : 10
Value of a : 20
Value of a reference (b) : 20

Download C++ Programmer Interview Questions And Answers PDF

Previous QuestionNext Question
Explain me what will i and j equal after the code below is executed? Explain your answer.

int i = 5;
int j = i++;?
Tell us why pure virtual functions are used if they don't have implementation / When does a pure virtual function become useful?