mercredi 19 avril 2017

How does C++ select which operator to use in if (class)?

I have a class which mimics the behaviour of an integer. It has the following overloads:

class myInt
{
    ...
    operator int() const { return val; }
    operator bool() const { return 0 != val; }
    operator myInt *() { assert(0); return NULL; } // Cast to pointer not supported
    ...
private:
    int val;
}

When I use it as follows:

myInt i = 0;
if (i) ...

it hits the assert in the pointer cast.

Why does the C++ pick this instead of the bool operator inside the if?

Cheers,

Ian






Comments
0 Comments

0 commentaires:

Enregistrer un commentaire