Skip to main content

Operator Overloading in C++

Subscribe us for our YouTube channel and any kind of help
Operator overloading allows the programmer to define how operators (such as +, -, ==, =, and !) should interact with various data types. Because operators in C++ are implemented as functions, operator overloading works very analogously to function overloading.

Consider the following example:

1
2
3
int nX = 2;
int nY = 3;
cout << nX + nY << endl;
C++ already knows how the plus operator (+) should be applied to integer operands — the compiler adds nX and nY together and returns the result. Now consider this case:

1
2
3
Mystring cString1 = "Hello, ";
Mystring cString2 = "World!";
cout << cString1 + cString2 << endl;
What would you expect to happen in this case? The intuitive expected result is that the string “Hello, World!” is printed on the screen. However, because Mystring is a user-defined class, C++ does not know what operator + should do. We need to tell it how the + operator should work with two objects of type Mystring. Once an operator has been overloaded, C++ will call the appropriate overloaded version of the operator based on parameter type. If you add two integers, the integer version of operator plus will be called. If you add two Mystrings, the Mystring version of operator plus will be called.

Almost any operator in C++ can be overloaded. The exceptions are: arithmetic if (?:), sizeof, scope (::), member selector (.), and member pointer selector (.*). You can overload the + operator to concatenate your user-defined string class, or add two Fraction class objects together. You can overload the << operator to make it easy to print your class to the screen (or a file). You can overload the equality operator (==) to compare two objects. This makes operator overloading one of the most useful features in C++ -- simply because it allows you to work with your classes in a more intuitive way.

Before we go into more details, there are a few things to keep in mind going forward.

First, at least one of the operands in any overloaded operator must be a user-defined type. This means you can not overload the plus operator to work with one integer and one double. However, you could overload the plus operator to work with an integer and a Mystring.

Second, you can only overload the operators that exist. You can not create new operators. For example, you could not create an operator ** to do exponents.

Third, all operators keep their current precedence and associativity, regardless of what they're used for. For example, the bitwise XOR operator (^) could be overloaded to do exponents, except it has the wrong precedence and associativity and there is no way to change this.

Within those confines, you will still find plenty of useful functionality to overload for your custom classes!


An Example...

#include<iostream>
#include<cmath>

using namespace std;


class complex
{
 public: int real,img;

  complex()
  {
   cout<<"inside default constructor"<<endl;
  }

  complex(int a)
  {
   cout<<"inside parameterized constructor"<<endl;
  }

  complex(const complex &c)
  {
   cout<<"inside copy constructor"<<endl;
  }

  void get_complex();
//  void put_complex();
  complex operator+(complex&);
  complex operator-(complex&);
  complex operator-();
  complex operator++();
  complex operator++(int);
  complex operator=(complex c);
  complex operator,(complex c);
  friend ostream& operator<<(ostream &cout,complex &c);
  friend istream& operator>>(istream &input,complex &c);
  ~complex()
  {
   cout<<"inside destructor"<<endl;
  }



};


ostream& operator<<(ostream &dout,complex &c)
{
dout<<c.real<<endl;
dout<<c.img<<endl;
}

istream& operator>>(istream &input,complex &c)
{
input>>c.real;
input>>c.img;
}



void complex::get_complex()//taking real and img inputs for each complex no
{
 cout<<"Enter the real part"<<endl;
 cin>>real;
 cout<<"Enter the imaginary part"<<endl;
 cin>>img;
}

/*
void complex::put_complex()//printing the complex no
{
 cout<<real<<endl;
 cout<<img<<endl;
}*/


complex complex::operator+(complex &c)//operator overloading for the + operator
{

 complex temp;
 temp.real=real+c.real;
 temp.img=img+c.img;
 return (temp);
}

complex complex::operator-(complex &c)//operator overloading for the - operator
{
 complex temp;
 temp.real=real-c.real;
 temp.img=img-c.img;
 return temp;
}

