Function overloading – C++

Date: February 18th, 2010
Author: Stefan Batanov

In this tutorial we will try to explain what the term function overloading is.

A function is overloaded when same name is given to different function. However, the two functions with the same name will differ at least in one of the following.

a) The number of parameters
b) The data type of parameters
c) The order of appearance

These three together are referred to as the function signature.

For example if we have two functions :

void foo(int i,char a);
void boo(int j,char b);

Their signature is the same (int ,char) but a function

void moo(int i,int j) ; has a signature (int, int) which is different.

While overloading a function, the return type of the functions need to be the same.

In general functions are overloaded when :

1. Functions differ in function signature.
2. Return type of the functions is the same.

Here s a basic example of function overloading

  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class arith {
  5. public:
  6.  void calc(int num1)
  7.  
  8. {
  9. cout<<"Square of a given number: " <<num1*num1 <<endl;
  10. }
  11.  
  12.  void calc(int num1, int num2 )
  13.  
  14. {
  15. cout<<"Product of two whole numbers: " <<num1*num2 <<endl;
  16. }
  17. };
  18.  
  19.  
  20. int main() //begin of main function
  21. {
  22.     arith a;
  23.     a.calc(5);
  24.     a.calc(6,7);
  25. }

I will explain what we did in the function overloading example.

First the overloaded function in this example is calc. If you have noticed we have in our arith class two functions with the name calc. The fist one takes one integer number as a parameter and prints the square of the number. The second calc function takes two integer numbers as parameters, multiplies the numbers and prints the product. This is all we need for making a successful overloading of a function.

a) we have two functions with the same name : calc
b) we have different signatures : (int) , (int, int)
c) return type is the same : void

The result of the execution looks like this

  1. Square of a given number: 25
  2. Product of two whole numbers: 42

The result demonstrates the overloading concept. Based on the arguments we use when we call the calc function in our code :

  1. a.calc(5);
  2. a.calc(6,7);

The compiler decides witch function to use at the moment we call the function.

I hope that everything about function overloading in C++ is clear now. If you haven\”t got that I recommend to go buy some C++ book on Amazon.com.

VN:F [1.9.18_1163]
Rating: 6.9/10 (37 votes cast)
Function overloading - C++, 6.9 out of 10 based on 37 ratings

100 Responses to “Function overloading – C++”

Leave a Reply