Using getters in C++

Written by Hamza on. Posted in C++

Now that we have had a look at setters in C++, let us move on the the use and concept of getters. Getters, or accessors, are often found alongside setters in a class, and are extremely vital in object oriented programming.

Getters are functions that are used to get the values of the private data members. They are simply used to return the data member and are thus simple to write and easy to use. The syntax of a getter is usually:

</p>
<p><Data_type_of_data_member> get_Value()</p>
<p>{</p>
<p style="text-align: justify;">return <data_member>;</p>
<p>}</p>
<p>

To further clarify, let us use the same example we used when explaining setters,i.e, the fraction class. I have reproduced the code below and added two getters for the numerator and denominator data types.

</p>
<p>class fraction</p>
<p>{</p>
<p>.  private:</p>
<p>.   int numerator;</p>
<p>.   int denominator;</p>
<p>.  public:</p>
<p>.   fraction()  //default constructor</p>
<p>.   <a style="outline :none;box-shadow :none;text-decoration:none;cursor :default;color :inherit;font :inherit" href="http://skintagsremoving.com/anal-skin-tags-causes-and-best-removal-options-for-genital-tags/">click</a> {</p>
<p>.    denominator=1;</p>
<p>.   }</p>
<p>.  void set_denominator(const int x)</p>
<p>{</p>
<p>.  denominator=x;</p>
<p>}</p>
<p>.  void set_numerator(const int x)</p>
<p>{</p>
<p>.  numerator=x;</p>
<p>}</p>
<p>.  void get_numerator()</p>
<p>{</p>
<p>.  return numerator;</p>
<p>}</p>
<p>.  void get_denominator()</p>
<p>{</p>
<p>.  return denominator;</p>
<p>}</p>
<p>&nbsp;</p>
<p>};</p>
<p>int main()</p>
<p>{</p>
<p>.  fraction obj;</p>
<p>.  obj.set_numerator(3);</p>
<p>.  obj.set_denominator(4);</p>
<p>.   int x=obj.get_numerator();</p>
<p>.   int y=obj.get_denominator();</p>
<p>}</p>
<p>

 

As you can see, the implementation of the getters is very easy, as the function just contains the return statement for the data types that are required. Now, if we need to check that the values that we have set for the numerator and denominator are 3 and 4 respectively, then we can use the getters to check. The values of x and y will be 3 and 4 respectively.

Often we can use the word ‘const’ after writing the function to signify that the getter is a constant function, but this is not necessary rather just a good programming practice.

Now, it should be clear how we can use the private data members within our class through an object using public member functions such as setters and getters. We shall now move on to other concepts such as the ‘this’ pointer, concepts vital for effective usage of classes of C++. Keep visiting Coding Mash to see the latest updates. Don’t forget to subscribe, and join our growing community at Facebook, Google+ and Twitter!

Tags: , , ,