codescracker


c++

C++ Function Overloading



« Previous Tutorial Next Tutorial »


When a several function declarations are specified for a single function name in the same scope, the (function) name is said to be overloaded. C++ allows functions to have the same name if it can distinguish them by their number and type of arguments. For example, following four functions are different in C++

float divide(int a, int b);
float divide(int a, int b, int c);
float divide(float x, float y);
float divide(float x, float y, float z);

That is, divide() taking two int type arguments is different from divide() taking three int type arguments is different from divide() taking two float type arguments is different from divide() taking three float type arguments.

This is known as function overloading.

Declaration and Definition

The key to function overloading is a function's argument list which is also known as the function signature. It is the signature, not the function type that enables function overloading.

If two function are having same number and types of arguments in the same order, they are said to have the same signature. Even if they are using distinct variable names, it does not matter. For example, following two functions have same signature :

void squar(int a, float b);	// function 1
void squar(int x, float y);     // same signature as that of function 1

C++ lets you to overload a function name provided the functions with the same name are having different signatures. The signature can differ in the number or in the type of arguments, or in both. To overload a function name, all you need to do is, declare and define all the functions with the same name but different signatures, separately. For example, following code fragment overloads function name printsquare()

void printsquare(int i);	// overloaded for integers #1
void printsquare(char c);	// overloaded for characters #2
void printsquare(float f);	// overloaded for floats #3
void printsquare(double d);	// overloaded for double floats #4

After declaring overloading functions, you must define them separately, as it is shown below for the above given declarations :

void printsquare(int i)
{
	cout<<"Integer "<<i<<"'s square is "<<i*i<<"\n";
}
void printsquare(char c)
{
	cout<<c<<" is a character "<<"Thus No Square for it"<<"\n";
}
void printsquare(float f)
{
	cout<<"Float "<<f<<"'s square is "<<f*f<<"\n";
}
void printsquare(double d)
{
	cout<<"Double float "<<d<<"'s square is "<<d*d<<"\n";
}

Thus, we see that there is not too much difficulty in declaring overloaded functions : they are declared as other functions are. Just one thing is to kept in mind that the arguments are sufficiently different to allow the functions to be differentiated to use.

The argument types are said to be part of the function's extended name. For instance, the name of above specified functions might be printsquare() but their extended names are different. That is they have printsquare(int), printsquare(char), printsquare(float), and printsquare(double) extended names respectively.

When a functions name is declared more than once in a program, the compiler will interpret the second (and subsequent) declaration(s) as follows:

(i) if the signatures of subsequent functions match the previous function's, then the second is treated as a re-declaration of the first.

(ii) if the signatures of the two functions match exactly but the return types differ, and is flagged at compile time as an error.

For example,

float square(float f);
double square(float x);         // error!!

Functions with the same signature and same name but different return types are not allowed in C++. You can have different return types, but only if the signatures are also different :

float square(float f);           // difference signature, hence
double square(double d);         // allowed

(iii) if the signatures of the two functions differ in either the number or type of their arguments, the two functions are considered to be overloaded.

Signed-ness (e.g., int versus unsigned int) and const-ness are also sufficiently different to tell functions apart i.e., functions with arguments with such differences are considered different functions.

Restrictions on Overloaded Functions

Several restrictions govern an acceptable set of overloaded functions :

(i) Any two functions in a set of overload functions must have different argument lists.

(ii) Overloading functions with argument lists of the same types, based on return type alone, is an error.

(iii) Member functions cannot be overloaded solely on the basis of one being static and the other non-static.

(iv) Typedef declarations do not define new types ; they introduces synonyms for existing types. They do not affect the overloading mechanism.
Consider the following code :

typedef char * PSTR;
void Print(char * szToPrint);
void Print(PSTR szToPrint);

The preceding two functions have identical arguments lists. PSTR is a synonym for type char *. In member scope, this code generates an error.

(v) Enumerated types are distinct types and can be used to distinguish between overloaded functions.

(vi) The types " array of" and " pointer to" are considered identical for the purposes of distinguishing between overloaded functions. This is true only for singly dimensioned arrays. Therefore, the following overloaded functions conflict and generate an error message.

