Possible Duplicate:
Why use getters and setters?
Can anyone tell me what is the use of getter/setter method?
class X
{
int i;
public:
void set(int ii){ i = ii;}
int get(){ return i;}
};
Now, The question goes like this:
Q1. Why did you declare the variable 'i' as private and not as public?
My answer: Bcoz, data is always sensitive and by declaring it private you'll prevent it from being exposed to the outside world.
To counter my reasoning, the interviewer said..."Then, why did you provide a public getter/setter method?? Since, these member functions are public, so still variable 'i' is exposed to outside world and anyone can change the value of 'i'."
Further, The interviewer suggested me to re-write my previous class as follows:
class X
{
public:
int i;
};
The benefit would be: you can modify the value of 'i' more quickly...since there is no function calling required this time.
The interviewer's reasoning seems good though....because by making private variable 'i' and public get/set method, you cant protect your data. So, Why do we write get()/set() method ?
The purpose is that you can always change the setter and the getter method with more sophisticated logic, if needed (for example validity check). If you don't use getter/setter you must write them and then change the code everywhere you change the field, which can lead to errors which will be very hard to find.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With