All About C++

Get Pure Concepts of C++

Friday 3 June 2016

Operator overloading in C++ with code example

Operator overloading
Operator overloading is a technique in C++ where we overload an operator. Here operators are <,>,>=, <= or  =.
The true concept about operator overloading is that using operator overloading scheme we manipulate or interact two objects  . For example we add the attributes of two different objects etc.
I give an example to understand the overloading concept
In this example, two different distances belong to two different objects and they are added through operator overloading
#include<iostream>
using namespace std;
class distancee
{ private:
int feet;
float inches;
public:
       distancee( ):feet(0),inches(0.0)
            { }
      distancee(int ft,float in) : feet(ft),inches(in)
      {  }
     
      void getdist()
      {
            cout<<"enter feet";
            cin>>feet;
            cout<<"enter inches";
            cin>>inches;
      }
      void showdist() const
      { cout<<feet<<inches<<endl; }
      void operator +=(distancee);
};
void distancee::operator += (distancee d2)
{
      feet += d2.feet;
      inches +=d2.inches;
      if(inches >= 12.0)
      {
            inches -= 12.0;
            feet++;
      }
};
int main()
{
      distancee dist1;
      dist1.getdist();
      cout<<"dist1";
      dist1.showdist();
      distancee dist2(11,6.35);
      cout<<"dist2";
      dist2.showdist();
      dist1+=dist2;
      cout<<"after addition";
      cout<<"dist1";
      dist1.showdist();
      cout<<endl;
      return 0;
}

In this code here we manipulate two different objects attributes together

feet += d2.feet;
       inches +=d2.inches;
       if(inches >= 12.0)
       {
              inches -= 12.0;
              feet++;}
Here:
feet and d2.feet indicates two different objects values


No comments:

Post a Comment