Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How priority is given to datatype in overloading functions?

Tags:

c++

I am having 3 functions overloaded. How priority is given to datatype in overloading functions?

#include <iostream>

using namespace std;

void myfunc (int i) {
    cout << "int" << endl;
}

void myfunc (double i) {
    cout << "double" << endl;
}

void myfunc (float i) {
    cout << "float" << endl;
}

int main () {
    myfunc(1);
    float x = 1.0;
    myfunc(x);
    myfunc(1.0);
    myfunc(15.0);
    return 0;
}

Output:

int
float
double
double

How program is deciding to call float or double?

like image 682
Vishwadeep Singh Avatar asked Dec 12 '25 13:12

Vishwadeep Singh


1 Answers

Literals have well-defined types. In particular, floating-point literals have type double unless suffixed. A suffix of f or F makes it a literal of type float while a suffix of l or L makes it a literal of type long double.

This explains the overload resolution observed:

myfunc(x);//calls myfunc(float) since x is a float
myfunc(1.0);//calls myfunc(double) since 1.0 is a double
myfunc(15.0);//calls myfunc(double) since 15.0 is a double

Similar reasoning holds for integer literals as well - 1 is a literal of type int.

like image 117
Pradhan Avatar answered Dec 14 '25 09:12

Pradhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!