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;
}
};
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
@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.
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 **)
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?
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.