+ 7
Consider the following program.would it compile and run without any error?if yeswhat will be the output?if no what is the error?
#include <iostream> using namespace std; class Test { public: void f(int n,double m); void f(int n,int m); }; void Test::f(int n,double m) { cout<<"addition of int and double value resulted in:"<<(double)(n+m)<<endl; } void Test::f(int n,int m) { int r=n+m; cout<< "addition of 2 ints resulted in:"<<r<<endl; } int main() { Test t1; t1.f(98,99); t1.f(5.3,4); t1.f(4.3,5.2); return 0; }
3 Respuestas
+ 4
There shouldn't be any problem in compiling the code above, as the functions are simply overloads of each other.
The only problem occurs in case 2, in which there is an implicit conversion of the passed double to int due to the missing overloaded version.
Also, you will not be able be able to get the correct output in cases like :
t1.f(2,3.0); // Its more likely the 1st overload that gets executed.
+ 8
As stated by Kinshuk Vasisht, it would compile. However, your compiler should be able to warn you about coercion (narrowing conversion) from double to int upon passing double to the first parameter of the second overload of the function.
+ 5
thanks kinshuk Vashisht and Hatsy Rei