views:

176

answers:

4

I am looking at the .h file of a Wrapper class. And the class contains one private member:

T* dataPtr;

(where T is as in template < class T > defined at the top of the .h file)

The class provides two "* overloading operator" methods:

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

const T& operator*() const
{
  return *dataPtr;
}

Both simply return *dataPtr, but what does the notation "*dataPtr" actually return, in plain English? And how does it fit with the return type "T&"?

+7  A: 

The return type T& states that you are returning a reference of an instance of a T object. dataPtr is a pointer, which you "dereference" (get the reference value/instance of a pointer) using *.

Anzurio
+2  A: 

dataPtr is a pointer to something.

The * operator dereferences the pointer, so *dataPtr is (or, instead of 'is', you can say 'refers to' or 'is a reference to') the pointee, i.e. the thing that dataPtr is pointing to.

T& means 'a reference to an object whose type is T' (not to be confused with T* which means 'a pointer to an object whose type is T').

ChrisW
+1  A: 

*DataPtr is the actual data pointed to by DataPtr. Both operators return a reference to T. A reference is a type that you should think of like another name for the value it refers to. "Under the hood," it is similar to a pointer, but don't think of it that way. It can't do pointer math, or be "reseated." One of the operators is const and is used on a const object, and the other is used on a normal object.

Zifre
+1  A: 

The wrapper class seems to be acting like a C++ pointer.

Operator * dereferences the wrapper which will evaluate to the thing it stores (in dataPtr). What you get is a reference to this contents. E.g. you can assign something to the reference

*intWrapper = 42;

There are two operators because there is a constant and a non-constant version. When you dereference a constant wrapper class, you can't assign to it (a const reference (T&) is returned)

Dario