Home » Learn C++ » C++ Functions Overloading

C++ Functions Overloading

C++ Functions Overloading:

Declaring more than one function with the same name hut with different set of arguments and return data types is called functions overloading.

            For example, three functions with same name “sum” and having different parameters are declared as:

 

int sum (int, int);
int sum (int, int, int);
double sum (double, double, double);
 

 

            The first function “sum” has two parameters both of int type and returned data type is also of int type.

            The second function “sum” has three parameters, all of int data type. The return data type is also of int type.

            The third function “sum” has three parameters, all of double type and its return data type is also double.

            When the program that has overloaded functions is compiled, the C++ compiler checks the number of parameters, their order and data type and marks a proper function name for each function. At function call, it executes that function whose return type or parameters matched with the return type or parameters given in the function call.

            The following program example explains the concept of functions overloading.
Program:

 

#include <iostream.h>

#include <conio.h>

main ( )

{

int sum (int, int);

int sum (int, int, int);

double sum (double, double, double);

clrsrc ( );

cout << “Sum of 3 integer values =” << sum (2, 4, 5) << endl;

cout << “Sum of 3 float values =” << sum (2.6, 4.7, 5.6) << endl;

cout << “Sum of 2 integer values =” << sum (2, 4) << endl;

cout << “Ok”;

}

int sum (int x, int y)

{

return x + y;

}

int sum (int x, int y, int z)

{

return x + y + z;

}

double sum (double x, double y, double z)

{

return x + y + z;

}

            In the above program, three functions are defined with the same name “sum”. When the function “sum” is called by passing three integer values as parameters, the control will shift to the 2nd function that has three integer type arguments. Similarly, when the function is called by passing three float data type values, control shifts to the 3rd function that matches the parameters.

 

Other Topics

comment closed

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Copyright © 2010 Information Village. All rights reserved.