Reputation: 1444
noGiven a private Member pData
private:
T* pData; // Generic pointer to be stored
Below is the overloaded implementation of * and ->
T& operator* ()
{
return *pData;
}
T* operator-> ()
{
return pData;
}
We call the same from the main as shown below:
void main(){
SP<PERSON> p(new Person("Scott", 25));
p->Display();
}
I cannot understand how -> and "*" operator overloading will work here?
or to be more clear how p->Display();
will be interpreted?
Upvotes: 1
Views: 123
Reputation: 56863
The ->
operator is special. When it returns an object, it is automatically applied again. If it returns another object it is also applied again, until finally a plain pointer is returned. This is called chaining, the plain pointer is finally dereferenced and the chain stops.
p->Display()
is therefore interpreted like this:
p->Display(); // Compiler sees this
T* tmp = p.operator->(); // First applied operator-> (the one you provided)
tmp->Display(); // since T* is a pointer itself, operator-> (the built-in one for pointers) is applied
Upvotes: 2