Reputation: 9289
I would like to leave the two instances unchanged, and return a new one. Currently I am doing it this way:
class myClass {
public:
myClass operator +(const myClass &obj) {
myClass ret = *this;
// some operation
return ret;
}
// functions...
};
It works, but I am not sure, if it is the correct way
Edit
The operator +
is just an example. I'm just curious, how the immutable functions/methods should be written in C++
Upvotes: 1
Views: 87
Reputation: 47962
If myClass
is supposed to be immutable under addition, you probably want to make operator+
a free function rather than a class member. (You might have to make it a friend function.)
myClass operator+(const myClass &lhs, const myClass &rhs) {
return myClass( /* some operation */ );
}
Note that both operands are taken by const reference, so you know you cannot accidentally change them (maintaining the immutability property). You're returning a new instance of myClass
, which is now immutable. You construct and return the result in one step, because, if myClass
really is immutable, you might not be able to default construct one and then set its value.
Here's a stupid example:
class myClass {
public:
explicit myClass(int x) : m_x(x) {}
friend myClass operator+(const myClass &lhs, const myClass &rhs);
private:
int m_x;
};
myClass operator+(const myClass &lhs, const myClass &rhs) {
return myClass(lhs.m_x + rhs.m_x);
}
If you really want to implement it as a class method, the method should be marked const to ensure the implementation doesn't accidentally mutate the left-hand instance.
Binary arithmetic operators (like operator+
) are often defined in terms of the arithmetic self-assignment operators (like operator+=
), which are obviously not immutable. If we add this method to myClass
:
myClass &operator+=(const myClass &rhs) {
m_x += rhs.m_x;
return *this;
}
Then the common idiom for defining operator+
would be:
myClass operator+(const myClass &lhs, const myClass &rhs) {
myClass result = lhs;
result += rhs;
return result;
}
Now the implementation of operator+
doesn't require any of the private members of the class, so it no longer needs to be declared as a friend function.
Upvotes: 1