Menu
C++ Tutorials

C++

Access Specifiers



Tutorials > C++ > Access Specifiers

View Full Source

What are Access Specifiers?

Access Specifiers allow you to define how methods and variables of a class are accessed. You have already come across one the public specifier. There is also a private and a protected access specifier. The protected specifier will be dealt with in a future tutorial.

Public VS Private

Placing variables and methods in the public section allows them to be accessed from anywhere.
Placing variables and methods in the private section allows them only to be accessed within the class ie. within another method, constructor, etc. in the class. These items cannot be accessed outside of the class. This will become more clear below.

Contents of main.cpp :


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

using namespace std;

The public section is shown below. The constructor and destructor must always appear in the public section. These items can be accessed from anywhere.

class Player
{
public :

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

	void takeTurn();

	int health;
	int mana;

The private section is given below. The attack method below can only be accessed from within the class.

private :

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

The body of the takeTurn method is shown below. Notice that it calls the attack method. This is allowed as the takeTurn method is a method of the class.

void Player::takeTurn()
{
	attack();
	cout << "Player defends" << endl;
}

The code below calls the takeTurn method. Notice the commented out piece of code. If we try to call the attack method, we will receive an error as it is a private method and the main method is not a part of the class.

int main()
{
	Player grant;
	//grant.attack(); // Error
	grant.takeTurn();

	system("pause");

	return 0;
}

You are now able to specify whether you want certain methods and variables to be private or public. This is useful as you may not want certain variables or methods to be dealt with directly. This is even more useful if you are creating a library that other people are using as they will have less to worry about.

You may want a decreaseHealth public method which decreases the person's health and updates other user info. The health variable would be private otherwise you may decrease the health variable without updating the other info.

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

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

< Tutorial 48 - Destructors Tutorial 50 - Getters And Setters >

Back to Top


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

Read the Disclaimer

Links