Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function overloading by swapping order of parameters

About function overriding in C++, the following is legal, as both prototypes have different numbers of parameters:

void func(int par1, double par2);
void func(int par1, double par2, double par3);

as is (because there is at least 1 parameter of a different type):

void func(int par1, double par2);
void func(double par1, double par2);

I wondered, just for curiousity, Is can you overload with the same number of parameters, of the same types, but in a different order? For example is the following legal:

void func(int par1, double par2);
void func(double par1, int par2);

If so, is there any formal document specify it?

like image 227
zangw Avatar asked Sep 15 '14 03:09

zangw


1 Answers

The formal document is the ISO C++ standard and, yes, you can do it.

The entirety of ISO C++11 Chapter 13 is devoted to overloading but the first few paragraphs sum it up nicely:

When two or more different declarations are specified for a single name in the same scope, that name is said to be overloaded. By extension, two declarations in the same scope that declare the same name but with different types are called overloaded declarations. Only function and function template declarations can be overloaded; variable and type declarations cannot be overloaded.

When an overloaded function name is used in a call, which overloaded function declaration is being referenced is determined by comparing the types of the arguments at the point of use with the types of the parameters in the overloaded declarations that are visible at the point of use.

Overloading is possible provided the parameter list is different, including order. It's different in all three cases you present in your question:

{int, double} vs {int, double, double}
{int, double} vs {double, double}
{int, double} vs {double, int}

Note that overloading is not possible for the two functions:

void func(int par1, int par2);
void func(int par2, int par1);

since it's really only the types that provide uniqueness, not the parameter names. Both of those functions are called func and they both have the parameter list {int, int}, so they're not unique.

like image 63
paxdiablo Avatar answered Sep 24 '22 02:09

paxdiablo