pre/post increment overloads

Hello, I am having trouble figuring out why my overloads for the pre/post ++ increment are not working. They either return random numbers, or the program crashes. Should this code work? Or is it my + overload? I think the + overload works though, as I have tested it many, many times, with many, many different numbers. Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* postfix*/
MyInt MyInt::operator++(int ignoreMe)
{                  
        MyInt temp;

        temp = *this;         

        *this = *this + 1;             

        return temp;
}              

/* prefix */
MyInt MyInt::operator++( )
{
        *this = *this + 1;

        return *this;              
}

That code looks fine. I'm betting the problem is with your + operator.



I would make these changes though:

1
2
3
4
5
6
7
MyInt MyInt::operator++(int ignoreMe)
{                  
//        MyInt temp;    // don't do this
//        temp = *this;
        MyInt temp(*this);  // do this instead
// or this:
        MyInt temp = *this;


When you break it up into two lines, the object will be default constructed, then reassigned. That's two separate operations. This is potentially slower than a single copy construct.

I would also have the prefix operator return by const reference:

1
2
3
// MyInt MyInt::operator++( )  // boo

const MyInt& MyInt::operator++()  // yay 


As this potentially avoids a needless object copy.




Just to clarify -- these changes will not solve your problem, they're just optimization suggestions.
Last edited on
Alright, not what I wanted to hear lol. Thanks for the tips anyways though.
what is the implementation of your operator+() ?
Topic archived. No new replies allowed.