views:

332

answers:

4

Possible Duplicate:
Why use getters and setters?

while writing class in c++, usually methods are made public, and attributes are made private/public, so that these attributes cant be accessed from outside.

But when we use getters/setters, these attributes can be easily accessed,modified from outside. So, why to make them private/protected in first hand; if we are going to use setters/getters later on to modify.

I have been confused with this question. Nice explanation would be helpful.

Thanks.

+1  A: 
  1. You can add some logic into setters/getters in future.
  2. Sometimes getters/setters can operate with abstract things... like count in dynamic arrays
Adelf
A: 

As Adelf stated, adding logic. Also the option to only write or only read a value.

PoweRoy
A: 

You can limit access to attributes, i.e. if you will write getter without setter, attribute will be read-only. Also some useful logic can be added i.e. for setter - verification of border terms of value. Also you can add getter for attribute the value of which is calculated at a call

zabulus
+1  A: 

You should never supply getters & setters by default, only if the use case of the class requires them. This will almost never be true for setters, and only occasionally for getters.

Consider the std::string class. Does it make sense to give access to its private data members? No, only one of them is exposed (the current length) via the size() getter, and none via setters.

anon