complex complex::operator-()//operator overloading for the unary minus operator
{

complex temp;
 temp.real=-real;
 temp.img=-img;
 return temp;
}

complex complex::operator++()//operator overloading for the ++(prefix) operator
{
 complex temp;
 temp.real=++real;
 temp.img=++img;
 return temp;
}

complex complex::operator++(int x)//operator overloading for the ++(prefix) operator
{
 complex temp;
 temp.real=real++;
 temp.img=img++;
 return temp;
}

complex complex::operator=(complex c)//operator overloading for the = operator
{

 real=c.real;
 img=c.img;
 return *this;
}

complex complex::operator,(complex c)//operator overloading for the = operator
{
 return c;
}


int main()
{

 complex c1;//invoking default constructor
 complex c2(20);//invoking parameterized constructor
 complex c3(c2);//invoking copy constructor
 complex c4,c5;

 c1.get_complex();
 c2.get_complex();
 cout<<"after addition";
 c3=c2+c1;
 cout<<c3;

 cout<<"after subtraction";
 c3=c1-c2;
 cout<<c3;

 cout<<"after unary minus";
 c3=-c3;
 cout<<c3;

 cout<<"after prefix operator";
 c3=++c3;
 cout<<c3;

 cout<<"after postfix operator";
 c4=c3++;
 cout<<c4;




 return 0;
}

Comments

Popular posts from this blog

CDAC CCAT Rank - Which Centre you Should go for...

Subscribe us for our YouTube channel and any kind of help Click here to ask questions regarding CDAC 1. C-DAC (Head Quarters) Pune    CDAC's Admission Booklet- Process of Admission to Post Graduate Diploma Courses of C-DAC                         click below to know about the CCAT's This batch allotment                click above to know about the CCAT's This batch allotment Rank 1-300 c-dac HQ has been the best from the start. 2.  Sunbeam Pune Rank 300-500 I got very positive feedback from my friends who are in c-dac banglure main campus,since there are many companies you may get more opportunities. 3.  C-DAC Knowledge Park Rank 400-700 It as very good faculty .Almost all the students get placed here every year. 4. C-DAC Hyderabad Rank 200-1000 (It depends on the course which you select) C-DAC hyderabad is very good for the course PG-DESD. PG-DESD course is in hyderbad is better than pune HQ as per the past feedback.It as v

CDAC COURSES AND PLACEMENTS, WHICH IS BETTER FOR YOU

Subscribe us for our YouTube channel and any kind of help   Click here to ask questions regarding CDAC Before going through this post, I would like to draw your attention towards the importance of this post. This page not only explains my experience in CDAC but also aims at answering the queries of you all who are going or looking to have a course from CDAC. Kindly post your queries at the bottom of this page and we will get back to you within 24 hours. Kindly do not post your queries as an Anonymous user and do not forget to subscribe via email so as to keep track of your query.                         click below to know about the CCAT's This batch allotment                 click below to know about the CCAT's This batch allotment ______________________________________________ NOW a day lot of the graduates and post graduates are wondering most of the times on which course they should go for. What are the pros & cons of joining a particular ce

Placement Statistics - 2011 & 2012

Subscribe us for our YouTube channel and any kind of help                          Post your queries below and we will get back to you in no more than 24 hours.  Click here to ask questions regarding CDAC                         click below to know about the CCAT's This batch allotment                     click above to know about the CCAT's This batch allotment CDAC's Admission Booklet- Process of Admission to Post Graduate Diploma Courses of C-DAC Click here to see placement statistics About C-CAT, Exam Pattern and Books No. of Seats Across Various Training Centres Important Dates - 2014 Tags: CDAC, CDAC scope in future, CDAC placements, CDAC training, CDAC recruitment, CDAC training centres, DSSD, DESD, DAC, PGDSSD, PGDESD, PGDAC, DABC, PGDABC, VLSI, PGDITISS, PGDIVESD, PGDESD, PGDWiMC, placement statistics