THE POINTER this

You wrote the Volume() member of the CBox class in terms of the class member names in the definition of the class. Of course, every CBox object that you create contains these members, so there has to be a mechanism for the function to refer to the members of the particular object for which it is called.

When any member function executes, it always contains a hidden pointer with the name this, which points to the object used to call the function. Therefore when the m_Length member is accessed in the Volume() function, it’s actually referring to this->m_Length, which is the fully specified reference to the object member that is being used. The compiler takes care of adding this to the member names in the function.

You can use this explicitly within a member function if you need to — when you want to return a pointer to the current object, for example.

TRY IT OUT: Explicit Use of this
You can add a public function to the CBox class that compares the volumes of two CBox objects:
// Ex7_10.cpp
// Using the pointer this
#include <iostream>
using std::cout;
using std::endl;
 
class CBox                             // Class definition at global scope
{
  public:
    // Constructor definition
    explicit CBox(double lv = 1.0, double bv = 1.0, double hv = 1.0)
    {
      cout << endl << "Constructor called.";
      m_Length = lv;                   // Set values of
      m_Width = bv;                    // data members
      m_Height = hv;
    }
 
    // Function to calculate the volume of a box
    double Volume()
    {
      return m_Length*m_Width*m_Height;
    }
 
    // Function to compare two boxes ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.