Cpp - class this Pointer

Introduction

this pointer points to the individual object in which the function is running.

The following code shows how to use this pointer.

Demo

#include <iostream> 
 
class Rectangle //from  ww w . j a  va2  s . co  m
{ 
public: 
    Rectangle(); 
    ~Rectangle(); 
    void SetLength(int length) { this->itsLength = length; } 
    int GetLength() const { return this->itsLength; } 
    void SetWidth(int width) { itsWidth = width; } 
    int GetWidth() const { return itsWidth; } 
 
private: 
    int itsLength; 
    int itsWidth; 
}; 
 
Rectangle::Rectangle() 
{ 
    itsWidth = 5; 
    itsLength = 10; 
} 
 
Rectangle::~Rectangle() 
{} 
 
int main() 
{ 
    Rectangle theRect; 
    std::cout << "theRect is " << theRect.GetLength()  
                   << " feet long." << std::endl; 
    std::cout << "theRect is " << theRect.GetWidth()  
                   << " feet wide." << std::endl; 
 
    theRect.SetLength(20); 
    theRect.SetWidth(10); 
    std::cout << "theRect is " << theRect.GetLength() 
                   << " feet long." << std::endl; 
    std::cout << "theRect is " << theRect.GetWidth() 
                   << " feet wide." << std::endl; 
   
    return 0; 
}

Result

The SetLength() and GetLength() accessor functions explicitly use the this pointer to access the member variables of the Rectangle object.