My pre increment is working fine but not the post increment

Viewed 87

I have implemented the following class and tried to overload the pre and post-increment operator along with the extraction '>>' operator. The programs runs fine till 'cout << ++num1;' but prints junk values for the last line 'cout << num1++;'. I cannot figure out that why is it working fine for pre-increment but not for post-increment.

class ComplexNumber
{
private:
    float real;
    float img;
public:
    ComplexNumber();
    ComplexNumber(float, float);
    ComplexNumber(const ComplexNumber& cn);
    friend istream& operator>>(istream& in, ComplexNumber& cn);
    // cin >> complexNo1 >> complexNo2;
    friend ostream& operator<<(ostream& out, const ComplexNumber& cn);
    //cout << complexNo1 << complexNo2; //3+4i, 5+10i
    ComplexNumber& operator++(int);
    //post increment operator. complexNo++;
    ComplexNumber& operator++();
    //pre increment operator. ++complexNo;
ComplexNumber& ComplexNumber::operator++(int x) // postincrement
{
    ComplexNumber c = *this;
    ++(*this);
    return c;
}
ComplexNumber& ComplexNumber::operator++() // preincrement
{
    real++;
    img++;
    return *this;
}
int main()
{
    ComplexNumber num1;//,num2,num3
    cin >> num1;
    cout << "-------------------------------------------" << endl;
    cout << "Complex Number is : ";
    cout << num1;
    cout << ++num1;
    cout << num1++;
}
1 Answers

Your post-increment operator is returning reference to local object, which will be destroyed when function ends, the returned reference is always dangling and dereference on it leads to UB.

Post-increment operator is supposed to return-by-value, e.g.

ComplexNumber ComplexNumber::operator++(int x) // postincrement
{
    ComplexNumber c = *this;
    ++(*this);
    return c;
}
Related