C++ Programming - References - Discussion

Discussion Forum : 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.
Only 1 is correct.
Only 2 is correct.
Both 1 and 2 are correct.
Both 1 and 2 are incorrect.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
9 comments Page 1 of 1.

JerryO said:   4 years ago
I agree @Singh,

But then shouldn't statement #2 be "the type of the function must be an L-value"?

That's what it means to be on the LEFT side of an assignment statement?

Baribua said:   8 years ago
Great explanation @Singh.

Thanks.

Singh said:   10 years ago
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.

Singh said:   10 years ago
#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;
}

Vijay said:   1 decade ago
Reference must be initialize at the time of declaration. Therefore R-value required.

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

Chanchal said:   1 decade ago
When we are declare a function we must specifies there return type because the function always return value by default they return int value.

Rajil said:   1 decade ago
Reference must be initialize at the time of definition. Therefore it must be at R-value place.

Somebody can write an example.

Aakash said:   1 decade ago
Reference value because call by ref reflects changes in original arguments.

Christian said:   1 decade ago
2. The type of the function must be a R-value.

What is R-value mean?

Post your comments here:

Your comments will be displayed after verification.