Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link
Posts

8.5 Function overloading

1 min read
Image result for Function overloading c++
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.

                      8.6 Operator Overloading          NEXT >>

You may like these posts

  • Pointer is a variable that stores the address of another variable. They can make some things much easier, help improve your program's efficiency, and even allow you to handle u…
  • refers to where variables is declared. It can be Inside a function or a block which is called local variables, In the definition of function parameters which is called f…
  • auto The default class. Automatic variables are local to their block. Their storage space is reclaimed on exit from the block. register If possible, the variable will be…
  • Array is a fixed size collection of similar data type items. Arrays are used to store and access group of data of same data type. Arrays can of any data type. Arrays must…
  • In Array we can store data of one type only, but structure is a variable that gives facility of storing data of different data type in one variable. Structures are variab…
  •   An operator is a symbol. Compiler identifies Operator and performs specific mathematical or logical operation. C provides following operators : # Arithmetic Operators # L…

Post a Comment