Possible Duplicate:
Why use getters and setters?
Can anyone tell me what is the use of getter/setter method?
In one of the interview someone asked me to write a simple class...so, I wrote the class as shown below:
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 ?