He couldn’t - it couldn’t have any technical reason - it just violates some expectations when using operators. So if this code is for yourself, go for it, but if it is read or used by other people, I would review it for the following reasons:
- The expected behavior is that operators of type
+= and *= return a reference to the object to which they were called after changing this object. Operators, such as + and * , return a new object (they pretty much should, because the implication is that the object they invoke does not change). They do not return a pointer to a new object because: - Nobody expects them, so they will not think about the
delete object that they return from the operator, which will cause a memory leak, and: - You cannot bind statements that return pointers; expression of type
MyClass a = b + c + d; will not work because the type of the return value ( MyClass* ) will not match the type of the argument you need to pass to the operator (possibly const MyClass& ). - Returning a link to a new object allows you to work around # 3 and still supports polymorphism, but you still stick to # 2, and worse than a couple. The same goes for operator overloading to take a pointer or link.
Ultimately, just do what makes life easier for those who will use the code - and if it's just you, you can do whatever you want. Just be careful if it falls into the hands of other people, because they will make assumptions.
Hope this helps!
Edit: Example returning a link to a new object:
A& A::operator + (const A& other) const { A* temp = new A();
But, having a little more time to think about it, I would suggest an alternative: Define the = operator for B, which takes A as its argument. Then you can do things like this:
B b1; B b2; B b3 = b1 + b2;
And it doesn't matter that b1 + b2 returned A because it was converted back to B at time = . If this works for you, I would recommend it on any other method, as it allows all operators to expect behavior.
source share