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; } }; |
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); |
No comments:
Post a Comment