question about encapsulation

so far I've been taught to always put member data/functions in either public: protected: or private:, but in a few code tutorials i've seen things like integers declared 'globally' or what-have-you inside a class. Why do people do this and not just declare it under public?

for example:
1
2
3
4
5
6
7
class example
{
int a;
public:
protected:
private:
};
Last edited on
closed account (jwC5fSEw)
Classes default to private, so anything declared "globally" in a class is actually private.
Yeap! When you declare a member variable in a class, the default access modifier is private. In your example integer a is a private member variable of the class example. In a struct however the default access modifier is public. So, here:

1
2
3
4
5
6
7
struct my_example
{
     int a;
     public:
     protected:
     private:
};


integer a is a public member variable of the struct my_example
Last edited on
Why do people do this and not just declare it under public?

my quick answer is to protect the class's members..
let say for example your class have an int variable and you expect it only to be set to 1, 4 and 7..

if that int member is public then this would be valid myclass.intmember = 99; which might cause a problem..

but if it is private, what you can do is to make a function to set the the value of that intmember like myclass.setIntValue( 99 ); which can do an extra checking if we are passing a value that we expect (1, 4, 7) and deny it if it is not valid..

hope that helps..
Topic archived. No new replies allowed.