function as a variable ?

Hello all,

I read the following code from C++ book by Eckel.

//: CONSTRET.CPP -- Constant return by value
// Result cannot be used as an lvalue

class X {
int i;
public:
X(int I = 0) : i(I) {}
void modify() { i++; }
};

X f5() {
return X();
}

const X f6() {
return X();
}

void f7(X& x) { // Pass by non-const reference
x.modify();
}

main() {
f5() = X(1); // OK -- non-const return value
f5().modify(); // OK
f7(f5()); // OK
// Causes compile-time errors:
//! f6() = X(1);
//! f6().modify();
//! f7(f6());
}


I dont understand that how can a function act like variable and get assigned the value. For eg. f5() = X(1) in the above code. Is a function used as a variable here?

Thank you in advance.
The function f5 returns a temporary, non-const, copy of an X instance, which may be modified (assigned to). However, this example is only demonstrating that fact--the result after its value is modified is discarded and the temporary instance is destroyed.
Thanks but I still dont get the line f5() = X(1). Why f5() is on the left hand side of the expression ?
Because we're setting the return value of f5() to something.

-Albatross
Topic archived. No new replies allowed.