Quick links: HR Interview Que. Code Snippets C Programs C++ Programs Java Programs Scala Solved Examples PHP Examples

Home » C++ programming language

C++ function overloading

In C++, it is possible to make more than one function with same name, this concept is known as function overloading. We can use same function name for different purpose with different number and types of arguments.

In function overloading function names will be same but Types of arguments, Order of arguments, Number of arguments must be different.

The C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.

Following advantages to use function overloading in your program:

Sponsored Links

  • Eliminating the use of different function names for the same operations.
  • Helps to understand, debug and group easily.
  • Easy maintainability of the code.
  • Better understandability of the relationship b/w the program and the outside world.

Points to remember

Function overloading does not depend on return type of function.

Consider the following functions :

int sumOfNumbers(int,int);
float sumOfNumbers(float,float);

This type of function overloading will produce an error "ambiguous call to overloaded function" , If you will call function like ( sumOfNumbers(10,20); and sumOfNumber(10.2,20.3); )

To remeove this problem, use 10.2f (as float value)and 20.3f as function argemnts.

Consider the example

#include <iostream>
using namespace std;

// function declarations
int		sumOfNumbers(int,int);		// type-1
int		sumOfNumbers(int,int,int);	// type-2
int		sumOfNumbers(int,float);	// type-3
float	sumOfNumbers(float,float);	// type-4

int main()
	cout<<"Type -1 : SUM IS = "<< sumOfNumbers(10,20) << endl; 
	cout<<"Type -2 : SUM IS = "<< sumOfNumbers(10,20,30) << endl; 
	cout<<"Type -3 : SUM IS = "<< sumOfNumbers(10,20.0f) << endl; 
	cout<<"Type -4 : SUM IS = "<< sumOfNumbers(10.2f,20.3f) << endl; 

	return 0;

// function definitions...

int sumOfNumbers(int x,int y)
	return (x+y);

int sumOfNumbers(int x,int y,int z)
	return (x+y+z);

int sumOfNumbers(int x,float y)
	return (x+(int)y);

float sumOfNumbers(float x,float y)
	return (x+y);
Type -1 : SUM IS = 30
Type -2 : SUM IS = 60
Type -3 : SUM IS = 30
Type -4 : SUM IS = 30.5

Keywords (like Linux, Java, Oracle etc) used in this website are the trademarks of their respective owners/company. This website is not affiliated to any company. The tutorials are designed by includehelp Team with the help of well known books and other online resources. These Tutorials are free for all, for learning purposes only. Enjoy learning:)
Copyright © 2015 - 2016. All Rights Reserved.