I understand that because of ABC operator=(const ABC& obj), a temporary object will be returned with value of q.i . BUT that's not looking to be the case. Even p is not getting the correct value.
Q2: What is the reason for/ when to return by reference? ABC&operator=(const ABC& obj).
EDIT 1 :
corrected code and made more understandable.
Q: the code doesn't give compile error. By returning by value ,compiler creates temporary object, which is const, so why does (i=j).modify(); work?
Also, ((i=j)=k); should not support the chaining.
Why is it so?
`foo += bar' means `foo = foo+bar'
you've got garbage because you are using an uninitialized variable in the copy constructor
you've got 90 because 80+10=90
By returning by value ,compiler creates temporary object, which is const
Where? If you want returned object to be const, you need to mark it so: constABC operator=(const ABC& obj) or mark modify as only executable on l-values: void modify() &
#include <string>
int foo() { return 100 ; }
constint const_foo() { return 100 ; } // const qualifier on prvalue of non-class type is ignored
std::string bar() { return"abc" ; }
const std::string const_bar() { return"abc" ; } // rvalues of class-type may be cv-qualified
void baz( std::string& str ) { str += "def" ; }
int main()
{
foo() += 2 ; // *** error: rvalue of non-class type can't be modified
bar() += "def" ; // fine: rvalue of (non-const) class type can be modified through a member function
baz( bar() ) ; // *** error: rvalue can't be used to initialise reference to non-const
const_bar() += "def" ; // *** error: rvalue of const class type can't be modified
}