Lets take some code samples:
! 4 > 0;
From C++ standard we know, that negation will be done first, than comparison. But if we expand this example a little:
#include <iostream>
class Test
{
public:
bool operator!() const
{
std::cout << "operator!" << std::endl;
return false;
}
bool operator>(const int &) const
{
std::cout << "operator>" << std::endl;
return false;
}
};
int main(int argc, char * argv[])
{
Test t;
std::cout << "t > 0;" << std::endl;
t > 0;
std::cout << "! t > 0;" << std::endl;
! t > 0;
std::cout << "!t.operator>(0)" << std::endl;
! t.operator>(0);
return 0;
}
Output of this program will be:
t > 0;
operator>
! t > 0;
operator!
!t.operator>(0)
operator>
- First call (control call) is quite clear. We check if operator we want is called.
- Second call is proof of what I stated first. negation operator is called first, than on result (bool) operator> is called.
- Third call is what bothers me.
And here pops my question. Why SomeObjInstance > 0
call is different from SomeObjInstance.operator>(0)
. I know that it's not common to call operators in second manner (as members), but why this calls differs? I always tought that SomeObjInstance > 0
is translated under the hood to member call SomeObjInstance.operator>(0)
or function call bool operator>(const Test &, int)
if member operator is not present.
Where this behaviour is described in C++ standard, or maybe is this some kind of undefined behaviour?