Skip to main content

Overloaded functions and default values

Let us look at a drawback of C language. Let us say you want to write a function to add two integers.

int add(int a,int b)
{
   return a+b;
}
But will this function add two floats and return the answer? No. Even if we call the function with floats, it converts them to integers and returns an integer. So, we have to write another function for float which basically is very much similar except for data types.

float add(float a,float b)
{
   return a+b;
}

Wait, wait. This is wrong. We can not write two functions which have same name. Program will not compile.

Let us change the name of second function to addf()

float addf(float a,float b)
{
   return a+b;
}

 Similarly we may have to write addd for double values, addar for arrays and so on. And these do not look very intuitive.

C++ solves this problem by letting you have overloaded functions - functions with same name but different number/type of parameters.

Overloaded functions

Functions having same name but different number and/or type of parameters are called overloaded functions. Depending on the type/number of arguments, the  correct overloaded function is selected.

The previous two functions we have seen above can both be called add() in C++. Let us see this concept with a complete program. 

#include<iostream>
using namespace std;
void print(int num)
{
   cout<<"The integer is "<<num<<"\n";
}
void print(float num)
{
   cout<<"The floating point number is "<<num<<"\n";
}
int main()
{
   int a=22;
   float b = 1.5f;
   print(a);
   print(b);
  // print(1.9);  
}
We have written two function print(int num) and print(float num). Both have same name but one has an integer parameter and the other has a float parameter.

When print() is called with a, the first function print(int num) is called because a is an integer. And print(b)  will call print(float num).

Output of the program is
The integer is 22
The floating point number is 1.5
What is the commented line in the program? Shall we uncomment it?

int main()
{
   int a=22;
   float b = 1.5f;
   print(a);
   print(b);
   print(1.9);  
}
Now when we compile the program, we get a syntax error - ambiguity error.

What went wrong? In C++, the arguments are converted to type of parameters during a function call automatically. e.g. if there is a function int square(int) and it is called as square(1.4), the number is converted to an integer (1) and function is called.

But now we have two functions with different types of parameters int and float. So there is a confusion. Should 1.9 be converted to int or float?

But, wait! Isn't 1.9 a float?

It is not. 1.9 is a double. Unqualified real literal numbers are double in C and C++. A suffix of f or F, will make the literal as float number.

So we need to correct the program by saying print(1.9f)?

We can use explicit conversion.

#include<iostream>
using namespace std;
void print(int num)
{
   cout<<"The integer is "<<num<<"\n";
}
void print(float num)
{
   cout<<"The floating point number is "<<num<<"\n";
}
int main()
{
   int a=22;
   float b = 1.5f;
   print(a);
   print(b);
   print((float)1.9);  
}   
Now the output is
The integer is 22
The floating point number is 1.5
The floating point number is 1.9

Default values for parameters 

Functions can specify default values for one or more parameters. If argument is not passed for that parameter, then its default value will be taken. 

Let us look at an example. 


int sum(int a,int b,int c=0,int d=0);
int sum(int a,int b,int c,int d)
{
   return a+b+c+d;
}
Here sum function takes 4 parameters. But if you omit d, then it is taken as 0.

So the following function call is valid

int s1 = sum(m,n,p);//d is 0
  
Similarly if we omit 3rd argument, the function call is still valid and c is taken as 0.

Let us call the function with different possibilities.


int s1 = sum(10,11,3,4);//s1 is 28
int s2 = sum(12,13,14);//s2 is 39
int s3 = sum(15,16);//s3 is 31
int s4 = sum(17);//error. no default value for b

The last call to sum function with just one argument is wrong. Because the function has default values for c and d, not for b. 

Where to specify values?

We can ideally specify default values in declaration of function. But providing values in definition of function is also correct. But we should not specify in both of them.

What went wrong?

We have a program with default parameters here. But it does not compile.


#include<iostream>
using namespace std;
int product(int a=1,int b,int c=1);
int main()
{
   cout<<product(8,8,8)<<endl;
   cout<<product(10);
}
int product(int a,int b,int c)
{
  return a*b*c;
}
Why?

The compilation error says
 error: default argument missing for parameter 2 of ‘int product(int, int, int)’

As we gave default value to a, but not b, we get an error. 

This means that we start by giving values to rightmost parameter and then proceed towards left. We can not omit a parameter without value in the middle.


Comments

Popular posts from this blog

C quizard app

C Quizard is an app which will make you from newbie in C to C wizard. The app has quiz on various topics, solved programs with explanations. It also lets you take a 25 question quiz any time offline. You can download CQuizard by Hegdeapps from google play.

Find the error in C++ program

This C++ program is not compiling. What do you think is the error with the program? #include<iostream> using namespace std; int main() {    int arr[10];    arr={1,2,3,4,5,6,7,8};    cout<<"arr[0]="<<arr[0];    return 0; } Is the error due to Not using printf Initialising the array with only 8 elements instead of 10 Initialising array in the next statement instead of in definition. None of the above  Now if you like this question, there are plenty more questions like this and programs and notes in my app Simplified C++. Download the Simplif ied C++   by Hegdeapps now By the way the correct answer is (3)

Polymorphism

You hear the term Polymorphism too frequently with object oriented languages. Along with Inheritance and Encapsulation, polymorphism is one of the corner stones of object oriented design. What is Polymorphism, exactly? Polymorphism is a mechanism by which you provide single interface for multiple methods. (poly - many, morph - form). In C++, polymorphism can be compile time or run-time. Compile time polymorphism is provided with the help of overloaded operators/functions and templates. Run time polymorphism is provided with the help of virtual functions and late binding. Late Binding: Connecting a function call to function body is called binding. Most functions use early binding where this binding happens before the program is run - during compile time. This is also called static binding. Late binding (also called dynamic binding)  is when a function call is connected to function body at run time. This is done after looking at the type of the object. Late binding is...