Friday, July 7, 2017

What is function overloading and how it works

Function overloading is one of the powerful feature of OOPS programming and it is very essential to know how it works and why it is even there at first place.

Function overloading, what does  definition says: "Its a way by which one can define two function with exact same name in a common scope or namespace. However the function will differ in argument type, No. of arguments passed"

But why do we need function overloading: Because you don't want to confuse the programmers/users who are using your program for some particular functionality or feature. Putting too many function name for calling a single feature in different circumstance will make someone go crazy.
Lets take a easy example where a retailer shop keeper want to use software for doing all type of bill purchase. He sells many diffrent things on his shop  but uses a single software application for billing purpose. All he requuires is a single "Calculate Bill" button for all type of purchase done by customer irrespective of type of goods, quantity, discount of the goods. One button should be able to do all the billing function for the users. But as a programmer of the software you need to use function overloading to achieve this 

Does C language supports Overloading :

Well the answer is No, But one may question how does printf() and scanf() or similar function work in C, because they seems to be doing exact same work ie taking different No./Types of arguments  and printing it on the screen!
Actually these C inbuilt function uses a Variable Argument List feature of C language which allows it to so. But is very different from Overloading function and its capability. 

How does overloading works internally:

Little depth of method overloading :
Lets see how compiler deals with these function, as if you know while compiling all function gets their own unique symbol in object code.
C++ Compiler: The compiler will generated different symbol(mangled) code for the these function, if you load the symbol chart of a object file with overloaded function you would see something like below:
For a overloaded function with name bechmark below symbol will be generated (2nd and 3rd line). You can see both have unique identification code.
symbol table

C compiler:
As mentioned earlier overloading does not exist in the C language, so if you try to declare two menthol with exact same name, the symbol code generated will have same identification for them, hence the linker would fail to link the function calls.

Please keep reading this site article for more details on this.

No comments:

Post a Comment