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

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)

Abstract class

 If we can not create any objects of a class, then it is called an abstract class. A class is made abstract by adding at least one pure virtual function to it. Pure virtual function A function is said to be a pure virtual function , if it has no definition but has only declaration. Pure virtual function is defined with the keyword virtual and followed by return type, function name and "=0". class Shape { public: virtual void printarea() =0 ; }; int main () { Shape obj1; //error } Here printarea() function of Shape class is a pure virtual function as it has no body. To make a function as pure virtual function, you should use =0 at the end of virtual function declaration Abstract class When a class has at least one pure virtual function, it is incomplete and no objects can be created from that class. Such a class is called an abstract class . In the earlier example class Shape is an abstract class, and objects can not be created from t...

Friends of C++

Friend function Remember that a member which is not public (Private and protected )  can not be accessed from outside the class.  Three are some situations where you may need to access these. Keyword friend  is used for this. A friend functions and classes can access all members of a class.  This concept is controversial. People say friend concept violates data encapsulation  A friend function is a non-member function but still can access all the members of a class including private members. Such a function is declared within class body with the prefix "friend" class Number { int num; public: Number( int m){ /*code*/ } friend void printNum(Number ob); /*friend function*/ }; void printNum (Number obj) { cout << obj.num << "endl" ; } printNum() is not member of class Number . But it can still access all members including private members, because it is a friend. Friend class An object of a friend c...