Access Specifiers

When declaring access specifiers for members of classes, why would you want them to be anything other than public? The tutorial says that this might give unexpected results, but what are these results and why do they arise?
It is there so you do not have other functions/classes modifying random data without using your functions. It also makes it easier to restrict data values since you only have to restrict the function that changes the value, rather then every place it is edited.
Last edited on
Why would you want to restrict these though? Couldn't you just not refer to the variables at any point in the program where you don't want to edit them?
Let's say you have a variable HP that isn't supposed to be over 100 or under 0, and it is in a class Player:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Player {
public:
void changehp(int);
int showhp();
private:
int hp;
}; //Whoops, forgot this semicolon >.>

C::changehp(int a) {
     this->hp += a;
     if(this->hp > 100) this->hp = 100;
     else if(this->hp < 0) this->hp = 0;
}

Player::showhp() {
     return this->hp;
}

int main() {
     Player hero;
     int b = 0;
     cout << "Edit the HP by: ";
     cin >> b;
     hero.changehp(b)
     cout <<"Valid value: "<< b;
     cout << endl << "hero.hp is now: " << hero.showhp();
     System("pause");
     return 0;
}


This would make it so when you change the HP value, it would automatically check and make sure it is not over 100 or under 0, and correct it if necessary, instead of you having to create lots of extra code to check every time.
Last edited on
The philosophy behind this is for multi-developer projects; or maintenance programming done by another developer after the project has been completed.

By not using public and using encapsulation it's easier to wrap validation around what values you permit into your member variables.

I personally use protected. I do this because a lot of my work has complex inheritance structures and I want my variables to inherited. If you declare them private they will not be inherited.

Hope that helps.
Thanks. I think I'll have to play with it a bit.
Last edited on
Topic archived. No new replies allowed.