Function overloading in C++ with Examples


In programming languages, Function overloading is a process of declaring multiple member functions having same name but differ in one of the following

  1. Different types of parameters.
  2. Different number of parameters.
  3. Different sequence of parameters.

For Example:-

  • Sum(int, int)
  • Sum(Float, Float)
  • Sum(int, float)
  • Sum(int, float, int)

This process have many advantages. The mechanism of function overloading allows programmer to implement the behavior of static polymorphism in his software. It allow users to invoke different functionality by interacting with same interface.

/* */

For Example:-

class Function_Example
int a;
double b;
a = 0;
b = 0.0;
void Sum(int a1, int a2)
a = a1 + a2;
std::cout << "Two integer values are added : "<<a<<"\n";
void Sum(float a1, float a2)
b = a1 + a2;
std::cout << "Two Float values are added : " << b << "\n";
void Sum(int a1, float a2)
b = a1 + a2;
std::cout << "One integer and one Float value are added : " << b << "\n";
void Sum(int a1, float a2, int a3)
b = a1 + a2 + a3;
std::cout << "One integer, one Float and one integer value are added : " << b << "\n"<<"\n";
Function_Example obj;
obj.Sum(3, 5);
obj.Sum((float) 4.55, (float) 6.55);
obj.Sum(2, (float) 7.5);
obj.Sum(1, (float) 8.5, 9);

Function Overloading exampleExplanation:-

In above example, we have declared a class Function_Example, it contains two data members ‘a’ and ‘b’. It also contains Four overloaded member functions, each function is differ by the type of parameters, number of parameters and by the sequence of parameters. Now we will move towards the “Main function”. There we have created an object “obj” of “Function_Example” class. Now we are calling “Sum” function four times by passing different types of values by different sequences. As you can see into the output image, every time when the function “Sum” is called the different output is generated because of different overloaded functions.

Function overloading in C++ with Examples
5 (100%) 1 vote

(royal52) is a software engineer. He is good at authoritative link building, Content Writing, SEO, Web Development, Wordpress, HTML, CSS, JAVASCRIPT, Game Development, Unity3d, Graphic Designing, Logo Designing, Android Development and Ios Development. Last but not least, he is passionate about development and gaming.

We will be happy to hear your thoughts

Leave a Reply

Grab our Partner's Top Rated web hosting deal - Upto 90% off