Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ overloading ->, how does it work?

Tags:

c++

Why if I overload the -> operator in this code

class subobj
{
public:
  void get()
  {
    printf("ea");
  }

};

template<typename T> class testPT
{
public:

  T* operator->()
  {
    return ptr;
  }


  T* ptr;
};


int main()
{
  subobj myobj;

  testPT<subobj> myclass;

  myclass.ptr = &myobj;



  myclass->get();


    return 0;
}

I get the "ea" string printed?

By using "myclass->", that should just return a T*, a pointer to the object. I should have done something like

myclass->->get()

to actually call the get() routine. Where am I getting wrong?

like image 502
Marco A. Avatar asked Dec 20 '22 22:12

Marco A.


1 Answers

operator-> is magic. :)

It uses chaining, that means it is called again as long as you don't return a plain pointer. When you return a plain pointer, it does one final call to operator->. When you call operator->

obj->foo;

it translates to:

(obj.operator->())->foo;

except when obj is a plain pointer.

You could even do this:

template<typename T> class testPT2
{
public:
  T* operator->()
  {
    return ptr;
  }
  T* ptr;
};

template<typename T> class testPT
{
public:
  testPT2<T> operator->()
  {
    testPT2<T> p2;
    p2.ptr = ptr;
    return p2;
  }
  T* ptr;
};

and it would still work by effectively applying operator-> three times.

like image 99
Daniel Frey Avatar answered Jan 06 '23 04:01

Daniel Frey