Rasmi Ranjan Nayak
Rasmi Ranjan Nayak

Reputation: 11998

Why Operator overloading behaves so strange

Hello Friend the output of the below program is so strange. I am not getting the reason.enter image description here

#include <iostream>
using namespace std;

class xyz
{
    private:
    int ab, cd;
    public:
    xyz()
    {

    }
    xyz(int i, int j)
    {
        ab = i;
        cd = j;

    }
    xyz operator+(xyz);
    void show()
    {
        cout << ab << " ....  "<< cd;
    }

};
xyz xyz :: operator +(xyz ob)
{
    xyz temp;
    temp.ab = ab + temp.ab;
    temp.cd = cd + temp.cd;
    return temp;
}

int main()
{
   // xyz xy, yz;

   xyz xy(2, 3);
   xyz yz(4, 5);
    xy = xy + yz;

    xy.show();
    return 0;
}

Upvotes: 1

Views: 147

Answers (4)

Yeshvanthni
Yeshvanthni

Reputation: 207

The temp object was just created initialized with random values and codeis just adding to it.

xyz xyz :: operator +(xyz ob)
{
xyz temp;
temp.ab = ab + ob.ab;
temp.cd = cd + ob.cd;
return temp;
}

output:

6..8

Upvotes: 1

DumbCoder
DumbCoder

Reputation: 5766

xyz xyz :: operator +(xyz ob)

You don't use the ob object whatsoever.

Upvotes: 3

Henrik
Henrik

Reputation: 23324

Copy&paste error?

This

temp.ab = ab + temp.ab;
temp.cd = cd + temp.cd; 

should be

temp.ab = ab + ob.ab;
temp.cd = cd + ob.cd; 

Upvotes: 8

Daniel Fischer
Daniel Fischer

Reputation: 183988

In the operator+(), the xyz temp; is uninitialised and contains whatever garbage happened to be in that location.

Upvotes: 3

Related Questions