my problem is a simple one. I have a class template that holds a pointer to a dynamically allocated type. I want to overload the indirection operator so that referring to the class template instance with the -> operator I get redirected as if I use the pointer contained within directly.
template<class T>
class MyClass
{
T *ptr;
...
// created dynamic resource for ptr in the constructor
};
Create myclass of some type:
MyClass<SomeObject> instance;
So what I want is instead of having to type:
instance.ptr->someMemberMethod();
I simply type:
intance->someMemberMethod();
Even thou instance
is not a pointer it behaves as if it is the pointer instance
contains. How to bridge that gap by overloading the operator?
You can just 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;
}
};
Note that, due to a design decision by the creator of the language, you can't overload the .
operator.
Also, you might think that operator*
would overload the multiplication operator instead of the dereference operator. However, this is not the case, because the multiplication operator takes a single argument (while the dereference operator takes no arguments), and because of this, the compiler can tell which one is which.
Finally, note that operator->
returns a pointer but operator*
returns a reference. It's easy to accidentally confuse them.