Classes question

Is my understanding of the output correct? I am certain that I'm doing this

wrong. My explanation is written as notes on the code below.

can someone clarify what is going on to get the output of 2?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>
    using namespace 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;
Last edited on
oh I understand. I was desperately trying to get things together.
thanks for the clarification.
Try adding some extra cout statements, see whether that helps to clarify:
1
2
3
4
5
6
7
8
9
10
int main()
{
    A a;
    cout << "one:   " << a.val << endl;
    Do(&a);
    cout << "two:   " << a.val << endl;
    cout << a.inc()   << endl;
    cout << "three: " << a.val << endl;
    return 0;
}

Output:
one:   0
two:   1
2
three: 1
Your misunderstanding is here:
 
       A a;  /// this line refers to the Class A, hence making val=1 due to increment 

This line calls the constructor which sets a.val to 0. It does NOT call inc().
Topic archived. No new replies allowed.