void Print(char * szToPrint);
void Print(char szToPrint[]);

For multiply dimensioned arrays, the second and all succeeding dimensions are considered part of the type. Therefore, they are used in distinguishing between overloaded functions :

void Print(char szToPrint[]);
void Print(char szToPrint[][7]);
void Print(char szToPrint[][9][42]);

C++ Function Overloading Programs

Here are some example programs illustrates the working of function overloading in C++. Let's first look at the following example where the same function named print() is being used to print the different data types:

/* C++ Function Overloading - This C++ program
 * demonstrates the concept of function overloading
 * in C++ practically.
 */

#include<iostream.h>
#include<conio.h>

class printData
{
	public:
		void print(int i)         // function 1
		{
			cout<<"Printing int: "<<i<<"\n";
		}
		void print(double  f)     // function 2
		{
			cout<<"Printing float: "<<f<<"\n";
		}
		void print(char* c)
		{
			cout<<"Printing characters (string): "<<c<<"\n";
		}
};

void main()
{
	clrscr();
	printData pdobj;

	pdobj.print(5);      	      // called print() to print integer
	pdobj.print(50.434);         // called print() to print float
	pdobj.print("C++ Function Overloading");     // called print() to print string

	getch();
}

Here is the output produced by the above C++ program:

c++ function overloading

Here is another C++ program, also demonstrating function overloading in C++ practically

/* C++ Function Overloading - This C++ program
 * demonstrates the working of default arguments
 * in C++
 */

#include<iostream.h>
#include<conio.h>
void amount(float pri, int tim=2, float rat=0.06);
void amount(float pri, int tim, float rat)
{
	cout<<"\n\tPrincipal Amount = "<<pri;
	cout<<"\n\tTime = "<<tim;
	cout<<"\n\tRate = "<<rat;
	cout<<"\n\tInterest Amount = "<<(pri*tim*rat)<<"\n";
}
void main()
{
	clrscr();
	cout<<"Results on amount(2000)";
		amount(2000);
	cout<<"\nResults on amount(2500, 3)";
		amount(2500, 3);
	cout<<"\nResults on amount(2300, 3, 0.11)";
		amount(2300, 3, 0.11);
	cout<<"\nResults on amount(2500, 0.12)";
		amount(2500, 0.12);
	getch();
}

Here is the output of the above C++ program:

function overloading in C++

Let's look at another C++ program, illustrating the function overloading concepts in C++

/* C++ Function Overloading - This C++ program illustrates
 * the working of function overloading as compared to
 * default arguments in C++ */

#include<iostream.h>
#include<conio.h>
void amount(float pr, int ti, float ra)
{
	cout<<"\n\tPrincipal Amount = "<<pr;
	cout<<"\t\tTime = "<<ti<<" years";
	cout<<"\tRate = "<<ra;
	cout<<"\n\tInterest Amount = "<<(pr*ti*ra)<<"\n";
}
void amount(float pr, int ti)
{
	cout<<"\n\tPrincipal Amount = "<<pr;
	cout<<"\t\tTime = "<<ti;
	cout<<"\tRate = 0.04";
	cout<<"\n\tInterest Amount = "<<(pr*ti*0.04)<<"\n";
}
void amount(float pr, float ra)
{
	cout<<"\n\tPrincipal Amount = "<<pr;
	cout<<"\t\tTime = 2 years";
	cout<<"\tRate = "<<ra;
	cout<<"\n\tInterest Amount = "<<(pr*2*ra)<<"\n";
}
void amount(int ti, float ra)
{
	cout<<"\n\tPrincipal Amount = 2000";
	cout<<"\t\tTime = "<<ti;
	cout<<"\tRate = "<<ra;
	cout<<"\n\tInterest Amount = "<<(2000*ti*ra)<<"\n";
}
void amount(float pr)
{
	cout<<"\n\tPrincipal Amount = "<<pr;
	cout<<"\t\tTime = 2 years";
	cout<<"\tRate = 0.04";
	cout<<"\n\tInterest Amount = "<<(pr*2*0.04)<<"\n";
}
void main()
{
	clrscr();
	cout<<"Results on amount(2000.0F)";
		amount(2000.0F);
	cout<<"\nResults on amount(2500.0F, 3)";
		amount(2500.0F, 3);
	cout<<"\nResults on amount(2300.0F, 3, 0.11F)";
		amount(2300.0F, 3, 0.11F);
	cout<<"\nResults on amount(2, 0.12F)";
		amount(2, 0.12F);
	cout<<"\nResults on amount(6, 0.07F)";
		amount(6, 0.07F);
	getch();
}

