C++ operator overloading for wrapper class

1.2k views Asked by At

I'm using a class called Pointer, which is some kind of a wrapper around a real pointer I guess. I think this line of code in this class enables me to get the real pointer:

 operator const T* () const;

What does this mean exactly? How can I call this?

Suppose myPointer is a Pointer<int16_t> object. I should be able to get the int_16* object which wraps this pointer, by using the operator overloading above, but I don't know how.

Edit

Based on the answers belo, I now know I can do this:

const int16_t* myRealPointer = myPointer;

Now suppose I need to call a function which expects a int16_t* parameter (so without the const). What can I do to pass this myRealPointer object to that function?

2

There are 2 answers

3
anderas On BEST ANSWER

This is a conversion operator. For example, you could use it to convert a Pointer<T> to a real T* and, additionally, use it everywhere a T* is expected:

Pointer<float> p(new float);
const float* p2 = p;

In this case, the operator is only defined for the conversion to const raw pointers, so float* p2 = p; would not work. (Also there might be a similar operator for that case.)

0
Vlad from Moscow On

This is not operator () as you wrote in the title of the question. It is an implicit conversion operator that converts an object of type Pointer<T>to an object of type T *. So everywhere where an object of type T * is expected you may use an object of type Pointer<T>.

For example

Pointer<int16_t> myPointer;

/* initialization of myPointer */

if ( myPointer != NULL ) std::cout << myPointer << std::endl;

In this code snippet the operator is called twice: in the if condition and in the output statement.

If you do not want such an implicit conversion you could declare the operator with function specifier explicit. For example

explicit operator const T* () const;

If you want indeed to write operator () that is named like the function call operator then it can look the following way

const T * operator ()() const;

In this case the above code snippet would look differently

Pointer<int16_t> myPointer;

/* initialization of myPointer */

if ( myPointer() != NULL ) std::cout << myPointer() << std::endl;