Reputation: 11998
Hello Friend the output of the below program is so strange. I am not getting the reason.
#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
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
Reputation: 5766
xyz xyz :: operator +(xyz ob)
You don't use the ob object whatsoever.
Upvotes: 3
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
Reputation: 183988
In the operator+()
, the xyz temp;
is uninitialised and contains whatever garbage happened to be in that location.
Upvotes: 3