Search Your Topic

config
Saturday, 17 June 2017 07:26

C++ Overloading (Function and Operator)

Written by
Rate this item
(0 votes)

If we create two or more members having 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

It is because these members have parameters only.

Types of overloading in C++ are:

  • Function overloading
  • Operators overloading

C++ Function Overloading

Having two or more function with same name but different in parameters, is known as function overloading in C++.

The advantage of Function overloading is that it increases the readability of the program because you don't need to use different names for same action.

C++ Function Overloading Example

Let's see the simple example of function overloading where we are changing number of arguments of add() method.

 
  1. #include <iostream>  
  2. using namespace std;  
  3. class Cal {  
  4.     public:  
  5. static int add(int a,int b){    
  6.         return a + b;    
  7.     }    
  8. static int add(int a, int b, int c)    
  9.     {    
  10.         return a + b + c;    
  11.     }    
  12. };   
  13. int main(void) {  
  14.     Cal C;  
  15.     cout<<C.add(10, 20)<<endl;    
  16.     cout<<C.add(12, 20, 23);   
  17.    return 0;  
  18. }  

Output:

30
55

 

 

C++ Operators Overloading

Operator overloading is used to overload or redefine most of the operators available in C++. It is used to perform operation on user define data type.

The advantage of Operators overloading is to perform different operations on the same operand.

C++ Operators Overloading Example

Let's see the simple example of operator overloading in C++. In this example, void operator ++ () operator function is defined (inside Test class).

 
  1. #include <iostream>  
  2. using namespace std;  
  3. class Test  
  4. {  
  5.    private:  
  6.       int num;  
  7.    public:  
  8.        Test(): num(8){}  
  9.        void operator ++()   
  10.        {   
  11.           num = num+2;   
  12.        }  
  13.        void Print() {   
  14.            cout<<"The Count is: "<<num;   
  15.        }  
  16. };  
  17. int main()  
  18. {  
  19.     Test tt;  
  20.     ++tt;  // calling of a function "void operator ++()"  
  21.     tt.Print();  
  22.     return 0;  
  23. }  

Output:

The Count is: 10

 

 

Read 64 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.