Tutorial Study Image

C++ Overloading


June 2, 2023, Learn eTutorial
349

Let us learn about different types of overloading in C++ with examples in this tutorial. Mainly in C++, the overloading is of two types and they are function overloading and operator overloading. Now let us learn the C++ overloading in detail.

In C++ we can mainly overload :

  • methods,
  • constructors
  • indexed properties

This is due to the fact that these members have parameters only.

The two types of overloading in C++

Mainly there are two types of overloading in C++

  • Function overloading
  • Operator overloading
C++ Overloading

C++ Function overloading

In C++, function overloading is defined as the process of having two or more functions with the same name but differing in parameters. Overloading a function redefines it mainly by using different types of arguments or by using a different number of arguments. Only through these distinctions can the compiler distinguish between the functions.

Function overloading has the benefit of improving program readability by eliminating the need for multiple names for the same action.

For example,
here you can see the same name but different arguments


int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
 

All four functions are overloaded in this case.

Take note that the return types of these four functions are not the same. Overloaded functions can have different return types or they can't, but they must have different arguments.

For example,
// Error code

int test(int a) { }

double test(int b){ }

Both functions in this case have the same name, type, and number of arguments. As a result, the compiler will generate an error.

Example 1: C++ function overloading mainly using different types of parameters

Write a program in order to compute the absolute value and its works for both int and float.


#include <iostream>
using namespace std;

// A float-type parameter in a function
float absolute(float var){
    if (var < 0.0)
        var = -var;
    return var;
}

// A function with an int-type parameter
int absolute(int var) {
     if (var < 0)
         var = -var;
    return var;
}

int main() {
    
    // call function with int type  parameter
    cout << "Absolute value of -7 = " << absolute(-7) << endl;

    // call function with float type parameter
    cout << "Absolute value of 7.7 = " << absolute(7.7f) << endl;
    return 0;
}

 

Output:


Absolute value of -7 = 7
Absolute value of 7.7 = 7.7

This fig shows the absolute() function is working with overloading.

C++ Overloading

The absolute() function is overloaded in the above program. The corresponding function is called based on the type of parameter passed during the function call.

The program shows C++ overloading using a different number of parameters


#include <iostream>
using namespace std;

// function with 2 parameters
void display(int var1, double var2) {
    cout << "Integer number: " << var1;
    cout << " and double number: " << var2 << endl;
}

// function with double type single parameter
void display(double var) {
    cout << "Double number: " << var << endl;
}

// function with int type single parameter
void display(int var) {
    cout << "Integer number: " << var << endl;
}

int main() {

    int a = 7;
    double b = 7.7;

    // calling a function with an int type parameter
    display(a);

    // calling a function with an double type parameter 
    display(b);

    // using two parameters to call a function
    display(a, b);

    return 0;
}

 

Output:


Integer number: 7
Double number: 7.7
Integer number: 7 and double number: 7.7

The display() function is called three times with different arguments in this case. The corresponding display() function is called depending on the number and type of arguments passed.

the figure shows the Working of the overloading for the display() function

C++ Overloading

All of these functions have the same return type, but this is not always the case with function overloading.

Point to remember: Many standard library functions in C++ are overloaded. The sqrt() function, for example, can accept parameters such as double, float, int, and so on. This is possible because the sqrt() function in C++ is overloaded

Ambiguity and Function Overloading

Function overloading occurs when the compiler is unable to determine which of the overloaded functions should be invoked.

When the compiler displays the ambiguity error, the program is not executed.

What are the main causes of function overloading?

C++ Overloading

Type conversion

Example program for type conversion


#include<iostream>  
using namespace std;  
void fun(int);  
void fun(float);  
void fun(int i)  
{  
    std::cout << "Value of i is : " <<i<< std::endl;  
}  
void fun(float j)  
{  
    std::cout << "Value of j is : " <<j<< std::endl;  
}  
int main()  
{  
    fun(12);  
    fun(1.2);  
    return 0;  
}  

 

The error stated in the above example is "call of overloaded 'fun(double)' is ambiguous." The first function will be called fun(10). According to our prediction, fun(1.2) calls the second function. However, this does not apply to any function because, in C++, all floating-point constants are treated as doubles rather than floats. The program works if we change float to double. As a result, this is a float to double type conversion.

