+ 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; }

31st May 2018, 4:50 AM
Nicky
Nicky - avatar
3 Réponses
+ 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.
31st May 2018, 5:33 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 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.
31st May 2018, 5:41 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
thanks kinshuk Vashisht and Hatsy Rei
31st May 2018, 8:15 AM
Nicky
Nicky - avatar