ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Function overloading in c++ with simple program example

Updated on June 14, 2016

1. What is Function Overloading?


This hub explains the various points that a c++ programmer should be aware of when dealing with Function overloading. Function overloading means the same function name can be used to perform different flavor of a task. Say for example the AddNumber function can add two integers or two floating-point numbers. Since the same function performs the tasks based on the passed-in parameters, we can say the function is overloaded. I mean, say the AddNumber function is overloaded to take care the duty of adding two integers or two floats. The function overloading comes under the compile time polymorphism as compiler resolves it during the compilation time.

How the compiler resolves the compile time polymorphism? It does Parameter matching. This has various rules. The function overloading is done by the parameters passed to the function and return type of the function doesn’t matter. The picture shown below makes you understand the factors that help the compiler to resolve the compile time polymorphism. Let us explore each factor with an example.

Source

2. Number of Parameter

The compiler looks at the number of parameters before making the choice of which function to call. Have a look at the below example.

//Sample 01: Overloaded One Param
void Test(int m)
{
	cout<<"void Test(int m)"<<endl;
}

//Sample 02: Overloaded two Param
void Test(int n, int m)
{
	cout<<"void Test(int n, int m)"<<endl;
}

The function Test is overloaded here. The compiler decides which function to call based on the number parameter the caller is passing the function Test. In the above example, even though both the functions are using integer(s) as an argument they differ by the number of parameters. So the call Test(12,10) calls the second function.

3. Types of parameter

Now have a look at the example given below. Here the types of parameter are differing even though the number of parameters is two in both the functions. The first function uses two integers and the second one uses one integer and one float. In this case, the compiler can able to resolve which function to call when the number of arguments is same. So the parameter type is also important.

//Sample 02: Overloaded two Param
void Test(int n, int m)
{
	cout<<"void Test(int n, int m)"<<endl;
}

//Sample 03: Overloaded Two Param different order
void Test(float m, int n)
{
	cout<<"void Test(float m, int n)"<<endl;
}

4. Order of Parameters

In some cases, the compiler resolves the ambiguity by comparing the parameters, based on the type of parameter and the order in which it is passed to the called function. Have a look at the example given below:

//Sample 03: Overloaded Two Param different Type
void Test(float m, int n)
{
	cout<<"void Test(float m, int n)"<<endl;
}

//Sample 04: overloaded two param differ by order
void Test(int m, float n)
{
	cout<<"void Test(int m, float n)"<<endl;
}

Here if you see, it is not possible to the compiler to resolve the above two overloads by using the only number of parameter and type of parameter. Why? Answer it yourself:

1) Can I resolve this by Number of parameters?

No. Both functions use two parameters. That is number parameter is same for both the functions.

2) Ok. Can I resolve it by type of parameters?

Again “No” since both the functions use one integer and one floating-point argument types. Now I believe you may come to the answer yourself. The compiler resolves it by the order of arguments. If the caller passes the integer as the first parameter and float as the second parameter then the compiler, while it generates the code, knows that second function should be called.

5. Default Parameter in Function

In function prototyping, we do specify the number of parameters, types of the parameters and the order in which the types parameter passed in and the return type. It is not required to specify the argument names in the function prototyping.

Consider the declaration below:

int add_numbers(int x, int y=0, int z = 0);

Here, we specified the argument names along with the argument types. Also, note that we need to specify the default value for the second and third arguments. And in our above example, it is 0 for third and second Parameters.


One more point, the default parameters should be specified from Right to the Left. That is, it is not possible to specify the default parameter when the parameter next to it is not a default parameter. Consider the below statement now:

int add_numbers(int x, int y=0, int z);


This is wrong. Because at runtime it not possible to skip the second parameter and pass value to the third one. Have look at the calling code below:


add_numbers(12, 14);


The value 14 always goes to argument y as the order matters. I can say like this also, how does the compiler know the value 14 is for Y or Z. So, the rule of thumb is, the second parameter value is for second argument y.


Below is the Example for Default parameters:

#include "stdafx.h"
#include <conio.h>


int add_numbers(int x, int y=0, int z = 0);

int add_numbers(int x, int y, int z)
{
            return x+y+z;
}

int _tmain(int argc, _TCHAR* argv[])
{

            int x = 15, y = 15, z = 12;
            printf("Added Result : %d\n", add_numbers(x));
            printf("Added Result : %d\n", add_numbers(x, y ));
            printf("Added Result : %d\n", add_numbers(x, y, z ));
            getch();
            return 0;
}
Source

6. Default parameter in Function Overloading

The function with default parameter can also be an overloaded function. But it may open the gate for ambiguous error. Look at the example given below:

//Sample 04: Two param with one default
void Test(char c, int t = 10)
{
	cout<<"void Test(char c, int t = 10)"<<endl;
}

