-5

I've got this code, but I do not understand the output...

class Complex
{
   private:
       float re;
       float im;
   public:
       Complex(float r = 0.0, float i = 0.0) : re(r), im(i){};
       void Print(){cout << "Re=" << re <<",Im=" << im << endl;}
       Complex operator++(); //prefiksna
       Complex operator++(int); //postfiksna
};

 Complex Complex ::operator++()
{
    //First, re and im are incremented
    //then a local object is created.
     return Complex( ++re, ++im);
 }

Complex Complex ::operator++(int k)
{
   //First a local object is created
   //Then re and im are incremented. WHY is this ??????
    return Complex( re++, im++);
}

int main()
  {
   Complex c1(1.0,2.0), c2;
   cout << "c1="; c1.Print();
   c2 = c1++;
   cout << "c2="; c2.Print();
   cout << "c1="; c1.Print();

   c2 = ++c1;
   cout << "c2="; c2.Print();
   cout << "c1="; c1.Print();
   return 0;
}

The output is :

1. c1=Re=1,Im=2

2. c2=Re=1,Im=2

3. c1=Re=2,Im=3

4. c2=Re=3,Im=4

5. c1=Re=3,Im=4

Can someone explain these outputs? (1. is trivial I think I understand 3. and 5. , just want to make sure...)I am very interested in the difference in 2. and 4. mainly, that is unclear why it is the way it is.. There is also a question within the code in comments (WHY is this ??????)

  • 2
    It really is a bad idea to define increment/decrement operators for complex numbers, or to use this as an example of what operators overloading is for. And that is before we even get to the implementation. – void_ptr Dec 22 '15 at 19:27

1 Answers1

2

Your question should be closed as a duplicate of everyone else who ever asked "what do pre increment and post increment mean" but your instructor should learn something before trying to teach it:

Complex& Complex ::operator++()
{
    //First, re and im are incremented
    ++re; ++im;
    //then there is no need to create a local object.
     return *this;
 }

The way you tested it, an optimizer can elide the extra work implied by the instructor's bad code. But if you are supposed to learn how to write pre and post increment operators (which is a step beyond learning what they mean) then correctly learn how and why pre should be more efficient than post.

JSF
  • 5,281
  • 1
  • 13
  • 20