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

  •   Constructor A constructor is a special kind of class member function that is executed when an object of that class is instantiated. Constructors are typically used to init…
  • A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for f…
  • Object Oriented Programming has a special feature called data abstraction. Data abstraction allows ignoring the details of how a data type is represented. While defining a clas…
  • Polymorphism "Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or reference) to assume (be replaced by) or become many different forms of…
  • Inheritance is one of the key feature of object-oriented programming including C++ which allows user to create a new class(derived class) from a existing class(base class). The…
  • 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 argu…

Post a Comment