Programming & Scripting Tutorials

C++: The "this" Keyword





The this keyword is commonly used so that local class variables can be used instead of the default used function variables.
Using the keyword makes the function refer to the wider scope (for example the local class variable instead of the class function's variable). For example this would display 21:

#include <iostream>

using namespace std;

class ClassOne{
public:
	int fish;
	void PrintFish(int fish){
		cout << fish << endl;
	}
};

int main(){
	ClassOne FishObject;
	FishObject.PrintFish(21);

	system("PAUSE");
	return 0;
}


Instead of it coming up with an error like it would have if it was referring to the class variable it simply displayed 21, this is because by default the function refers to the function variables.
However if we use the this keyword we can change the way it works:


#include <iostream>

using namespace std;

class ClassOne{
public:
	int fish;
	void PrintFish(int fish){
		this->fish = 12;
		cout << fish << endl;
		cout << this->fish << endl;
	}
};

int main(){
	ClassOne FishObject;
	FishObject.PrintFish(21);

	system("PAUSE");
	return 0;
}


You can see that this outputs 21 and then 12.


This C++ tutorial was written by


Back to C++

Advertisement: