Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foo() = 42; <- How can this be possible? [duplicate]

Tags:

c++

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?

like image 532
codingTornado Avatar asked Nov 09 '12 17:11

codingTornado


2 Answers

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)
like image 75
Ryan Guthrie Avatar answered Oct 23 '22 06:10

Ryan Guthrie


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.

like image 36
slaphappy Avatar answered Oct 23 '22 07:10

slaphappy