Function polymorphism/overloading based on parameter count
Writing polymorphic function based on difference on number of parameters.
Learning Objectives
- Understanding function overloading or polymorphism based on parameter count with a simple example.
Source Code
|
|
Related ( ? ) : |
Run Output
Code Understanding
void repeat(char,int);
void repeat(char);
These are two prototypes, where the function names are same but number of parameters in the input are different. Polymorphism/overloading occurs when name of function is same within the same program project.
char c=’@’; int rc=10; //These are related variable which will be used for passing to function
repeat(c);
Here is the function call with just one parameter, so the polymorphic version of function with one parameter will be called.
repeat(c,rc);
This is a function call with two parameters so the equivalent function with two parameters be called. In the inside of function polymorphic functions may be doing anything which may be quite different from other function of same name.
void repeat(char a){for(int i=0;i<20;++i) cout<<a;}
This variation of function definition is printing the given character in c for a fixed number (20) of times.
void repeat(char a,int rc){for(int i=0;i<rc;++i) cout<<a;}
This variety is printing the character in c for no. of times as specified specifically in variable rc.
Notes
- Polymorphism may be based on parameter data type also, even when the number of parameters are same.
- Both number of parameter variables and type of data may be different at the same time.
Common Errors
- Some time student try to write polymorphic functions with same count and same data type with different return types. This does not work in c++. For example –
int repeat(char);
void repeat(char);
Above two declarations will give error as only return data type is different. This makes calling a function ambiguous.
Suggested Filename(s): fn-poly-param.cpp
Created: 5-Jan-2018 22:20 | Updated: 15-Sep-2018 14:09|
