c++ - Signature of a function -


i beginner level programmer , have started learning programming in c++,

i had @ feature called "function overloading" , while have understood purpose , implementation @ code level, haven't understood how implemented @ compiler level how compiler differentiates between signature of different functions same name , would

return-type func-name (data-type 1 , data-type-2); 

would have same signature as

return-type func-name (data-type 2 , data-type-1); 

and same thing applies overloaded constructors ?

the compiler uses technique known name mangling.

briefly, compiler encodes number , type of arguments actual name written object file. there few examples in wikipedia article on subject, including examples c++.

as specific example, i've used g++ on mac compile following c++ file:

test.cpp

int f(int x) {} int f(double x, char y) {} 

with

g++ -s test.cpp 

this results in assembly language file (elided somewhat):

test.s

.globl __z1fi __z1fi: pushq %rbp movq %rsp, %rbp movl %edi, -4(%rbp) leave ret .globl __z1fdc __z1fdc: pushq %rbp movq %rsp, %rbp movsd %xmm0, -8(%rbp) movb %dil, -12(%rbp) leave ret 

the important part here functions called __z1fi , __z1fdc in assembly language output, linker see. can infer f name of function, , arguments, have i (int) , dc (double , char). note order of arguments encoded too!

now consider happen if had

int f(int x) {} int f(int y) {} 

this of course not acceptable situation far language concerned, since call f(10) not resolved. theoretically language specify second declaration replaces first, c++ not this. illegal overloading.

it turns out name mangling shows why should error. compiler try make 2 distinct functions name __z1fi (the actual name not defined language compiler dependent). can't have 2 identically named functions in program @ level.


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -