Solved

Operator Overloading in C++

Posted on 2004-03-22
11
421 Views
Last Modified: 2013-11-25
Its very urgent to me. Can u please write for me a small easy program how to overload '+' and '++' operator in C++? I will be really grateful if u can do it soon..Thanx
regards - LovingStar
0
Comment
Question by:loving_star
  • 6
  • 2
11 Comments
 
LVL 1

Expert Comment

by:fxnut
Comment Utility
It depends on exactly what you want to do with it, i.e. what you want the operators to operate on. Here's an example for a 2D vector class...


class Vector2D
{


};
0
 
LVL 1

Accepted Solution

by:
fxnut earned 43 total points
Comment Utility
Oops, pressed submit by accident..


class Vector2
{
   float x,y;

   Vector2& operator +=(const Vector2& rhs)
   {
      x+=rhs.x;
      y+=rhs.y;
      return *this;
   }

   const Vector2& operator + (const Vector2& rhs) const
   {
      return Vector2(x+rhs.x,y+rhs.y);
   }

   //Not much use in a vector class, but you could do this...
   
   //This is the prefix operator
   Vector2& operator ++()
   {
      x++;
      y++;
      return *this;
   }

   //And this is the postfix operator
   Vector2 operator ++(int)
   {
      Vector2 temp = *this;
      x++;
      y++;
      return temp;
   }

};
0
 
LVL 9

Assisted Solution

by:_ys_
_ys_ earned 41 total points
Comment Utility
Quick correction on operator+
Should not return a reference

const Vector2 operator + (const Vector2& rhs) const;

Also operators are typically non-privately scoped.
0
 
LVL 1

Expert Comment

by:fxnut
Comment Utility
Yep, thanks! I was typing that in (instead of copying and pasting) and added the return by reference in by mistake. And you also noticed that I forgot to add in the public definition - something I keep on forgetting to do in my own code! :-)

So the start should look like this...

class Vector2
{
public:
   float x,y;

etc...
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 37

Assisted Solution

by:Harisha M G
Harisha M G earned 41 total points
Comment Utility
1. Consider a program for complex numbers

struct complex
{
  int re,im;
};

complex operator + (complex c1, complex c2)
{
  complex temp;
  temp.re = c1.re + c2.re;
  temp.im = c1.im + c2.im;
  return temp;
}

complex operator ++(complex c1)
{
  complex temp;
  temp.re = c1.re + 1;
  temp.im = c1.im;
  return temp;
}


void main()
{
  complex a, b, c;
  a.re = 1;
  a.im = 4;
  b.re = 3;
  b.im = 2;
 
  c = a + b;
  if(c.im>0)
    cout<<c.re<<" + i"<<c.im;
  if(c.im<0)
    cout<<c.re<<" - i"<<c.im;
  if(c.im==0)
    cout<<c.re;
  c++;
  if(c.im>0)
    cout<<c.re<<" + i"<<c.im;
  if(c.im<0)
    cout<<c.re<<" - i"<<c.im;
  if(c.im==0)
    cout<<c.re;

}

0
 
LVL 1

Expert Comment

by:fxnut
Comment Utility
I could be wrong on this mgh (feel free to correct me!), but I don't think your ++ operator is correct.

For your complex class, the ++ operator overload definitions should be..

   Complex& operator++();       // Prefix increment operator.
   Complex operator++(int);     // Postfix increment operator

Or alternatively, you could define them at file scope (i.e. not in the class)

   friend Complex& operator++( Complex& )      // Prefix increment
   friend Complex& operator++( Complex&, int ) // Postfix increment

The other problem is that your ++ operator passes in a Complex type by value, and it doesn't modify "this"s values at all, so in actual fact your ++ operator does nothing to the instance that is operated on, all it does is return a new incremented copy of the value passed in. In my mind, it's a bad idea to define a ++ operator that has non-standard behaviour. (And that's assuming that your compiler will let you define such an overload which some might not)


0
 
LVL 9

Expert Comment

by:_ys_
Comment Utility
In mgh_mgharish's absence I'll comment.

The code is very C-esque - absence of encapsulation - and as such is fully functional. Again, the lack of reference parameters is again traditional C.

I agree with fxnut on c++; This is definitely postfix and the extra [unused] int parameter would be required. Perhaps the compiler has optomised this (given that the return value is not required) and transformed it into ++c;. Unusual for user defined types.

Final note - I wouldn't re-invent the wheel for complex classes; STL already has one.
0
 
LVL 1

Expert Comment

by:fxnut
Comment Utility
Are you gonna close this question?
0
 
LVL 1

Expert Comment

by:fxnut
Comment Utility
Since mgh_mgharish's answer was prettyflawed, and _ys_ was only providing feedback on my answer, I would have thought accepting my answer with an assist from _ys_ would seem the fairest. But I'm happy to settle for a split between myself and _ys_.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
Displaying an arrayList in a listView using the default adapter is rarely the best solution. To get full control of your display data, and to be able to refresh it after editing, requires the use of a custom adapter.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now