Core C++

Lesson 40 : The "this" Pointer

In this C++ video tutorial, we explain what the "this" pointer is and how it is used. When an object calls a member function, the calling object is passed into the function with a pointer argument. That pointer is available internally to the function as the "this." The keyword "this" is reserved in C++ for exactly that purpose.

#include <iostream>

enum EMetal {keSilver, keGold, kePlatinum, keTitanium, keTungsten};

class CWeddingRing
{
public:
    CWeddingRing() : miSize(14), meMaterial(keGold) {}
    int GetSize() {
        return this->miSize;
    }
    EMetal GetMaterial() {
        return this->meMaterial;
    }
    void SetSize(int iSize) {
        this->miSize = iSize;
    }
    void SetMaterial(EMetal eMaterial) {
        this->meMaterial = eMaterial;
    }
private:
    int miSize;
    EMetal meMaterial;
};

int main() {
    using namespace std;

    CWeddingRing qMyRing;
    cout << "Ring Size = " << qMyRing.GetSize() << endl;
    cout << "Ring Material = " << qMyRing.GetMaterial() << endl;

    qMyRing.SetSize(10);
    qMyRing.SetMaterial(keTitanium);
    cout << "Ring Size = " << qMyRing.GetSize() << endl;
    cout << "Ring Material = " << qMyRing.GetMaterial() << endl;

    return 0;
}

The program above has a simple class to represent wedding rings. Above the wedding ring class is an enumeration, which describes the various metals that can be used to fashion the ring: silver, gold, platinum, titanium, and tungsten. Inside of the wedding ring class, we have two data member that describe the size of the ring and material of which it is composed.

Our main function, instantiates a wedding ring object, and calls the Get() functions to get the size and metal for the ring. These are the default values 14 and gold. Below that, we set the size and material for the ring to 10 and titanium and output the values again.

The member functions all use the "this" pointer to access the data members. In our prior examples, we have omitted the explicit usage of "this" and wrote just the data member names. The "this" pointer is hidden in the code, but it is a constant pointer to the calling object, which in this case is "qMyRing." All of this is done to make code more readable. However, we should always be aware of the "this" and think of our member functions as ordinary functions, which take "this" as an additional argument. In the coming C++ lessons, we will see examples where the "this" pointer must be accessed.

 

© 2007–2024 XoaX.net LLC. All rights reserved.