Question about & operator in C ++

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

T* dataPtr;

      

(where T

matches the template < class T >

one listed at the top of the .h file)

The class provides two "* operator overloading" methods:

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

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

      

Both just return *dataPtr

, but what does the letter " *dataPtr

" mean in plain English? And how does it match the return type " T&

"?

+1


a source to share


4 answers


The return type T & states that you are returning a reference to an instance of an object T. The DataPtr is a pointer that you are "dereferencing" (get a reference value / pointer instance) using *.



+6


a source


dataPtr is a pointer to something.

The * operator looks for a pointer, so * dataPtr (or, instead of 'is', you can say 'refer to' or 'is reference to') pointee, that is, the thing that dataPtr points to.



T & means "a reference to an object of type T" (not to be confused with T *, which means "a pointer to an object of type T").

+2


a source


*DataPtr

- the actual data to which it points DataPtr

. Both operators return a reference to T

. A reference is a type that you have to think of a different name for the value it refers to. Under the hood, it looks like a pointer, but don't think of it that way. It cannot do pointing math or be "re-enabled". One of the operators is const

and is used for an object const

, and the other is for an ordinary object.

+1


a source


The wrapper class seems to act like a C ++ pointer.

The * operator allocates a wrapper that will evaluate the item it stores (in dataPtr). What you get is a link to this content. For instance. you can assign something to the link

*intWrapper = 42;

There are two operators as there is a constant and a non-constant version. When you go looking for a constant wrapper class, you cannot assign to it (constant reference (T &) is returned)

+1


a source







All Articles