RUNTIME ERROR IN FUNCTION OVERLOADING

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.

given me the reason ??
thanks


#include<iostream>
using namespace std;
void function(int a,int s)
{
cout<<"F1: "<<a<<s;
};
void function(float a,int s)
{
cout<<"F2: "<<a<<s;
};
void main()
{
function(15,4);
function(20.2,4);

}
Last edited on
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>
using namespace 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);
}

can you explain 20.2f and what is difference b/w float and double????
I think the only difference b/w float and double is their range.....
#include<iostream>
using namespace std;

void function(float a,int s)
{
cout<<"F2: "<< a << s << '\n';
}
int main()
{
function(20.2, 4);
}

and in this case 20.2 is float or double
how it is working???
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)
thank you very much
Topic archived. No new replies allowed.