The this pointer used in overloading unary operator

I am having problems with the overloading operator functions return value the *this value why does it not return the this value without the indirection wouldnt the this value return the address of the object? Im confused with the derenferencing value *this being used instead.

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
class Digit
{
private:
    int m_nDigit;
public:
    Digit(int nDigit=0)
    {
        m_nDigit = nDigit;
    }
 
    Digit& operator++();
    Digit& operator--();
 
    int GetDigit() const { return m_nDigit; }
};
 
Digit& Digit::operator++()
{
    // If our number is already at 9, wrap around to 0
    if (m_nDigit == 9)
        m_nDigit = 0;
    // otherwise just increment to next number
    else
        ++m_nDigit;
 
    return *this;
}
 
Digit& Digit::operator--()
{
    // If our number is already at 0, wrap around to 9
    if (m_nDigit == 0)
        m_nDigit = 9;
    // otherwise just decrement to next number
    else
        --m_nDigit;
 
    return *this;
}
this is a pointer. The operator should return a reference so that is why the pointer has to be dereferenced before it's returned from the function.
In a non-static member function of Digit:

this is a pointer - a pointer to Digit (pointer to optionally cv-qualified Digit)

*this is a reference - a reference to Digit (reference to optionally cv-qualified Digit).

When we dereference (use the unary * operator on) a pointer to T, we get a reference to T.
The overloaded operators return the reference obtained by derefencing this - they return *this.
Topic archived. No new replies allowed.