Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can overloaded compound assignment operators be non-member functions?

Tags:

c++

I've just discovered recently that compound assignment operators (such as operator+= or operator-=) can be overloaded outside class scope.

Consider:

class X { }; // A third party class

// The following function is legal:
X& operator+=(X& lhs, const X& rhs) {
    // ...
}

Obviously, the non-member function can't touch the private interface of X, so there's no encapsulation concern here. But it does make it seem as if it's part of X's own interface, which it clearly isn't.

It seems to me this can lead to some serious code abuse and confusing behavior. Imagine someone thought it would be nice to use it for some "clever hacks" with standard contains such as std::vector or std::map.

This is especially peculiar since other operators such as operator[] and operator-> can't be non-member functions for what I thought was this very reason.

So why is it allowed?

like image 414
Avidan Borisov Avatar asked Oct 25 '25 03:10

Avidan Borisov


1 Answers

So why is it allowed?

You are asking us to read the mind of Stroustrop. Not possible.
But a general principle of C++ is not to limit developers (we don't provide a neutered set of tools that are safe to play with. We provide the full set of razor saws and spinning flails).

It seems to me this can lead to some serious code abuse and confusing behavior. Imagine someone thought it would be nice to use it for some "clever hacks" with standard contains such as std::vector or std::map.

Yes it can.
When you abuse operator overloading it can lead to some dangerous and deadly things. Best not to do it (especially for other peoples or standard classes).

But it can provide some potentially useful situation (when you are careful). This is particularly useful when you are building a numeric "type" class as it helps with auto conversions which make the code more natural to read.

like image 115
Martin York Avatar answered Oct 26 '25 16:10

Martin York



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!