It is a while ago that I was really into C++, however I think I see what's going wrong here:
Your operator+ in line 7 of your firt code snippet returns a Number& - a reference to a Number object. In line 9, you create a Number object as a local variable, and in line 11 you return a reference to that local object.
This goes wrong, because as soon as the method ends, the local variable is cleaned up, and the reference that you return becomes invalid - it refers to a variable that no longer exists, so you'll get undefined results. It is exactly the same as returning a pointer to a local variable.
Instead of returning a reference, your operator+ should just return a Number object:
Thanks for help, it is working However I have a one more question. When I was learning cpp, which was some years ago, I've read that objects are always passed to functions as reference, and functions return reference to an object, so there is no difference if I write MyClass or MyClass&. Ofcourse I know that there is a difference, but I've allways wondered why? Did I learn something wrong? Can objects be passed to functions by value? Or is there an oder mechanism which I mistook? Or maybe it is only a tip to pass objects as a reference in order to create faster applications?
Lazaro Caruso wrote:I've read that objects are always passed to functions as reference, and functions return reference to an object, so there is no difference if I write MyClass or MyClass&.
Are you sure that was about C++, or are you confusing it with another language such as Java? Because for C++, that's not correct.
In Java, variables of non-primitive types are references. Not in C++: variables that are not pointers or references are just the value itself, which can be a complete object. You can pass complete objects as arguments and return them, as values. That's not possible in Java. Note that in Java the automatic memory management system keeps track of references to objects, and it makes sure the object is not discarded as long as there are any live threads that have references to it. C++ doesn't have automatic memory management, so it will not automatically keep objects around that you reference.
You should watch out with this in C++, because if the objects are large, passing them directly as values can be costly (the whole object will be copied when you pass it as a value).
Joined: Jan 03, 2011
You are right, I had probably memorized something badly.
Hmmm I've just noticed that I have one more problem.
operator+ returns "Number", but operator= needs "Number&", so when I try this:
a = b + c ;
It gives error:
error: no match for 'operator=' in 'a = Number::operator+(Number&)(((Number&)(&c)))'
note: candidates are: Number& Number::operator=(Number&)
I don't see creating operator=(Number) as good solution.