Function Overloading logic / understanding

Hi All,

I am literally just beginning learning C++, following a beginners 21 day tutorial...

I'm learning about "function overloading" and would just like someone to briefly explain what I seem to be misunderstanding...

The tutorial gave an example:

int myFunction (int, int);
int myFunction (long, long);
int myFunction (long);

saying that The functions must differ in their parameter list, with a different type of parameter, a different number of parameters, or both...

I get the logic here (well I thought I did) till I came to the end of the section with some Q&A questions and one seemed to contradict the example they gave above...

Q. What happens if I have the following two functions?

int Area (int width, int length = 1);
int Area (int size);

The answer was the declarations will compile, but if you invoke Area with one parameter you will receive a compile-time error: ambiguity between Area(int, int) and Area(int).

Could someone please briefly explain why and what is different with the Area functions to the last two myFunction examples they gave above?

Many thanks,

Si
See that = 1 in int Area (int width, int length = 1);. It means that there is a default second argument. It allows the function to be called with only one argument, in which case 1 will be automatically passed as the second argument. Area(2); is equivalent to calling Area(2, 1);.

When you also have this other Area function that only takes one argument the compiler doesn't know which one it should call so it gives you an error.
1
2
3
Area(2); // Should this call Area(int, int) with 2 and 1 passed as arguments?
         // Or should it call Area(int) with 2 passed as argument?
         // The compiler is confused... 
Last edited on
Thanks Peter...

So if I understand this correctly the tutorial example:

int myFunction (long, long);
int myFunction (long);

are both OK because the first doesn't have a default parameter declared...

Thanks for your help :)

Yes.
Topic archived. No new replies allowed.