Again reading C++ primer 5 ed. by lipmann now I've read about Member access operators overloading. Everything is clear to me except:
struct A
{
int& operator* () {return *p;}
void foo()const{cout << "A::foo()\n";}
int* p = new int(5);
};
struct B
{
A& operator*(){return a;}
A* operator->(){return &a;}
A a{};
};
struct C
{
B& operator*(){return b;}
B& operator->(){return b;}
B b{};
};
int main()
{
C c;
//cout << *c << endl; // error.
c->foo(); // works
}
What I've learned is that the arrow operator can be overloaded and must be a member function. And if I see an expression like in main
c->foo()
I can think thatc
is either a built-in pointer to an object of a class type that has a member function calledfoo
thus fetch it. Or (like the case in main)c
is an object of a class type that has defined its own->
. So becausec
here is an object that expression callsc
's arrow operator which returns an object of classB
type which itself calls its arrow operator until it returnsB
object which its->
returns a built in pointer toA
object and in this case it is de-referenced and the resulted object is used to fetchfoo()
function. So it recursively calls itself until a built-in pointer is returned and that pointer must point to an object that has that fetched-member.What I don't understand: Why the de-reference operator doesn't work the same way? So why de-referencing
c
doesn't call the*
operator ofb
and so on as long as it returns an object that has defined it de-reference operator?Please don't argue about memory leak in
A
the purpose is for brevity.