Private and public.

Can anyone explain why we must declare public and private in struct?

example coding

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  class box {
	public:
		void open();
		void removeItem();
		void storeItem(int x);
		void close();
		void displayItem();
		box();
	private:
		int item;
		bool boxOpen;
		bool empty;
};
You aren't required to declare public or private sections in a struct or class. You only need to declare public, private, or protected access sections if you want something other than the default access mode.

Encapsulation.

You put money into your wallet. You go to shop. You decide to buy something, because you have enough money to pay for it. Alas! The money is not in your wallet. How is that possible?

Your wallet is an object. The wallet has internal state (how much money it has). The wallet has public interface (your hand) that puts or takes money to/from the wallet. As long that is the only way to change the internal state, you can trust to have some amount of money.

Leaving the the internal state public is like making it possible for every bypasser to touch the money in your wallet without you knowing it.


An object can be complex. Even a simple change in the apparent state of the object may require additional book-keeping. Users of the object do not need, nor should, know about the bookkeeping. Keep the state private. Access the state via public members only.


You could look at GotW #100, even though it talks about more than just public/private. http://herbsutter.com/gotw/_100/
Topic archived. No new replies allowed.