Overloading '*' Operator

My question is if you can overload the unary '*' operator. I'm hoping to create a smart pointer and it would be much easier to dereference the smart pointer with the dereference operator directly but I'm not entire sure if you can overload that operator. If you can overload this operator what would the method look like exactly.My initial thought is that it would look something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
template<class T>
class Smart_Ptr
{
private:
     T *m_Ptr;

public:
     // Some code...

     T *operator(void) const
     {
          return m_Ptr;
     }
};


Is this guess correct?

Thanks!
~Dudester~
closed account (1yR4jE8b)
What you have returns the pointer that your Smart_Ptr encapsulates, and won't compile (did you try?) You are trying to return a T* as a T, you should be returning *m_Ptr. I would suggest instead of returning a T, that you should return a const T&. That way, you save excessive copying for potentially large generic objects of type T.

You should also have a non-const version that returns a T&, so that you can do things like

1
2
3
4
5
6
Smart_Ptr<int> mySmartPointer;

//some code

*mySmartPointer = 4;
I think you meant this:

1
2
3
4
5
  T *operator*(void) const
     {
          return m_Ptr;
     }
Thanks for the fast replies.

@idbentley
Yeah I forgot the asterisk lol.

@darkestfright
No I hadn't tried compiling it since not enough is finished to allow it to compile. I made the changes you suggested and my IDE seems to like it so far.
Last edited on
None of these are right. Actually darkestfright was right, I just didn't read his post.

You'd need to return a reference. returning a pointer defeats the point of the * operator because then you'd have to dereference the returned pointer (ie: you'd need double **)

This is how you do it:

1
2
3
4
5
6
7
8
9
const T& operator * () const
{
  return *m_Ptr;
}

T& operator * ()
{
  return *m_Ptr;
}

Last edited on
Yeah that's what I have now though I think the last version, not the const one, is probably the most useful. Wouldn't the const declaration make it so that the value cannot be changed directly?
@Dudester

please help me on my post..i really need plzzz
closed account (1yR4jE8b)
Yes, but without a const version of the operator you would not be able to dereference a const Smart_Ptr. Sometimes you just need to point to data but you don't want to change it, so using a const Smart_Ptr could be usefull, but it would be worthless if you cannot dereference it.

The compiler will not let you use the * operator on a const Smart_Ptr if there is no const version of the operator overload.
Good point. I forgot about that possibility.
Topic archived. No new replies allowed.