Waleed Naveed
Waleed Naveed

Reputation: 2381

How function overloading works with double and float

I have two overloaded methods

double Sum(double n1, double n2)
{
     return n1 + n2;
}

float Sum(float n1, float n2)
{
     return n1 + n2;
}

When I call Sum(5.5, 5.5), the method with double return type gets called.

My question is why the method with double return type is called, and why not the method with float return type? How is the compiler deciding which method should be called?

Upvotes: 1

Views: 2594

Answers (1)

Ozan Yurtsever
Ozan Yurtsever

Reputation: 1304

Because, floating-point literals such as 5.5 have the type double in C++ as default. That's why, when you pass a double literal to an overloaded function, it is going to call the version of that function which accepts the double typed parameters.

If you want to override this default behaviour, you need to be using suffix notations such as f to let the compiler know which type does literal have. As an example, you need to be passing Sum(5.5f, 5.5f) instead of Sum(5.5, 5.5) to avoid default behaviour.

Upvotes: 7

Related Questions