C++ Overloading

In this C++ tutorial, let us have a look at C++ overloading, its types and example programs.

Introduction of C++ Overloading

Overloading is one of the most advanced features of object-oriented programming. It makes the operations on objects much easier. If we create two or more members having the same name but different in number or type of parameter, it is known as C++ overloading. In C++, we can overload

  • methods,
  • constructors, and
  • indexed properties

Types of Overloading

  • Function overloading
  • Operator overloading

Function Overloading

Function Overloading is defined as the process of having two or more function with the same name, but different in parameters is known as function overloading in C++.  

The benefit of using function overloading in C++ is, it improves the readability of the program that there is no need to use different names for the same action.

Program for C++ Function Overloading

This program is for function overloading when the number of arguments vary.

#include <iostream>    
using namespace std;    
class Cal {    
    public:    
static int add(int a,int b){      
        return a + b;      
    }      
static int add(int a, int b, int c)      
    {      
        return a + b + c;      
    }      
};     
int main(void) {    
    Cal C; // class object declaration.   
    cout<<C.add(10, 20)<<endl;      
    cout<<C.add(12, 20, 23);     
   return 0;    
}    

Output

30
55

Operator Overloading

Everyone likes the simplest way of programming. So, instead of making a call to the function explicitly, one would appreciate the method being called implicitly whenever the (+) operator is used. This is operator overloading.

Hence, Operator overloading refers to giving additional meaning to the arithmetic operators.

The benefit of Operators overloading is to implement different operations on the same operand.

The operator that cannot be overloaded are as follows:

  • Scope Resolution (::)
  • Member Selection(.)
  • Pointer to member selection(.*)
  • Conditional operator(?:)
  • Preprocessor Directive(#)

Program for Operator Overloading in C++

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

Output
The Count is: 10

Leave a Comment

Your email address will not be published. Required fields are marked *