Menu
C++ Tutorials

C++

Getters And Setters



Tutorials > C++ > Getters And Setters

View Full Source

Introduction

Getters and Setters allow you to effectively protect your data. This is a technique used greatly when creating classes. For each variable, a get method will return its value and a set method will set the value.

You may ask why you shouldn't just edit the value directly. The reason for this is twofold. Firstly, if you decide that some action should be taken every time you change the value of a particular variable, you only need to edit the set method instead of looking for every place you change the variable. Another reason is that a person using your code can look for all methods starting with get or set instead of looking for specific variables that they need to remember.

Contents of main.cpp :


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

using namespace std;

class Player
{

The getters and setters are usually public and the variables are made private.

public :

	void attack()
	{ cout << "Player Attacks" << endl; }

Getters usually start off with the letters "get". You may have noticed the const keyword after the method below. This states that the method will not change any value within the class. This is useful as it forces you not to modify any value of the class. Getters usually never modify values of the class and so you can therefore place a const after the method signature.

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

Setters are similar and they start with the "set" characters. The functions take a parameter which specifies the new value. Notice that the const keyword isn't used as you are changing a value within the class.

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

The private data variables are given below.

private :

	int health;
	int mana;
};

An example of using a setter and a getter is given below.

int main()
{
	Player grant;

	grant.setHealth(30);

	cout << grant.getHealth() << endl;

	system("pause");

	return 0;
}

Getters and setters are a common technique used in object orientated programming. It is good practice to use these getters and setters instead of changing the variables directly.

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

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

< Tutorial 49 - Access Specifiers Tutorial 51 - This Pointer >

Back to Top


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

Read the Disclaimer

Links