This Pointer

Introduction

  • Member functions have an extra implicit parameter that is a pointer to an object of the class type. This implicit parameter is named this
  • Member functions may not define the this parameter; the compiler does so implicitly.

When to Use the this Pointer

  • this pointer must be used when we need to refer to the object as a whole rather than to a member of the object.
  • The most common case where we must use this is in functions that return a reference to the object on which they were invoked.

Example
The return type of these functions is Screen&, which indicates that the member function returns a reference to an object of its own class type. Each of these functions returns the object on which it was invoked.

class Screen 
{
     public:
          // interface member functions
          Screen& move(index r, index c);
          Screen& set(char);
          Screen& set(index, index, char);
          // other members as before
};
 
Screen& Screen::set(char c)
     {
         contents[cursor] = c;
         return *this;
     }
     Screen& Screen::move(index r, index c)
     {
         index row = r * width; // row location
         cursor = row + c;
         return *this;
     }

Example: Allow a series of functions to be chained together.

iclass Calc
{
        private:
                int m_nValue;
        public: 
                Calc() { m_nValue = 0; }
                void Add(int nValue) { m_nValue += nValue; }
                void Sub(int nValue) { m_nValue -= nValue; }
                void Mult(int nValue) { m_nValue *= nValue; }
                int GetValue() { return m_nValue; }
};
 
int main()
{
        Calc cCalc;
        cCalc.Add(5);
        cCalc.Sub(3);
        cCalc.Mult(4);
}

However, if each fucntion returns *this, we can chain the calls together.

class Calc
{
        private:
                int m_nValue;
        public: 
                Calc() { m_nValue = 0; }
                void Add(int nValue) { m_nValue += nValue; }
                void Sub(int nValue) { m_nValue -= nValue; }
                void Mult(int nValue) { m_nValue *= nValue; }
                int GetValue() { return m_nValue; }
};
 
int main()
{
        Calc cCalc;
        cCalc.Add(5);
        cCalc.Sub(3);
        cCalc.Mult(4);
}
int main()
{
        Calc cCalc;
        cCalc.Add(5).Sub(3).Mult(4);
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.