I don't understand this class member

Okay this whole code that I'm about to list is about using postfix and prefix operators to increment one class object to another by using the "this" pointer. The thing that I don't understand about this code is from lines: 21-23. They are trying to set up the default constructor but they put the "itsVal" outside the brackets of the constructor and they put a zero right next to it, which I'm assuming set the "itsVal" to zero. But why I don't get is how are they allowed to set the private member to zero, by just putting a value right next to it in parenthesis? Another question I need to know is through lines:31-35. On line 33, what is it actually saying? I know an object of the class is being declared and their adding the "this" pointer in the parameters, but is the
this
pointer pointing to the memory address of the constructor? Any help would be grateful


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
1:     // Listing 10.12
2:     // Returning the dereferenced this pointer
3:
4:     typedef unsigned short  USHORT;
5:     #include <iostream.h>
6:
7:     class Counter
8:     {
9:     public:
10:       Counter();
11:       ~Counter(){}
12:       USHORT GetItsVal()const { return itsVal; }
13:       void SetItsVal(USHORT x) {itsVal = x; }
14:       const Counter& operator++ ();      // prefix
15:       const Counter operator++ (int); // postfix
16:
17:    private:
18:       USHORT itsVal;
19:    };
20:
21:    Counter::Counter():
22:    itsVal(0)
23:    {}
24:
25:    const Counter& Counter::operator++()
26:    {
27:       ++itsVal;
28:       return *this;
29:    }
30:
31:    const Counter Counter::operator++(int)
32:    {
33:       Counter temp(*this);
34:       ++itsVal;
35:       return temp;
36:    }
37:
38:    int main()
39:    {
40:       Counter i;
41:       cout << "The value of i is " << i.GetItsVal() << endl;
42:       i++;
43:       cout << "The value of i is " << i.GetItsVal() << endl;
44:       ++i;
45:       cout << "The value of i is " << i.GetItsVal() << endl;
46:       Counter a = ++i;
47:       cout << "The value of a: " << a.GetItsVal();
48:       cout << " and i: " << i.GetItsVal() << endl;
49:       a = i++;
50:       cout << "The value of a: " << a.GetItsVal();
51:       cout << " and i: " << i.GetItsVal() << endl;
52:     return 0;
53: }
Last edited on
for your first question read up on initialiser lists, for the second question - this points to the object that the member function is being called for. Line 33 is just constructing a Counter object using the copy constructor with the object pointed to by this as a parameter
Last edited on
thanks for telling me
Topic archived. No new replies allowed.