Overloading the Indirectness Operator in C ++

my problem is simple. I have a class template that contains a pointer to a dynamically allocated type. I want to overload the indirectness operator, so that referring to an instance of the class template with the β†’ operator, I get a redirect, as if I were using a pointer contained inside directly.

template<class T> class MyClass { T *ptr; ... // created dynamic resource for ptr in the constructor }; 

Create a class of my class:

 MyClass<SomeObject> instance; 

So what I want instead of typing:

 instance.ptr->someMemberMethod(); 

I just type:

 intance->someMemberMethod(); 

Even you instance not a pointer that behaves as if it contains an instance pointer. How to overcome this gap by overloading the operator?

+6
source share
3 answers

You can simply overload operator-> and operator* :

 template<class T> class MyClass { T* ptr; public: T* operator->() { return ptr; } // const version, returns a pointer-to-const instead of just a pointer to // enforce the idea of the logical constness of this object const T* operator->() const { return ptr; } T& operator*() { return *ptr; } // const version, returns a const reference instead of just a reference // to enforce the idea of the logical constness of this object const T& operator*() const { return *ptr; } }; 

Please note that due to the design decision of the creator of the language, you cannot overload the operator . .

In addition, you might think that operator* will overload the multiplication operator instead of the dereference operator. However, this is not so, because the multiplication operator accepts a single argument (while the dereference operator does not accept arguments), and because of this, the compiler can determine which one.

Finally, note that operator-> returns a pointer, but operator* returns a link. It's easy to confuse them.

+11
source

Overload the operator -> :

 template <typename T> class MyClass { T * p; public: T * operator->() { return p; } // #1 T const * operator->() const { return p; } }; 

Note that both overloads do not mutate the object; Nevertheless, we decided to make # 1 non-constant, so we will bequeath the object's constness on pointee. This is sometimes called "deep propaganda" or something like that. D takes this a lot further.

+5
source

The member access operator can be overloaded to return a pointer to the object to access:

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

You may also need the deference operator so that it feels more like a pointer; instead, the link is returned:

 T & operator*() {return *ptr;} T const & operator*() const {return *ptr;} 
+3
source

Source: https://habr.com/ru/post/905854/


All Articles