Question
When overloading, indirection operator (*obj
) must return reference, but member access operator (obj->
) must return pointer.
struct my_ptr
{
some_type & operator* () { return *ptr; } // returns reference
some_type * operator->() { return ptr; } // returns pointer
some_type *ptr;
};
Why is there such difference?
Answers
You can find some answers at the link above. But they doesn't completely answer why C++ was designed in such way that operator*
and operator->
return different types.
https://stackoverflow.com/a/28435758/5447906
I guess this was just the only way they could think of to implement it and it turned out a bit hackish.
operator->
allows to recursively travers through multiple objects until it will meet a real pointer:
struct A {
int foo, bar;
};
struct B {
A a;
A *operator->() { return &a; }
};
struct C {
B b;
B operator->() { return b; }
};
struct D {
C c;
C operator->() { return c; }
};
D d;
d->bar; // Provides access to A::bar.
Someone might consider this as a useful feature. But I personally do not. Consistency and obviousness would be a bigger advantage for me.