Reputation: 2673
In the test program below, calling the checkit
method with a bool predicate instead calls the integer overload. Why?
(i == 10)
should create a boolean value, which should then trigger the bool overload to be called, no?
Program Output
should be int
I'm a bool 1
should be bool
I'm a bool 1
should also be bool
I'm a int 1
Source
class Overload
{
public:
void checkIt(bool n) { printf(" I'm a bool %d\n", n); }
void checkit(long n) { printf(" I'm a long %ld\n", n); }
void checkit(int n ) { printf(" I'm a int %d\n", n); }
};
int main(int argc, char *argv[])
{
Overload obj;
int i = 10;
bool b = true;
printf("should be int\n");
obj.checkIt(i);
printf("should be bool\n");
obj.checkIt(b);
printf("should also be bool\n");
obj.checkit( (i == 10) );
}
EDIT
Duh! sorry for the typo.
However, after fixing typo and commenting out the bool method, the int method is called with the bool predicate. Is there a default conversion from bool to int if a more appropriate signature is not found? Strictly speaking, there is no bool
signature so I was expecting either a compile or runtime error...
Updated Code
class Overload
{
public:
//void checkIt(bool n) { printf(" I'm a bool %d\n", n); }
void checkIt(long n) { printf(" I'm a long %ld\n", n); }
void checkIt(int n ) { printf(" I'm a int %d\n", n); }
};
int main(int argc, char *argv[])
{
Overload obj;
int i = 10;
bool b = true;
printf("should be int\n");
obj.checkIt(i);
printf("should be bool\n");
obj.checkIt(b);
printf("should also be bool\n");
obj.checkIt( (i == 10) );
}
Updated Output
should be int
I'm a int 10
should be bool
I'm a int 1
should also be bool
I'm a int 1
Upvotes: 1
Views: 665
Reputation: 174
Yes C++ uses implicit conversion.bool,char is automatically converted into int /short/long or vice versa.
Upvotes: 0
Reputation: 318
Remember that function names (and almost everything else) in C++ are CaSe SeNsItIvE.
In your updated code, there are 2 checkIt
methods, one for int
type and one for long
type. You called checkIt
3 times, and the 2 last times you passed to the method a bool
value. In C++ bool
value automatically casts to int
with true == 1
and false == 0
bool a = 1 // equals to true
bool b = 0 // equals to false
As there are no methods accepting 'bool' type, the value automatically casts to int
and calls the int
method.
Upvotes: 0
Reputation: 85757
checkIt
isn't overloaded; there's only a bool
version.
checkit
is overloaded; there's a long
and an int
version.
Your code calls checkIt
twice and checkit
once.
Upvotes: 3