C++ Programming - References - Discussion

Discussion :: References - General Questions (Q.No.3)

3. 

Functions can be declared to return a reference type. There are reasons to make such a declaration/Which of the following reasons are correct?

  1. The information being returned is a large enough object that returning a reference is more efficient than returning a copy.
  2. The type of the function must be a R-value.

[A]. Only 1 is correct.
[B]. Only 2 is correct.
[C]. Both 1 and 2 are correct.
[D]. Both 1 and 2 are incorrect.

Answer: Option C

Explanation:

No answer description available for this question.

Christian said: (May 23, 2013)  
2. The type of the function must be a R-value.

What is R-value mean?

Aakash said: (Aug 4, 2013)  
Reference value because call by ref reflects changes in original arguments.

Rajil said: (Jan 12, 2014)  
Reference must be initialize at the time of definition. Therefore it must be at R-value place.

Somebody can write an example.

Chanchal said: (Nov 10, 2014)  
When we are declare a function we must specifies there return type because the function always return value by default they return int value.

Vijay said: (Dec 9, 2014)  
Reference must be initialize at the time of declaration. Therefore R-value required.

E.g: int &z = a(R-value).

Singh said: (May 8, 2015)  
#include <iostream>
#include <ctime>

using namespace std;

double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0};

double& setValues( int i )
{
return vals[i]; // return a reference to the ith element.
}

// main function to call above defined function.

int main ()
{

cout << "Value before change" << endl;
for ( int i = 0; i < 5; i++ )
{
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}

setValues(1) = 20.23; // change 2nd element
setValues(3) = 70.8; // change 4th element

cout << "Value after change" << endl;
for ( int i = 0; i < 5; i++ )
{
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}
return 0;
}

Singh said: (May 8, 2015)  
A C++ program can be made easier to read and maintain by using references rather than pointers. A C++ function can return a reference in a similar way as it returns a pointer.

When a function returns a reference, it returns an implicit pointer to its return value. This way, a function can be used on the left side of an assignment statement.

Baribua said: (Jan 24, 2017)  
Great explanation @Singh.

Thanks.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.