13
class NullClass{
    public:
    template<class T>
        operator T*() const {return 0;}

};

I was reading Effective C++ and I came across this class, I implemented the class and it compiles. I have a few doubts over this:

  1. It doesn't have a return type.

  2. What is this operator.

  3. and what it actually does.

user2614516
  • 387
  • 4
  • 8
  • Perhaps a duplicate of something like this: http://stackoverflow.com/questions/1307876/how-do-conversion-operators-work-in-c – Bill Lynch Jul 31 '14 at 13:44
  • 2
    It's a [used-defined conversion operator](http://en.cppreference.com/w/cpp/language/cast_operator). It allows instances of `NUllClass` to be implicitly converted to a pointer of any type. – Some programmer dude Jul 31 '14 at 13:44
  • Conversion or casting operator. – Niall Jul 31 '14 at 13:44

1 Answers1

15

That's the type conversion operator. It defines an implicit conversion between an instance of the class and the specified type (here T*). Its implicit return type is of course the same.

Here a NullClass instance, when prompted to convert to any pointer type, will yield the implicit conversion from 0 to said type, i.e. the null pointer for that type.

On a side note, conversion operators can be made explicit :

template<class T>
explicit operator T*() const {return 0;}

This avoid implicit conversions (which can be a subtle source of bugs), but permits the usage of static_cast.

Quentin
  • 62,093
  • 7
  • 131
  • 191