Overloading bool function

Apr 13, 2017 at 7:47pm
I keep having trouble trying to overload the boolean function. I cannot figure out the syntax. Below is what I currently have. What I want it to do is receive a variable from an Integer class that I made then return false if its 0 and true in all other cases. I have read online to use overload operator bool()but I wasn't able to figure out how and have tried using variations of the code below. I am not sure how to receive the Integer and also if anything needs to be returned in the header. The syntax appears to be very different that the other operators (<, ==. etc ) that I have succesfully overloaded.

1
2
3
4
5
6
7
Integer::operator bool() const {
 if ( num == '0') {
  return false;
 } else {
  return true;
 }
}


My other operators have used this syntax
1
2
3
bool operator!= (const Integer int1, const Integer int2) {
  //stuff
}
Last edited on Apr 13, 2017 at 7:48pm
Apr 13, 2017 at 7:56pm
bool is a type, not a function that I am aware of.
what exactly is bool() supposed to be? Ive missed a few things the last few years, but this seems odd.

it looks like you are trying to overload an older style cast (bool)(x), almost?

Apr 13, 2017 at 8:16pm
Below is part of checker code for the overloaded bool which I am trying to create. From my understanding there is a bool function which will return true or false. I am just very confused in general.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void testbool(string s)  {
  std::cout << ((s) ? s + " is true" : s + " is false")  << '\n';
}

int main() {
  string s[] = {"2", "0", "-3", "100", "-0"};

  for (int i = 0; i < 5; i++)
    testbool(s[i]);


std::ostream&   operator<<(std::ostream& out , const Integer& one) {
  out << one.num;
  return out;
}


std::istream&   operator>>(std::istream& in , Integer& one) {
  in >> one.num;
  return in;
}

}


This link is the closest thing I could find that was relevant, and is what I am trying to do http://stackoverflow.com/questions/5829487/how-do-i-override-the-bool-operator-in-a-c-class
Topic archived. No new replies allowed.