6

Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?

I was reading an article on rvalues in order to understand universal references from the new C++ Standard and found the following as an example of lvalue

// lvalues:
//
int i = 42;
i = 43; // ok, i is an lvalue
int* p = &i; // ok, i is an lvalue
int& foo();
foo() = 42; // ok, foo() is an lvalue
int* p1 = &foo(); // ok, foo() is an lvalue

What does int& foo(); mean here?

Community
  • 1
  • 1
codingTornado
  • 113
  • 1
  • 5

4 Answers4

5
int& foo(); 

Declares a function that returns a reference to an int. You can see it as similar to

int* foo();

Except that the return value cannot be null.

The syntax is a bit different, though, since int* foo(); would be used as *(foo()) = 42;, and int& foo(); as foo() = 42.

You can read more about references in the FAQ.

Community
  • 1
  • 1
slaphappy
  • 6,894
  • 3
  • 34
  • 59
5

Say the body of foo was this:

int & foo()
{
   static int i = 0;
   return i;
}
foo() = 30;

That would set the static int, i, to 30;

A more practical example is a class returning a reference to itself

class foo
{
public:
   foo() {}

   foo& addString() {
      /* AddString */ 
      return *this;
   }

   foo& subtractSomething() { 
      /* Subtract Something */ 
      return *this; 
   }
}

Then use it like:

foo f;
f.addString().subtractSomething();

class operators do this - so you can do this:

foo a, b c;

foo d = a+b+c;

Where the + operator is defined as:

foo & operator+(const foo& f)
Ryan Guthrie
  • 688
  • 3
  • 11
1

int& foo(); means that the function foo() returns a reference type. That is, its return value can be modified:

foo() = 42;

means "modify the referenced value returned by foo".

0

You're defining a function prototype with a reference as the return value. The function returns a reference to an integer. As such its return value can be set to another value.

Mario
  • 35,726
  • 5
  • 62
  • 78