Below is the sample output of this C++ program:

c++ function overloading programs

Here is one more C++ program to illustrates the concept of function overloading in C++

/* C++ Function Overloading - C++ Program Example
 * demonstrating function overloading in C++ */

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
float calarea(float a, float b, float c)
{
	float s, are;
	s = (a+b+c)/2;
	are = sqrt(s*(s-a)*(s-b)*(s-c));
	return are;
}
float calarea(float a, float b)
{
	return a*b;
}
float calarea(float a)
{
	return a*a;
}
void main()
{
	clrscr();
	int choice, s1, s2, s3, a;
	do
	{
		cout<<"\nArea Calculation Main Menu\n";
		cout<<"1.Triangle\n";
		cout<<"2.Square\n";
		cout<<"3.Rectangle\n";
		cout<<"4.Exit\n";
		cout<<"Enter your choice (1-4): ";
		cin>>choice;
		cout<<"\n";
		switch(choice)
		{
			case 1: cout<<"Enter three sides: ";
				cin>>s1>>s2>>s3;
				a = calarea(s1, s2, s3);
				cout<<"Area = "<<a;
				break;
			case 2:	cout<<"Enter a side: ";
				cin>>s1;
				a = calarea(s1);
				cout<<"Area = "<<a;
				break;
			case 3:	cout<<"Enter length and breadth: ";
				cin>>s1>>s2;
				a = calarea(s1, s2);
				cout<<"Area = "<<a;
				break;
			case 4: cout<<"Exiting...press any key...";
				getch();
				exit(1);
			default:cout<<"Wrong choice..!!";
		}
		cout<<"\n";
	}while(choice>0 && choice<=4);
	getch();
}

Below are the two sample runs of the above C++ program:

c++ function overloading examples

c++ function overloading default parameters

Let's take one more C++ program for the complete understanding on function overloading in C++

/* C++ Function Overloading - Example program
 * demonstrating function overloading in C++
 */

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int divide(int num, int den)
{
	if(den==0)
	{
		return -1;
	}
	if((num%den)==0)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
int divide(int a)
{
	int j = a/2, flag = 1, i;
	for(i=2; (i<=j) && (flag); i++)
	{
		if(a%i == 0)
		{
			flag = 0;
		}
	}
	return flag;
}
void main()
{
	clrscr();
	int choice, res, a, b;
	do
	{
		cout<<"1.Check for divisibility\n";
		cout<<"2.Check for Prime\n";
		cout<<"3.Exit\n";
		cout<<"Enter your choice(1-3): ";
		cin>>choice;
		cout<<"\n";
		switch(choice)
		{
			case 1: cout<<"Enter numerator and denominator: ";
				cin>>a>>b;
				res = divide(a, b);
				if(res == -1)
				{
					cout<<"Divide by zero error..!!\n";
					break;
				}
				cout<<((res) ? "It is" : "It is not")<<"\n";
				break;
			case 2:	cout<<"Enter the number: ";
				cin>>a;
				res = 0;
				res = divide(a);
				cout<<((res) ? "It is" : "It is not")<<"\n";
				break;
			case 3: cout<<"Exiting...press any key...";
				getch();
				exit(1);
			default:cout<<"Wrong choice..!!";
		}
		cout<<"\n";
	}while(choice>0 && choice<=3);
	getch();
}

Here are the sample runs of the above C++ program

c++ function overloading return type

function overloading

function overloading definition

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test