I have a problem which I can't seem to find others who have the same problem. I have a custom class, call it foomatic. I want to define how foomatic is reference in assignments with =. For example, consider the following code:
objectName = object1;
object1Size = object1;
Here, I have control of the object on the right of the =...the rvalue. I don't have control over the objects on the left side of the =. I know that I could extend string class in this example, but I don't want to create a new class for every custom object. This means I would have to go through ALL my source code and update the extended string class, for example, just so I can make the above code valid. Furthermore, I am not even aware of a way to override operator= for primitive types, such as int, or char *, etc.
You need to override the = operator in the global namespace (outside of your class).
No. That isn't possible. You can do that with other binary operators, but the assignment operator must be a non-static member function. Zaita's solution should work, but he better declare the operators const:
Ropez: That's more in his implementation. Maybe he wants to alter the returned name at some point. Because it's being returned by value rather than reference the const keyword would only be a preference thing.
Nothing. Because the operator returns a value, not a reference.
"Const methods are a way for us to say that a method does not modify the member variables of a class. It's a hint both to the programmer and the compiler that a given method doesn't change the internal state of a class."
"is often missed is that by extension a const method cannot call a non-const method (and the compiler will complain if you try). Since we assume that a non-const method does modify the member variables of our class, we can't call that from a method where we've promised not to do just that."
What exactly is set as constant with ropez's solution?
The implicit first parameter.
All member function has a "hidden" parameter called this, e.g.
1 2 3 4 5 6 7 8 9
// Member function:
// Basically the same as:
void f(A* this);
// Const member function:
void A::f() const;
// Basically the same as passing "this" as a const pointer:
void f(const A* this);