Hello i have 2 similar small programs using the overloading of << and ++ operator but i don't understand why they give me different results. It would be really helpful if someone can enlighten me on this.
All i've done is change the order of variables after the cout statment.
#include <iostream>
usingnamespace std;
class Int {
public:
int v;
Int(int a) { v = a; }
Int &operator++(int x) {
v+=2;
return *this;
}
};
ostream &operator <<(ostream &o, Int &a) {
return o << a.v;
}
int main() {
Int i = 0;
cout << i++ << i.v;
return 0;
}
#include <iostream>
usingnamespace std;
class Int {
public:
int v;
Int(int a) { v = a; }
Int &operator++(int x) {
v+=2;
return *this;
}
};
ostream &operator <<(ostream &o, Int &a) {
return o << a.v;
}
int main() {
Int i = 0;
cout << i.v << i++;
return 0;
}
Thank you for the answer. Now, i understand that they should not be put together and we have an undefined behaviour but i got this on a test and i needed to give a precise answer. So is there any way to predict the result ?
#include <iostream>
usingnamespace std;
class Int {
public:
int v;
Int(int a) { v = a; }
Int &operator++(int x) {
v+=2; // as you see here when you use the suffix(after i) ++ it adds 2 to the the value of v
return *this;
}
};
ostream &operator <<(ostream &o, Int &a) {
return o << a.v;
}
int main() {
Int i = 0;
cout << i.v << " "; // prints 0
i++; // adds 2
cout << i.v << endl; // prints 2
return 0;
}
#include <iostream>
usingnamespace std;
class Int {
public:
int v;
Int(int a) { v = a; }
Int &operator++(int x) {
v+=1; // now I have changed this to add one so it will add one
return *this;
}
};
ostream &operator <<(ostream &o, Int &a) {
return o << a.v;
}
int main() {
Int i = 0;
cout << i.v << " ";
i++; // add 1 not 2 as the previous code
cout << i.v << endl;
return 0;
}
As you can see your code adds 2 and than I have changed it to add 1 in the second one.
You can predict it if you look at line 8(v+=2;), what ever number is in the place of 2 is the number you will be adding onto the original number