Originally, C++ has not put any rules on which operators you define, or whether you define them in a logically symmetric manner. You can choose to implement just 1 comparison operator , or many, though later standards have tried to regularise this somewhat.
A couple of ways you could take advantage of this:
- You may want to stop
*
from being used to get your internal object, and perhaps take its address.
Yes, ->
gets your internal object, but it doesn't leave it in an accessible state, a member must be called.
Effectively, ->
provides better OOP than *
.
Ok, yes, as HBC points out, the object caller can call the method operator->()
directly and get the object, but I would like to think that this would be an obvious code smell in any code review. I mean, you could just reinterpret_cast<> the object bytes into the pointer, if we go down that path.
Of course, yes, if you are going to implement *
, then you might as well implement ->
, but not necessarily vice-versa.
- The other thing you might do is implement
*
to give you a raw blob of data or simple struct, that you might then transmit or store, but ->
gives you a manipulator object paired with the data, so adding some object richness to a simple struct. This would be in a case where you can't simply add the richness directly, perhaps because the data was provided by an older C library.
You could even have the simple blob implement some compact c-style nested struct polymorphism, while ->
gives you an equivalent smart manipulator.
In this way ->
has provided a "view" on your data. Potentially that might be confusing, or it might be the obvious way to provide object capabilities to a piece of dumb data, that perhaps still needs to also be accessed as dumb data. All these tools are provided to API definers to use wisely.