The overload operator "operator T * ()" produces a comparison operator?

class Test { public: operator Test * () { return NULL; }; }; int main() { Test test; if (test == NULL) printf("Wtf happened here?\n"); return 0; } 

How does this code compile? How did the test get the comparison operator? Is there any implicit casting? What does this overloaded operator even mean (and do)?

+4
source share
4 answers

The overloaded operator adds a conversion from Test to Test * . Since there is no comparison operator that takes Test and NULL as arguments, all existing conversion operators are tried. operator Test * returns a type comparable to NULL , so it is used.

+7
source

Yes, you added an implicit conversion to T* , so the compiler will use it to compare with NULL.

A few other notes:

NULL is an abbreviation of 0, so that means a comparison with 0 is allowed. (However, this does not apply to other integer values. 0 is special.)

Your type can also be implicitly used in boolean contexts. That is, it is legal:

 Test test; if (test) { // ... } 

C ++ 0x allows you to specify the explicit keyword for conversion statements to prevent such things.

Implicit conversion to pointer types is often quite dubious. In addition to conversion errors that occur in unexpected cases, it can resolve dangerous situations if the object owns the returned pointer. For example, consider a string class that allows implicit conversion to const char* :

 BadString ReturnAString(); int main() { const char* s = ReturnAString(); // Uh-oh. s is now pointing to freed memory. // ... } 
+1
source

+1 for Baffe's answer. If you want to somehow expose some instance of the wrapped object through * , then perhaps you should overload -> instead of overload * .

 class Bar { public: void Baz() { ... } } class Foo { private: Bar* _bar; public: Bar* operator -> () { return _bar; } } // call like this: Foo f; f->Baz(); 

Just a thought.

0
source

You did not define your own comparison, so its compiler made one for you. however, you tried to overload the dereference operator ... which I don’t understand why.

you want to define your operator == function

read this

-3
source

All Articles