Menu
C++ Tutorials

C++

This Pointer



Tutorials > C++ > This Pointer

View Full Source

Introduction

Sometimes when working with a class, you may want to use a pointer to the current class. This is useful for passing a pointer to the object to some method or function. The this keyword is used to give you a pointer to the current class. This is also useful for making your code easier to read.

Contents of main.cpp :


#include <iostream>
#include <stdlib.h>

using namespace std;

A Player class is created as we have seen in the past.

class Player
{

public :

	Player() : health(100), mana(50) {}

	// Getters
	int getHealth() const { return health; }
	int getMana() const { return mana; }

	// Setters
	void setHealth(int h) { health = h; }
	void setMana(int m) { mana = m; }

	void castBerserker();

private :

	int health;
	int mana;
};

Below is an example of how the this pointer can be used. As you can see, the -> operator needs to be used as you are dealing with a pointer. Any method or variable can then be accessed. Even though you do not need the this pointer in this scenario, it makes your code easier to understand as you know the method or function comes from the current class.

void Player::castBerserker()
{
	this->setMana(mana - 10);
	this->setHealth(getHealth() - 10);
}

The code below simply uses the method above to show that all is working correctly.

int main()
{
	Player grant;
	grant.castBerserker();

	cout << "Grant : "
		<< grant.getHealth() << " "
		<< grant.getMana() << endl;

	system("pause");

	return 0;
}

You should now understand what the this pointer is. You may still be wondering exactly why it is useful besides making your code simpler to read. The answer will become more apparent in future tutorials such as the Operator Overloading tutorial.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 50 - Getters And Setters Tutorial 52 - Copy Constructors >

Back to Top


All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer

Links