C++ Function Overloading - Devbhoomi

FREE JOB ALERT & ONLINE TUTORIALS

Hot

Post Top Ad

Saturday 7 October 2017

C++ Function Overloading

C++ Function Overloading


If a C++ class have multiple member functions, having same name but different parameters (with change in type, sequence or number), and programmers can use them to perform similar form of operations, then it is known as function overloading. In this case, two functions can have same identifier (name) and if either number of arguments or type of arguments passed to functions are different; then overloading is possible within a C++ program. In other words, it is the ability of creating multiple functions with same name and slightly different implementation and depending on the context (type, sequence and number of value passed), the appropriate function gets invoked.
In case of C++ programs, if the functions are like this:
Example:
int overloaded() { }
int overloaded (int g){ }
int overloaded (float g){ }
int overloaded (int g, double s){ }
int overloaded (float s, int g, double k){ }
Here the function name overloaded is used as overloading functions with the change in argument type and number.

Function Overloading

Example:
#include <iostream>
using namespace std;

long add(long, long);
float add(float, float);
int main()
{
 long a, b, c;
 float e, f, g;
 cout << "Enter two integers\n";
 cin >> a >> b;
 c = add(a, b);
 cout << "Sum of integers: " << c << endl;
 cout << "Enter two floating point numbers\n";
 cin >> e >> f;
 g = add(e, f);
 cout << "Sum of floats: " << g << endl;
}

long add(long c, long g)
{
 long sum;
 sum = c + g;
 return sum;
}

float add(float c, float g)
{
 float sum;
 sum = c + g;
 return sum;
}
Rules for Overloading Operators:
  • Only existing operators can be overloaded
  • Programmers cannot change the basic meaning of an operator
  • Overloaded operators will always follow the syntax rules of the original operators
  • Programmers cannot use friendfunction to overload certain operators



No comments:

Post a Comment

Post Top Ad