This is Sri again. Looking at the title,you people may be thinking whether this a crime story 🙂 but the killer in title is Mortein Mosquito and Cockraoch killer. Many of us would have seen this ad “Black Hit for Mosquito and Red Hit for Cockroach”.
How many of you used red for cockroach and wondered y the cockroach is still alive 🙂 I am one among them.In those scenarios I always think like why the hell do they have separate bottles 😦
Now coming to our topic polymorphism this would be the case for the users of your code if no polymorphism exists.
Somebody asked you to write a math library which includes function like addition,subtraction etc..They will use the library for their calculator program.
The day comes,you delivered the code and along with given 100 pages document saying ,Call addFloat for adding float numbers,addInt for adding integers etc……….Hey boss for just adding two numbers how many pages do I have to refer to find the correct function name. Because to add float you have written function with name addFloat,for integers addInt….
int addInt(int num1,num2);
float addFloat(float num1,float num2);
This is really cumbersome and irritating when team and project is big.Even for small projects this is very difficult for development and maintenance.
To overcome this issue ,compile time polymorphism came into picture..Don’t name the functions differently.If it is addition just name the function as add again .Function for adding integers and float will have same names .But for the compiler to identify its not a redefinition ,we have to given some identification marks like
1.Make the datatype of the function parameters different or
2.Make difference in number of parameters.
int add(int num1,num2);
float add(float num1,float num2);
So that complier can identify this is a polymorph of add function.But you may be asking how a compiler is doing this magic.
The secret sauce is Name Mangling,even though we name both the functions as add for adding float and adding integers
compiler will internally change the name of the function so that it will become 2 different functions for compiler.
int _Zpiadd(int num1,int num2);
float _KLpiadd(float num1,float num2);
These are just samples ………
So whenever we call add ,compiler will look for the type of parameters and call the respective the name mangled add function .
We can see Run Time Polymorphism in our next post ……
I heard that putting like is good for health 🙂 So just hit the like button. And for more technical videos visit our site http://www.guvi.in
I have 10 +yrs of experience in software industry. Very passionate and love to teach others.
Had good experience in languages like C,C++,VC++,Java,PHP…..
Now a full time entrepreneur and taking care of GUVI