I tried to refresh my c++ knowledge and found a strange behaviour. When I declared a class and overloaded an operator in it, I forgot that the operator has a return value. This caused some behaviour I cannot explain. Here is the code:
class myClass{
double i;
myClass(double value): i(value){}
myClass operator+ (const double ¶m)
{
i = i + param;
}
};
So, the operator+ should return a value with type myClass, but instead it just adds param to member i. When I tried this operator in my program by
myClass A(10.5);
A+10.0;
the result is A.i = 20.5, as i would expect. But if I change the code to
A = A + 10.0;
The result is A.i = nan, or some very small number. I realized, that the operator+ should return a value by definition, but I didn't add return to its definition. My question is, what is returned in this case? Some random garbage value from memory? Why does the compiler not enforce to add a return to the operator definition if it is expected to return a value with myClass type?