f()=X()??

Hey,

Please Correct me if I am wrong,when an expression contains '=' sign then the expression on the RHS of '=' sign is evaluated and the result is assigned to the variable or the identifier on the LHS of '=' sign, right?

But I am confused as what happens in case of two functions and an = sign.
Recently I found this Example in my book:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class X{
  int i;
  public:
   X(int ii=0);
   void modify();
};

X::X(int ii) {i=ii;}

void X::modify() {i++;}

X f5() {return X();}

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

void f7(X& x) {x.modify();}

int main()
{
  f5()=X(1);
  f5().modify();
  //f7(f5());
  //f6()=X(1);
  //f6().modify();
  //f7(f6());
}


I have not ever seen some expression like this ever before:

 
f5()=X(1);


So can someone please tell me which of the above function will be called first f5() or X()? moreover is it a good programming practice to use two or more functions in a same expression and assigning the result to a result of third function?Also can someone please share with me some more examples in which two or more functions are used in a same expression like this.

Well, this is the first time that i have seen one function being equated to other and I am not liking it, this expression really feels so odd.Would be really helpful if someone can share more examples like this one so i can get along with thse kinds of statements.

Thank You for reading.
The order of f5() and X(1) is not specified. It's up to the compiler to decide. The order doesn't make a difference in this case anyway.

f5() returns a temporary X object. X(1) also gives you a temporary object with i==1. Then operator= is used to copy the content so that both temporaries have i==1; Both objects are destroyed at the end of the line.

I know it doesn't look very useful but remember that operator= is a member function just like modify() is. You could have written line 20 as f5().operator=(X(1));. You can define operator= to do something else, like printing a message, but in that case it is probably better to name it something else.
f5().print(); <-- this make more sense?
Last edited on
so, is = a member function of every class by default?? Thanks for sharing this useful info.
so, is = a member function of every class by default?

Yes.
Topic archived. No new replies allowed.