Friday, August 2, 2013

LearnCpp 8.7 — The hidden “this” pointer

http://www.learncpp.com/cpp-tutorial/87-the-hidden-this-pointer/

Most of the time, you never need to explicitly reference the “this” pointer. However, there are a few occasions where it can be useful:

1) If you have a constructor (or member function) that has a parameter of the same name as a member variable, you can disambiguate them by using “this”:
1
2
3
4
5
6
7
8
9
10
11
class Something
{
private:
    int nData;
 
public:
    Something(int nData)
    {
        this->nData = nData;
    }
};
Note that our constructor is taking a parameter of the same name as a member variable. In this case, “nData” refers to the parameter, and “this->nData” refers to the member variable. Although this is acceptable coding practice, we find using the “m_” prefix on all member variable names provides a better solution by preventing duplicate names altogether!

2) Occasionally it can be useful to have a function return the object it was working with. Returning *this will return a reference to the object that was implicitly passed to the function by C++.


One use for this feature is that it allows a series of functions to be “chained” together, so that the output of one function becomes the input of another function! The following is somewhat more advanced and can be considered optional material at this point.


class Calc
{
private:
    int m_nValue;
 
public:
    Calc() { m_nValue = 0; }
 
    Calc& Add(int nValue) { m_nValue += nValue; return *this; }
    Calc& Sub(int nValue) { m_nValue -= nValue; return *this; }
    Calc& Mult(int nValue) { m_nValue *= nValue; return *this; }
 
    int GetValue() { return m_nValue; }
};


Note that Add(), Sub() and Mult() are now returning *this, which is a reference to the class itself. Consequently, this allows us to do the following:
1
2
Calc cCalc;
cCalc.Add(5).Sub(3).Mult(4);
The important point to take away from this lesson is that the “this” pointer is a hidden parameter of any member function. Most of the time, you will not need to access it directly. It’s worth noting that “this” is a const pointer — you can change the value of the object it points to, but you can not make it point to something else!


No comments:

Post a Comment