Function with Default Arguments

Example program for function with Default Arguments


#include<iostream>  
using namespace std;  
void fun(int);  
void fun(int,int);  
void fun(int i)  
{  
    std::cout << "Value of i is : " <<i<< std::endl;  
}  
void fun(int a,int b=9)  
{  
    std::cout << "Value of a is : " <<a<< std::endl;  
    std::cout << "Value of b is : " <<b<< std::endl;  
}  
int main()  
{  
    fun(12);  
   
    return 0;  
}  

 

The preceding example demonstrates an error: "Call of overloaded 'fun(int)' is ambiguous." The fun(int a, int b=9) function can be called in two ways: one with one argument, fun(12), and the other with two arguments, fun(12) (4,5). With one argument, the fun(int i) function is called. As a result, the compiler could not choose between fun(int I and fun(int a, int b=9).

Function with pass-by-reference

Example program for function with pass-by-reference


#include <iostream> 
using namespace std;  
void fun(int);  
void fun(int &);   
int main()  
{  
int a=10;  
fun(a); // error, which f()?  
return 0;  
}  
void fun(int x)  
{  
std::cout << "Value of x is : " <<x<< std::endl;  
}  
void fun(int &b)  
{  
std::cout << "Value of b is : " <<b<< std::endl;  
}  

 

The preceding example contains an error: "Call of overloaded 'fun(int&)' is ambiguous." The first function accepts one integer argument, while the second accepts a reference parameter as an argument. The compiler does not know which function is required by the user in this case because there is no syntactical difference between fun(int) and fun(int) (int &).

Operators Overloading in C++

Operator overloading is a type of compile-time polymorphism where the operator will be overloaded in order to give the user-defined data type a special meaning. Most of the operators available in C++ are overloaded or redefined using operator overloading. It's used to run an operation on a user-defined data type. C++, allows you to add variables of a user-defined data type that are applied to built-in data types.

The benefit of operator overloading is that it allows you to perform multiple operations on the same operand.

There are some operators that cannot be overloaded and they are

  • Scope operator (::)
  • Sizeof
  • member selector(.)
  • member pointer selector(*)
  • ternary operator(?:)

The syntax for operator overloading


 return_type class_name  : : operator op(argument_list)  
 {  
      // is the body of the function.  
 }  
 

where the type of value returned by the function is the return_ type.

class_name which is known as the name of the class.

The operator op is an operator function in which op is the overloaded operator and the operator is the keyword.

Rules for operator overloading

  • Operators that are already in operation can only be overloaded; new operators cannot.
  • At least one operand of the user-defined data type is present in the overloaded operator.
  • The friend function cannot be used to overload specific operators. The member function, on the other hand, can be used to overload those operators.
  • When unary operators are overloaded via a member function, they take no explicit arguments, but when overloaded via a friend function, they take one argument.
  • When binary operators are overloaded via a member function, they take one explicit argument; when they are overloaded via a friend function, they take two explicit arguments.

Let's look at a simple example of C++ operator overloading. The void operator ++ () operator function is defined in this example (inside the Test class).

A program that is used to overload the unary operator ++.


#include <iostream>   
using namespace std;    
class Test    
{    
   private:    
      int num;    
   public:    
       Test(): num(8){}    
       void operator ++()         {     
          num = num+2;     
       }    
       void Print() {     
           cout<<"The Count will be: "<<num;     
       }    
};    
int main()    
{    
    Test tt;    
    ++tt;  // calling of a function "void operator ++()"    
    tt.Print();    
    return 0;    
}    

 

Output:


The Count will be:10

A program that is used to overload the binary operator


#include <iostream>  
using namespace std;  
class A  
{  
    
    int x;  
      public:  
      A(){}  
    A(int i)  
    {  
       x=i;  
    }  
    void operator+(A);  
    void display();  
};  
  
void A :: operator+(A a)  
{  
     
    int m = x+a.x;  
    cout<<"so the result of the addition of two objects will be : "<<m;  
  
}  
int main()  
{  
    A a1(5);  
    A a2(4);  
    a1+a2;  
    return 0;  
}  

 

Output:


so the result of the addition of two objects will be :9