C++: The this keyword

This entry is part 35 of 61 in the series C++

The this keyword points to the object for which the member function is called.  I have always used it to explicitly point to the data members of the class.

Consider the following function where a variable name occurs in another part of the program.

If you remove the this pointer from the program below, it will still work correctly.

#include <iostream>
#include <string>

using namespace std;

class Rock

	string name;
	string track;

	int Display();

	Rock(string, string);  //This is the constructor
	~Rock();  //This is the destructor


int Rock::Display()

	cout << "This is " << this->name << " Singing " << track;
	cout << endl;

	return 0;

Rock::Rock(string name, string track)
	this->name = name;
	this->track = track;

	cout << "This is Rod Stewart Signing Off";
	cout << endl;

int main()

	string name= "Rod Stewart";
	string track = "I was only Joking";

	Rock rockstar(name, track); // instance declaration


	return 0;


Series Navigation<< C++: Properties of an object
C++: Access controls >>