C++ operator help
Hello!
simple C++ operator... I need some help.
Q.: Which is correct? And Which is commonly used.
XVector operator + (const XVector& vec) const
{
XVector tmp;
tmp.x = x + vec.x;
tmp.y = y + vec.y;
tmp.z = z + vec.z;
return tmp;
}
OR
XVector& operator + (const XVector& vec) const
{
XVector tmp;
tmp.x = x + vec.x;
tmp.y = y + vec.y;
tmp.z = z + vec.z;
return tmp;
}
Thx.
The first. Binary + should return a new object, not a reference. Regardless of operator etiquette, the second is returning a reference to a local, which is a pretty bad thing.
However, generally binary + would be implemented as a free function and implemented using the += operator:
Obviously += needs to be implemented, but the implementation of that should be more obvious.
The less stuff you implement as member functions, the less stuff you have depending upon internal details of the objects in question, so as a general rule, if you can implement an operator as a free function, it is probably a good idea.
HTH
However, generally binary + would be implemented as a free function and implemented using the += operator:
XVector operator+(const XVector &A,const XVector &B){ XVector C=A; C+=B; return C;}
Obviously += needs to be implemented, but the implementation of that should be more obvious.
The less stuff you implement as member functions, the less stuff you have depending upon internal details of the objects in question, so as a general rule, if you can implement an operator as a free function, it is probably a good idea.
HTH
Returning a reference to a local variable is bad mojo. As soon as the function exits, the local variable's value is undefined... but then the next thing that happens is that its value is read, to assign to the result variable or wherever you're using it. This is one of those particularly bad bugs that will work "sometimes", and then pop up in response to a seemingly unrelated change. Luckily, most compilers catch this situation and issue a warning. Make sure that whatever compiler you're using, you set warnings to a high level (-Wall on GCC, level 3 on MSVC [level 4 is just stupid]).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement