Question

What an operator is overloaded here?

operator T * ()

I know that the operator method has the following structure:

type operator operator-symbol ( parameter-list )

Assume we have the following code

template<typename T> class SmartPtr
{
public:
    SmartPtr(T* data): member(data) {}
    T* member;      
    T& operator * () { return *member; }  //usage: *TObj    
    T*& operator () () { return member; }  //usage: TObj()
    operator T * () { return member; }   //usage: ???
};

No compilation errors if you try it on the ideone. So what is going on here?

ADD: Am I right that static_cast<T*>(TObj) makes a call of the operator T *? I've tried it here.

Was it helpful?

Solution

That's a conversion operator, which allows the class to be converted to T*. Usage:

T * p = TObj;

It's probably a bad idea for a smart pointer to provide this, as it makes it easy to accidentally get a non-smart pointer. Standard smart pointers provide explicit conversion via a get() function instead, to prevent accidental conversions.

OTHER TIPS

This operator is invoked when a SmartPtr object appears in an expression, but the compiler has no functions available to resolve the usage made thereof: if it's legal to use a T* where the SmartPtr appears, the operator T*() function is called to generate one. This means my_smartptr->my_T_member can work, as can f(T*); f(my_smart_ptr_to_T);. Similarly, iostreams have an operator bool() in C++11 (operator void*() in C++03 for reasons too tedious to bother with). It's kind of the opposite of an implicit constructor from a single parameter, where should the compiler not find a valid match using the parameter, it may try to construct an object using that parameter to use instead.

operator T * () { return member; }

it is a so-called conversion operator. It converts an object of type SmartPtr to type T *. Moreover it is an implicit conversion opertaor. So when the compiler awaits an object of type T * you can use instead an object of type SmartPtr. You could make this conversion operator explicit if you would add keyword explicit. For example

explicit operator T * () { return member; }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top