Vishwadeep Singh
Vishwadeep Singh

Reputation: 1043

How priority is given to datatype in overloading functions?

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?

Upvotes: 3

Views: 1055

Answers (1)

Pradhan
Pradhan

Reputation: 16737

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.

Upvotes: 7

Related Questions