Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the use of getter and setter method? [duplicate]

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 ?

like image 707
Jatin Avatar asked Feb 20 '23 09:02

Jatin


1 Answers

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.

like image 72
Dani Avatar answered Feb 21 '23 22:02

Dani