Quick C++ semantic question

Status
Not open for further replies.

Feshy

Ars Tribunus Militum
2,777
I'm looking at overloading an operator. Specifically, the parenthesis. But NOT someclass() parenthesis.. how would I overload this:

if(myclass)

? In this case, "myclass" would be evaluated to see if it is zero or non-zero, yes? Is that done by treating it as an unsigned that is either zero or greater-than, i.e. using whatever I have defined as the result of

0 < myclass

? Or is it evaluated by seeing if it is actually euqal to zero, i.e.

0 == myclass

? Or is it evaluated by seeing if it is NOT equal to zero, i.e.

0 <> myclass

Or is it compiler-dependant? Or some completely different method that I am missing from staring at this too long. . .
 

Feshy

Ars Tribunus Militum
2,777
The if probably attempts to convert your class into a bool or an int; it should be easy to figure out which.

Gotcha. . . I think... overloaded conversion operator, THEN compared to zero.

Probably bool... unless you're in the antiquated development environment I've got at work, where there IS no bool. . . (no... really...)

So, I guess it might be somewhat compiler-dependent, then?
 

earl

Well-known member
3,066
test.cpp
code:<HR>
Code:
#include<stdio.h>
#include"test.h" 
 
 
Ctest::Ctest()
{
  printf("constructor\n");
}
 
int main(int argc, char** argv)
{
  Ctest bleh;
  if (bleh)
    printf("true\n");
  else
    printf("false\n");<P>
  printf("hi\n");
  return 0;
}

test.h
code:<HR>
Code:
class Ctest
{
  public:
    Ctest();
    operator int() const {return -1;}
    operator bool() const {return true;}
};

With g++ something-or-other, it calls the boolean operator.

-earl-
 
Status
Not open for further replies.