i am a beginner level programmer and have just started learning programming in C++,
i had a look at a feature called “FUNCTION OVERLOADING” and while i have understood the purpose and implementation at the code level, i haven’t understood how it is implemented at the compiler level that is how does a compiler differentiates between the signature of the different functions with same name and would
return-type func-name (data-type 1 , data-type-2);
would have the same signature as
return-type func-name (data-type 2 , data-type-1);
and does the same thing applies to overloaded constructors too ?
The compiler uses a technique known as name mangling.
Briefly, the compiler encodes the number and type of the arguments into the actual name written into the object file. There are a few examples in the Wikipedia article on the subject, including examples from C++.
As a specific example, I’ve used g++ on a Mac to compile the following C++ file:
test.cpp
with
This results in the assembly language file (elided somewhat):
test.s
The important part here is that the functions are called
__Z1fiand__Z1fdcin the assembly language output, which the linker will see. You can probably infer thatfis the name of the function, and for arguments, we havei(int) anddc(double and char). Note that order of arguments is encoded too!Now consider what would happen if you had
This is of course not an acceptable situation as far as the language is concerned, since a call like
f(10)could not be resolved. Theoretically a language could specify that the second declaration replaces the first, but C++ does not do this. This is simply an illegal overloading.It turns out that name mangling actually shows why this should be an error. The compiler would try to make two distinct functions with the name
__Z1fi(the actual name is not defined by the language but is compiler dependent). We can’t have two identically named functions in a program at this level.