Which compiler might that be, and what is the exact code?Originally Posted by vaibhavs17
Which compiler might that be, and what is the exact code?Originally Posted by vaibhavs17
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Maybe it is a compiler bug where your compiler determined that it did not need to copy, so it ignored the fact that copying was not possible.Originally Posted by vaibhavs17
EDIT:
I tested with:
- Comeau online compiler
- g++ 4.2.4
- MinGW port of g++ 3.4.5
- MSVC8
and all of them reported at least one error, unlike your compiler.
Last edited by laserlight; 05-13-2009 at 01:31 AM.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
[QUOTE=brewbuck;861946]Yes. It would cause the following code to not work as you might expect:
The expected result would be to add 3 to the value of a. But if operator+=() returns an object instead of a reference, it will actually only add 1 to the value, because the result of the first increment is not the original object but a temporary copy of it -- the 2 gets added to this temporary then silently vanishes.Code:(a += 1) += 2;
How can we achieve the same with below peice of code?
without returning a reference, output is same with both case
Code:#include <iostream.h> class Sample { int i; public: Sample(){} Sample(int x) { i = x; } Sample operator+(const Sample& s1) { i = i + s1.i; return *this; } void show() { cout<<i<<endl; } }; void main() { Sample a(5),b(10),c(15); // a.show(); //b.show(); a =a +b +c ; a.show(); }
operator+= and operator+ are supposed to have different semantics (i.e., meaning), so trying to achieve the same strange thing as brewbuck's example does not quite make sense. Consequently, your operator+ is a poor one as it changes the current object.Originally Posted by vaibhavs17
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Thanks, i would have to stop thread now. I understood now.
Thanks for your help.