Using the this pointer

The methods in a class have a special calling convention, which in Visual C++ is called __thiscall. The reason is that every method in a class has a hidden parameter called this, which is a pointer of the class type to the current instance:

    class cartesian_vector     {     public:         double x;         double y;         // other methods         double get_magnitude()         {              return std::sqrt((this->x * this->x) + (this->y * this->y));         }     };

Here, the get_magnitude method returns the length of the cartesian_vector object. The members of the object are accessed through the -> operator. As shown previously, the members of the class can be accessed without the this pointer, but it does make it explicit that the items are members of the class.

You could ...

Get Beginning C++ Programming 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.