title: what is the use of getter and setter method?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/1568091/why-use-getters-and-setters">Why use getters and setters?</a>  </p>
  </blockquote>
  
  
  
  <blockquote>
    <p>Can anyone tell me what is the use of getter/setter method?</p>
  </blockquote>
  
  <h2>In one of the interview someone asked me to write a simple class...so, I wrote the class as shown below:</h2>
  
  <pre><code>class X
  {
      int i;
  public:
  
      void set(int ii){ i = ii;}
      int get(){ return i;}
  };
  </code></pre>
  
  <p>Now, The question goes like this:</p>
  
  <blockquote>
    <blockquote>
      <p>Q1. Why did you declare the variable 'i' as private and not as public?</p>
      
      <p>My answer: 
      Bcoz, data is always sensitive and by declaring it private you'll prevent it from being exposed to the outside world.</p>
    </blockquote>
    
    <p>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'."</p>
    
    <p>Further, 
    The interviewer suggested me to re-write my previous class as follows:</p>
  </blockquote>
  
  <pre><code>class X
  {
  public:
  
      int i;
  };
  </code></pre>
  
  <p>The benefit would be: you can modify the value of 'i' more quickly...since there is no function calling required this time.</p>
  
  <p>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 ?</p>