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:
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: