Main Content

When do I use the this keyword in C++?

Archive - Originally posted on "The Horse's Mouth" - 2015-10-29 07:14:50 - Graham Ellis

Question: When do I use the this keyword in C++?

Answer: When I expliciy need (or want) to refer to a member variable or object within the current object.

Example:

   class Transport{
      public:
         Transport(int);
         int nSeats;
      };


I could define my constructor as follows:
   Transport::Transport(int nS) { nSeats = nS; }
But that means that I've had to come up with a second variable name for "number of seats" and may lead to confusion in future code work where I have to remember which particular word I used where. The Eskimos may have 450 different words for "snow", but a program is far more followable and maintanable if we have just one. But writing
   Transport::Transport(int nSeats) { nSeats = nSeats; }
isn't going to work, because the parameter nSeats masks the object member, and the assignment just overwrites a variable with itself, and the object member does not get set. The solution is "this" to explicitly refer to the object member:
   Transport::Transport(int nSeats) { this->nSeats = nSeats; }

From yesterday's C++ - sample code [here] showing this, vector, iand examples of factory, inherrited constructor, file input, and a tokeniser.