+ 1

i have overloaded two Funtions one with int parameter and the 2nd with A float one..and..:

#include <iostream> using namespace std; void print(int a){ cout<<a; } void print(float b){ cout<<b; } int main() { print(1.6); return 0; } could someone tell me why the 1.6 is not printed? isnt it a float number?

5th Apr 2018, 7:50 AM
RiGeL
RiGeL - avatar
7 Réponses
+ 4
If you write it like this you will get warning. Compilator doesn't know if you want to parse it to int or to float. You need do declare a variable float f=2.6 and then print it. Or make it like this: print((float)1.6);
5th Apr 2018, 7:55 AM
Bartosz Pieszko
Bartosz Pieszko - avatar
+ 5
This is because by default 1.6 is considered a double (not float) and it becomes ambiguous which version to call It can be resolved by using any of the following ways : 1. Change float to double in function prototype void print(double b) 2. Pass 1.6 by type casting as float print((float) 1.6); Or explicitly defining 1.6 as float print(1.6f); 3. Declaring as float and passing float a = 1.6; print (a);
5th Apr 2018, 8:00 AM
Bishal Sarang
Bishal Sarang - avatar
+ 1
I think a float number can be explicitly defined using 1.6f This tells it that 1.6 is a float so print(1.6f) should work
5th Apr 2018, 8:05 AM
Bebida Roja
Bebida Roja - avatar
+ 1
Bishal On the second example you gave, 1.6f does NOT cast 1.6 from double to float. It defines it to be a float, so it is faster than a cast.
5th Apr 2018, 9:40 AM
Bebida Roja
Bebida Roja - avatar
+ 1
Thanks for pointing out Bebida Roja :) . *Corrected
5th Apr 2018, 10:30 AM
Bishal Sarang
Bishal Sarang - avatar
0
Bartosz Pieszko Thank you alot now its all clear👍
5th Apr 2018, 8:05 AM
RiGeL
RiGeL - avatar
0
Bishal Sarang thank you
5th Apr 2018, 8:05 AM
RiGeL
RiGeL - avatar