user34537
user34537

Reputation:

Why is this operator called in C++?

I dont understand, why is the aaa operator called in the 2nd last line?

#include <iostream>

class MyClass
{
private:
    typedef void (MyClass::*aaa)() const;
    void ThisTypeDoesNotSupportComparisons() const {}
public:
    operator aaa() const { return (true) ? &MyClass::ThisTypeDoesNotSupportComparisons : 0; }
};

int main()
{
    MyClass a;
    MyClass b;

    if(a && b) {}
}

Upvotes: 4

Views: 221

Answers (3)

sashoalm
sashoalm

Reputation: 79467

It looks like a type cast operator. Oops, never mind, misread 'why is this operator called' for 'what is this operator called'


Ok, I tested your code and examined it some more. So operator aaa is a type cast to type aaa. Type aaa is a pointer to a member function of type void func(). ThisTypeDoesNotSupportComparisons is a function of type aaa. operator aaa gets called and returns the pointer to function.

I think it is called because the if allows to use pointers to functions as well. You can test if a pointer is NULL or not, and this is the closest the compiler can find, so if calls the operator aaa and tests if the pointer returned is zero.

Upvotes: 0

Yochai Timmer
Yochai Timmer

Reputation: 49251

The compiler searches for the best match for (a && b).

Because the class doesn't have an operator that turns MyClass to a boolean, it searches for the best cast.

operator aaa() const is a cast to an aaa type pointer. Pointers can be evaluated in an if sentence.

Overloading typecasts

Conversion Functions (C++)

Upvotes: 6

Bo Persson
Bo Persson

Reputation: 92261

Your variables are used in an expression. The type itself does not have an operator&& defined for it, but it is convertible to a type (a pointer) that can be used in the expression. So the conversion operator is called.

Upvotes: 3

Related Questions