The below given code has a runtime error.
1: To overload the function i change the data-type of parameter a in second function.But it is not working
2: If i change data-type of float a to char a[], and make it a string then program starts working.
It does not give a runtime error, it gives a compile-time error, at least two of them on conforming compilers:
test.cc:11:1: error: 'main' must return 'int'
void main()
^
test.cc:14:1: error: call to 'function' is ambiguous
function(20.2,4);
^~~~~~~~
test.cc:3:6: note: candidate function
void function(int a,int s)
^
test.cc:7:6: note: candidate function
void function(float a,int s)
^
The last one happens because the type of 20.2 is double, and the type of 4 is int, so you're attempting to call function(double, int), which doesn't exist. The compiler sees two other functions named 'function': it can call the first one after converting 20.2 from double to int, and it can call the second one after converting 20.2 from double to float. Since it can't decide, it is asking you.
To fix, use 20.2f, as in:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include<iostream>
usingnamespace std;
void function(int a,int s)
{
cout<<"F1: " << a << s << '\n';
}
void function(float a,int s)
{
cout<<"F2: "<< a << s << '\n';
}
int main()
{
function(15, 4);
function(20.2f, 4);
}
20.2f is just how one writes "the float value closest to 20.2" in C++ (and in C).
You could also write static_cast<float>(20.2) or float(20.2) or (float)20.2, although that says "take the double value closest to 20.2 and convert it to float".
As for the difference, float and double are two different types, and overload resolution is decided by the types of the arguments: function(float) and function(double) are as different as function(int) and function(string)