#include <iostream>
usingnamespace std;
class A {
public:
A() : val(0) {}
int val;
int inc() { ++val; return val--; }
};
void Do(A *a) {
a-> val = a->inc();
}
int main() {
A a; /// this line refers to the Class A, hence making val=1 due to increment
Do(&a); // similarly, the function Do points at the class A, increasing the value of val to 2
cout << a.inc(); // this line increases val to 3, but decreases back to 2, then prints the output 2?
return 0;
}
The code "A::inc" will never print any number greater than 1 if A::val is never modified by anything other than the class. Once the value "val" is incremented using the pre-increment ++ operator, it's value at that point is 1. The post-decrement -- operator decreases the value to 0 but returns the value before it was decremented so this will return 1. Next time the inc function is called, the same process is repeated.
But going with the code in your main function. When "Do" is called, a.val will be set to 1 then when you call a.inc in main, the value of a.val is incremented to 2 and then decremented again. But since this is post-decrement, the value 2 is returned when the actual value of "a.val" is 1. To see that a.val is actually 1, below your last print statement, do cout << a.val << endl;