C++ Notes
(This question has been asked in GU Uni Dec 2018 for 7 Mark)
In C++, two functions can have the same name if the number and/or type of arguments passed is different.
These functions having the same name but different arguments are known as overloaded functions. For example:
Below program has two different functions namely myFun. The first function takes only one argument and the Second function takes two arguments. Note that both functions has the same name but they have a different number of arguments.
Whenever we are calling function myFun from main function compiler will decide which function to be called based on the number and type of arugment.
If we passed only one argument first function with single argument will be called. If we pass two argument second function will be called. This is clearly visible from the output of the function with cout statement telling us which function is called.
Depending on the number and type of arguments passed, the corresponding myFun()
function is called.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <iostream> using namespace std; int myFun(int x ) { cout<<"Function with one argument called"<<endl; return x; } int myFun(int x, int y) { cout<<"Function with two arguments called"<<endl; return x+y; } int main() { int a=5; int b=3; int c; int d; c=myFun(a); cout<<"c: "<<c<<endl; d=myFun(a,b); cout<<"d: "<<d<<endl; return 0; } |
OUTPUT:
1 2 3 4 | Function with one argument called c: 5 Function with two arguments called d: 8 |
Comments
Post a Comment