Consider this program:
#include <iostream>
using namespace std;
void f(unsigned char c) {
cout << c << endl;
}
void f(int c) {
cout << c << endl;
}
int main() {
f('a');
}
This prints out 97
, suggesting that the f()
overload that was selected was the one taking an int
. I find this weird; wouldn't intuitively an unsigned char
be a better match for a char
?
The main advantage of function overloading is that it improves code readability and allows code reusability. The use of function overloading is to save memory space, consistency, and readability. It speeds up the execution of the program.
Restrictions on overloadingAny two functions in a set of overloaded functions must have different argument lists. Overloading functions that have argument lists of the same types, based on return type alone, is an error.
The call is resolved for an overloaded subroutine by an instance of function through a process called Argument Matching also termed as the process of disambiguation.
Function Overloading in C++When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading can be considered as an example of a polymorphism feature in C++.
wouldn't intuitively an
unsigned char
be a better match for achar
?
Well, I guess, but not according to the Standard. According to [conv.prom]p1
:
A prvalue of an integer type other than
bool
,char16_t
,char32_t
, orwchar_t
whose integer conversion rank is less than the rank of int can be converted to a prvalue of typeint
ifint
can represent all the values of the source type; [...]
Now, the three character types have the same rank, and a signed type has a rank always less than int
. This is a combination of [conv.rank]p1.6
and [conv.rank]p1.2
:
The rank of a signed integer type shall be greater than the rank of any signed integer type with a smaller size.
[...]
The rank of
char
shall equal the rank ofsigned char
andunsigned char
.
Basically, every character has always a smaller rank than int
and they can all be represented in an int
, and so the overload with unsigned char
is not a better match, because it would involve a conversion from char
to unsigned char
, instead of a promotion.
If you change your overload to take a char
, then there would be an exact match, and so naturally, the "correct" overload (in your eyes) would be chosen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With