Question

I need some help understanding how overloaded C++ functions are selected by the compiler.

When given a function:

type func(type1 x, type2 y);
type func(type3 x, type2 y);

How does the compiler determine which function to choose?

I know the function chosen is according to its suitability, but how to you know which function is chosen if either could be used successfully.

For example:

Given these function overloaded functions:

char* average(int i, float f, double d);
double average(double d, float f, int i);
double fabs(double d);

Given these variables:

int i1, i2, i3;
float f1, f2, f3;

What data type is the return value of these function calls? and why?

average(i1, i2, i3);
average(f1, f2, f3);
fabs(average(f1,f2,f3));
Was it helpful?

Solution 2

In order to compile a function call, the compiler must first perform name lookup, which, for functions, may involve argument-dependent lookup(ADL). If these steps produce more than one candidate function, then overload resolution is performed to select the function that will actually be called. In general, the candidate function whose parameters match the arguments most closely is the one that is called.

As in your case:

1--> char* average(int i, float f, double d);

2--> double average(double d, float f, int i);

Here in both of your functions you have completly different argument list. 1st average is taking int, float, double and the 2nd one is double, float, int.

So, compiler decides which method to invoke first based in its arguments. If you invoke method with argument (int, float, double) the overloaded version takes 1st method and if you invoke method with argument (double, float, int) the overloaded version takes 2nd method.

The choice if which overloaded method to call(in other words, the signature of the method) is decided at compile time. So, compiler will already know the signature of the method to be invoked.

While overloading methods we must keep the following rules in mind:

  • Overloaded methods MUST change the argument list,
  • Overloaded methods CAN change the return types.
  • Overloaded methods CAN change the access modifier.
  • A method can be overloaded in the same class or in a subclass.

OTHER TIPS

The return value depends on the function call that is made. For example your first function call would return value double because second average function is called.

The function overloading solely takes place on basis of arguments irrespective of return types. You can't overload two functions solely on basis that they have different return types. The functions should differ by arguments in order for function overloading to work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top