8.5 Function overloading - shahzade baujiti

Breaking

Wednesday, April 24, 2019

8.5 Function overloading


8.5 Function overloading

You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You can not overload function declarations that differ only by return type.

// overloading functions
#include <iostream.h>
using namespace std;

int add (int a, int b)
{
return (a+b);
}

double add (double a, double b)
{
return (a+b);
}

int main ()
{
int x=5,y=2;
double n=5.0,m=2.5;

cout << add(x,y) << '\n';
cout << add(n,m) << '\n';
return 0;
}

o/p:
7
7.5

In this example, there are two functions called add, but one of them has two parameters of type int, while the other has them of type double. The compiler knows which one to call in each case by examining the types passed as arguments when the function is called. If it is called with two int arguments, it calls to the function that has two int parameters, and if it is called with two doubles, it calls the one with two doubles.

Note that a function cannot be overloaded only by its return type. At least one of its parameters must have a different type.

No comments:

Post a Comment