More name decoration
In Chapter 4, the concept of
name decoration
was introduced. In the
code
void f();
class X { void f(); };
the function f( ) inside the
scope of class X does not clash with the global version of
f( ). The compiler performs this scoping by manufacturing different
internal names for the global version of f( ) and
X::f( ). In Chapter 4, it was suggested that the names are simply
the class name “decorated” together with the function name, so the
internal names the compiler uses might be _f and _X_f. However, it
turns out that function name decoration involves more than the class
name.
Here’s why. Suppose you want to
overload two function names
void print(char);
void print(float);
It doesn’t matter whether they are
both inside a class or at the global scope. The compiler can’t generate
unique internal identifiers if it uses only the scope of the function names.
You’d end up with _print in both cases. The idea of an overloaded
function is that you use the same function name, but different argument lists.
Thus, for overloading to work the compiler must decorate the function name with
the names of the argument types. The functions above,
defined at global scope, produce internal names that might look something like
_print_char and _print_float. It’s worth noting there is no
standard for the way names must be decorated by the
compiler, so you will see very different results from one compiler to another.
(You can see what it looks like by telling the compiler to generate
assembly-language output.) This, of course, causes problems if you want to buy
compiled libraries for a particular compiler and linker – but even if
name decoration were standardized, there would be other roadblocks because of
the way different compilers generate
code.
That’s really all there is to
function overloading: you can use the same function name for different functions
as long as the argument lists are different. The compiler decorates the name,
the scope, and the argument lists to produce internal names for it and the
linker to
use.