C++ Programming Tutorials - Functions
C++ FUNCTION OVERLOADING
Overloading refers to the use of same thing for different purpose. C++ also permits overloading of functions. This means that we can use the same function name to crate functions that perform a variety of different tasks. This is known as function polymorphism in OOP
Using the concept of function overloading; we can design a family of functions with one function name but with different arguments lists. The function would perform different operations depending on the argument list in the function call.
For examples, an overloaded add() function handles different types of data as shown below:
// declarations int add (int a, int b); // prototype 1 int add (int a, int b, int c) // prototype 2 double add (int p, double q) // prototype 3 //function calls cout << add(5, 10) // uses prototype 1 cout << add(15, 10.0) // uses prototype 3
A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution.
|
// function volume() is overloaded three times #include using namespace std; // declarations (prototypes) int volume(int); double volume (double, int); long volume (long, int, int); int main() { cout << volume(10) << “\n”; cout << volume(2.5, 8) << “\n”; cout << volume(100L, 75, 15) << “\n”; return 0; } // function definitions int volume(int s) // cube { return(s*s*s); } double volune(double r, int h) // cylinder { return(3.14519*r*r*h); } Long vlume(long l, int b, int h) // rectangular box { return(l*b*h); } |
Output 1000 157.26 112500 |
![]() |
