Same function name but different purpose
Function overloading when function name is same but the objective of function is entirely different.
Learning Objectives
- Understanding overloading with unrelated purpose of functions.
Source Code
|
Run Output
Code Understanding
void action(char c) { for(int i=0;i<5;i++) cout<<c;}
Purpose of this function is to print given input character five times. It doesn’t return any thing.
int action(int n) {return n*n;}
Purpose of this function is entirely different. It returns the square of given integer.
int main() {
action(‘*’);
Call to function with input as a character. Since it doesn’t return any value so there is nothing on the left hand side of expression. The function call in itself is an expression.
cout<<action(4)<<endl;
Call to function with input as an integer. Since this returns an integer, so the returned integer can be directly fed to the console stream, hence it is a part of cout chain of action.
return 0;
}
Notes
- Usually naming a function with same name is done when they have similar purposes. For. eg. in the above example the functions can be named as printfivetimes() and square() respectively for better understanding. The above code has been shown as an example that overloading doesn’t restrict you from naming functions with same name even when purpose is different. This is also a requirement when large teams of programmers is working on a project and you do not want to restrict programmers with very strict naming constraints.
Suggested Filename(s): func-ol3.cpp
sunmitra| Created: 26-Aug-2018 | Updated: 28-Aug-2018|