How to overload operator '->' in C ++?

I want to write a simple wrapper around another class. A small example:

class MyClass {
   ...
   int someMember();
   ...
};

class MyClassRefernence{
   ...
   MyClass* ptr;
   MyClass& operator *();
   ...
};

      

If I now have code like the following:

MyClassReference ref;
... // Init the ref and the pointer ptr.
int a = (*ref).someMember(); // this works but is nasty
int b = ref->someMember(); // Compile error

      

So my question is, is there a way to use a much prettier operator ->

instead of a construct (*...).

?

+3


source to share


1 answer


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

      



+11


source







All Articles