//void Test(char c)   =>  ambiguous to previously overloaded function when called like Test(char)
//{
//}

The Test function is overloaded here with char as first parameter type and an integer as second parameter type. In the caller perspective, it can be called like the function with one parameter of type char or function with one more parameter of type integer. Now, look at the commented piece of code and the overloaded version gets only one char parameter. When a user tries to make a call by passing single char argument to the function, the compiler gets confused which version to call. So when you use an overloaded function with default parameters, be aware what is discussed here.

7. Promoting a variable

Promoting the arguments passed to the function happens when the match does not occur. Note that the primary match occurs based on Number of parameters, type(s) of parameter and order of parameter. To know how promotion works look at the below example:

//Sample 05: Let us see promotion from float
void Test(double k)
{
	cout<<"void Test(double k)"<<endl;
}

Let us say there is no function that takes float as a single parameter. In this situation, if the caller passes the test function a float parameter, the parameter float is promoted to double and the above function gets called. As this promotion from long to double does not cause any loss of the data, the compiler does call the above-shown function even though no direct match occurs.

8. The complete Example

Below is the complete example that shows the overloaded Test function. As this hub concentrates purely on Function overloading, I gave the very simple example.

// TestIt.cpp : Defines the entry point for the console application.
// constructor initializer list

#include "stdafx.h"
#include <iostream>
using namespace std;


//Sample 01: Overloaded One Param
void Test(int m)
{
	cout<<"void Test(int m)"<<endl;
}

//Sample 02: Overloaded two Param
void Test(int n, int m)
{
	cout<<"void Test(int n, int m)"<<endl;
}

//Sample 03: Overloaded Two Param different Type
void Test(float m, int n)
{
	cout<<"void Test(float m, int n)"<<endl;
}

//Sample 04: overloaded two param differ by order
void Test(int m, float n)
{
	cout<<"void Test(int m, float n)"<<endl;
}

//Sample 04: Two param with one default
void Test(char c, int t = 10)
{
	cout<<"void Test(char c, int t = 10)"<<endl;
}

//void Test(char c)   =>  ambiguous to previously overloaded function when called like Test(char)
//{
//}

//Sample 05: Let us see promotion from float
void Test(double k)
{
	cout<<"void Test(double k)"<<endl;
}


int main()
{
	//Usage 00: Declarations
	int x = 15;
	int y = 10;
	float t = 18.72f;
	double d = 4.16743;
	char c = 'A';

	//Usage 01: Single int match
	Test(x);

	//Usage 02: Two int match number of parameter
	Test(x,y);

	//Usage 03: Match by Order of Parameter
	Test(t, x);
	Test(x, t);

	//Usage 04a: Match by with and without default parameter
	Test(c);
	Test(c,x);

	//Usage 05: Automatic Promotion [Float to Double is Promotable, as there is no loss of data]
	Test(t);
}

The output of executing the above program is shown below:

Source

Comments

    0 of 8192 characters used
    Post Comment

    • jabelufiroz profile image

      Firoz 3 years ago from India

      Nice article on Function Overloading. Voted up.

    • sirama profile image
      Author

      sirama 3 years ago

      Thanks Firoz.

    • MysticPrince profile image

      Arindam Sarkar 3 years ago from The Source Code

      Nice :)

      One thing I'd add, that while using default parameters, the default values should always come after non-default ones.

      For eg.

      func(int a,int b=10) is alright

      BUT

      func(int a=10,int b) will generate an Error..

    • Carl8033 profile image

      Alexander Okelo 3 years ago

      It been a while since I learned how to "hello world" with C++ lol. Thanks for jogging my memory. Great hub.

    • Marsha Musselman1 profile image

      Marsha Musselman 3 years ago from Michigan, USA

      I'm not even going to try to read and understand this hub, for I know it will be over my head. I'm not a programmer.

      The reason I'm commenting here is that I was intrigued when I saw what you write about because recently we had something come up on my husband's computer. We were trying to download a security suite. It said that it couldn't be installed because it was missing a dll component. We found out that the specific component is used for Visual C ++. I'm not sure that is what you are talking about here?

      After we did several things including downloading the missing dll, the computer locked up. It's currently in the shop.

      My question to you is what programs is the Visual C ++ used for? We weren't even aware that it was on his computer.

      I voted this up, I'm sure it will help those in the programming field of work.

    • sirama profile image
      Author

      sirama 3 years ago

      @Marsha Musselman1: Thanks for the Up Vote.

      Visual C++ is one computer program development tool. The security suite that you installed depends on the Visual C++. You may be missed some install steps that is making the security suite a partial install. Hope the the problem will be rectified in the service centre.

    Click to Rate This Article