0
void essai (int, double); // essai I
void essai (double, int); // essai II

int n, p; double z; char c;

essai(n,z); // calling essai I
essai(c,z); // calling essai I, after the conversion of c in int
essai(n,p); // compilation error

Why essai(n,p) produce a compilation error here? Is it because the conversion can not be done from int to double?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523

3 Answers3

3

The compiler looks at the two overloads of essai for each of your three cases, and decides which overload to take, and what conversions to perform to make the call:

  1. In case of essai(n,z) overload #1 wins, because it can be called with no conversion, vs. two conversions for overload #2
  2. In case of essai(c,z), overload #1 wins, because it can be called with a single conversion of char to int, vs. two conversions for overload #2
  3. In case of essai(n,p), both overloads require an equal number of conversions (two). Since there is no clear winner, the compiler considers the call ambiguous, and issues an error.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Personnal question : if the two function `void fexample (int)` and `void fexample (const int)` was defined, is there a compiler error? –  Oct 12 '15 at 14:53
  • @J.G [You cannot overload a function based on the `const` of the variable](http://stackoverflow.com/questions/3682049/functions-with-const-arguments-and-overloading) – NathanOliver Oct 12 '15 at 14:57
  • 1
    @J.G You would get a compile error on an attempt to override `int` vs `const int`. It would compile if you change `int` to `int&` and `const int` to `const int&` ([demo](http://ideone.com/eHzmke)). – Sergey Kalinichenko Oct 12 '15 at 14:58
  • 1
    @J.G `const` does not make a difference to the caller when passing by value, because copy semantic is used. You can call `foo(int)` and pass it `const int b = 5` because `b` would get copied anyway. Hence `foo(int)` vs. `foo(const int)` overload would be ambiguous. The situation with `int&` vs. `const int&` is different, because one cannot pass a `const` to a non-const parameter by reference. That's why the overload `foo(int&)` vs. `foo(const int&)` is unambiguous. – Sergey Kalinichenko Oct 12 '15 at 15:05
1

Both

void essai (int, double);
void essai (double, int);

are valid overloads when you call essai(n,p); as one of the ints needs to be converted so it could convert either one. Since you have two equal overloads the compiler gives up and should issue an ambiguity compiler error.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
0

The compiler doesn't know which data of int to convert to double.

You should convert it explicitly to call essai I:
essai(n,(double)p);

or to call essai II:
essai((double)n,p);

MikeCAT
  • 73,922
  • 11
  • 45
  • 70