#include<iostream>
using namespace std; int PupilAge( int MinmAge=7) //PupilAge() is declare with a default value 7 { int PupAge= MinmAge; return PupAge; } //end myAge() int main() //start main() { int MaxYears=9; //Main calls PupilAge() with a default in case of the minimum age and then passes a value to when calling for a maximum age. cout<< "The minimum and maximum entry level age for a primary pupil is " << PupilAge()<< " and "<< PupilAge (MaxYears)<< " years respectively" <<endl; return 0; } //main() | The minimum and maximum entry level age for a primary pupil is 7 and 9 years respectively |
Function Overloading
Function overloading allows for the same name to be defined but with different signatures. Function overloading provides for declaration using same name of functions that perform similar tasks but on different data types. The compiler is able to select the appropriate function by examining the types, number and arguments used in the call. For example a function that calculates for the area of a rectangle can do it when measurements are given either as int or double. So, instead of redefining the function we can change the data types and still use the same functions. Follow the example belowint RecArea(int w,int h) { return w*h; } // only the signature changes types double RecArea(double w,double h) { return w*h; } int main() { int width=5, height=6; double wid=12.5, heit=6.2; cout<<" When using int, the function RecArea() returns " <<recArea(width,height)<<" and " << recArea(wid,heit) <<" when double is used in the function call."; return 0; } |
When using int, the function RecArea() returns 30 and 77.5 when double is used in the function call. |
PREV:Introduction to passing by value and by reference |
|
| NEXT: Introduction to function templates and recursion |
can we pass default argument in overloaded function?
ReplyDeleteif we can passed so HOW?
if not then why not?