Using Setters in C++

Written by Hamza on. Posted in C++

After talking about constructors and destructors, next up in my series on object oriented programming is how to use setters. Setters are functions that are used to change the values of data members inside classes. They are very important, as they are the only route through which we can change the value of our data members after an object is instantiated.

Setters are sometimes called mutator methods. Don’t get confused if you come across this term.

A setter usually has the following format:

void set_value ( const data_type data_member);

It is a good programming practice to pass a const data type into the setter function, as whatever value passes into this function will always be constant.

To see how a setters works, let us use the same fraction class I used to explain constructors, i.e, the fraction class. Here, there are two data members, the numerator and the denominator, and thus we write two setters for each of the two data members.

<p>class fraction</p>
<p>.  private:</p>
<p>.   int numerator;</p>
<p>.   int denominator;</p>
<p>.  public:</p>
<p>.   fraction()  //default constructor</p>
<p>.   {</p>
<p>.    denominator=1;</p>
<p>.   }</p>
<p>.  void set_denominator(const int x)</p>
<p>.  denominator=x;</p>
<p>.  void set_numerator(const int x)</p>
<p>.  numerator=x;</p>
<p>int main()</p>
<p>{ <a style="text-decoration :none ; font :inherit ; box-shadow :none" href=""><font style="color: #444"></font></a></p>
<p>.  fraction obj;</p>
<p>.  obj.set_numerator(3);</p>
<p>.  obj.set_denominator(4);</p>


As you can see, the parameter is a const int for both cases. In this case, we have instantiated an object call ‘obj’ but now we want it to hold the value ‘3/4’. As the data members are private, we cannot access the numerator and denominator directly (e.g like obj.numerator=3, obj.denominator=4) . This is why we need a public data member, which we call a setter, to change these data members.

The setters themselves are easy to write. They simple put the data members for that object equal to the parameter being passed. Now, we can change both the numerator and denominator through our setters.

As I have mentioned in my introduction to classes in object oriented programming, data members are made private so that they cannot be accessed by the outer world and just be accessed through your program.

Next in the series is another concept closely related to setters, which we call getters. Check regularly for the next update!

Tags: , , ,