C++

C++ Getters and Setters Methods

One of the most widely used high-level languages is C++ which helps us with various operations and functions. Additionally, it offers several header files containing function declarations, and we may create classes in C++ codes. These features make our job more convenient. The core of the encapsulation principle is getters and setters. Getters make the private data reachable to the public. They might also somewhat alter the outcome that is returned. Setters make it possible to change a private variable. They are crucial because they might offer a confirmation before setting a value. Let’s apply these getters and setters in our C++ codes here.

Example 1:

We use the header files here to start our code since they are available for C++ development. We load the header files that are needed to run this code to begin. The “string” and “iostream” header files are included in this code. We subsequently include the “namespace std” after that.

Then, we create a “Table” class here and initialize a private variable named “count” with the “int” data type and store “15” in it as its value. After this, we insert the “public” keyword. Then, we create a function named “getCount()”. Its data type is “int”. This is the getter function here. We return this “count” in this function by utilizing the “return” keyword. Then, we invoke the following “main()” function where we create the object of the previous class with the “T_obj” name. Then, we call the “getCount()” function with this class object in the “cout” statement to get the value of count and print the result here.

Code 1:

 #include <string>

#include <iostream>

using namespace std;

class Table

{

private:
    int count = 15;
public:
    int getCount()
    {
        return count;
    }
};
int main()
{
    Table T_obj;


    cout << "We get the numbers of the table here which are: " << T_obj.getCount();

}

Output:

After the complete and successful compilation of this code, we get this desired output in which we can see that it gets the count value and display it here which is “15”. It is initialized inside the “private” class.

Example 2:

The “string” and “iostream” header files that are required for this code are included here. The “namespace std” is then included after that. Next, we make a new instance of the “MySquareClass” class, initialize a private variable called “squareSide” with the “int” data type, and set its value to “5”. The “public” keyword is then added, and a function called “getSquareSide()” with the “int” data type is developed.

Here, it’s referred to as the “getter” function. Inside this, we “return” the “squareSide”. So, when we call this function, it gives the “squareSide” value. After this, we place another function called “getSquarePerimeter()”. Here, we place the formula to find the perimeter so it returns the perimeter of the square after getting the value of the side of the square and multiplying it with “4”. We also need to find the area of the square. For this purpose, we develop one more function named “getSquareArea()” and compute the area of the square with the help of a formula that multiplies the sides of the square. It returns the area of the square whenever we call it and gets the value of the square side from the previous “squareSide” variable.

Now, we need to call these functions. We invoke the “main()” and then create an object of “MySquareClass” with the “sq_obj1” name. After this, we call and print all three functions with this class object separately.

Code 2:

#include <string>

#include <iostream>

using namespace std;

class MySquareClass

{

private:

    int squareSide = 5;
public:
    int getSquareSide()
    {
        return squareSide;
    }
    int getSquarePerimeter()
    {
        return squareSide * 4;
    }
    int getSquareArea()
    {
        return squareSide * squareSide;
    }
};
int main()
{
    MySquareClass sq_obj1;

    cout << "The Side of the square = " <<

    sq_obj1.getSquareSide() << endl;

    cout << "The Perimeter of the square = " <<

    sq_obj1.getSquarePerimeter() << endl;

    cout << "The Area of the square = " <<

    sq_obj1.getSquareArea() << endl;

}

Output:

First, it displays the side of the square, which is “5”, with the help of the “getSquareSide()” function. Then, it prints the perimeter of the square by utilizing the “getSquarePerimeter()” function and the area of the square using the “getSquareArea()” function.

Example 3:

Here, we have the “Driver” class in which we put the “private” keyword and declare the “driverSalary” as the private member with the “int” data type. After this, we have “public” where we create a “setDriverSalary” function and pass “int d_s” as the parameter of this function. This is the setter function here in this code. Now, we assign “d_s” to the “driverSalary” variable inside this function.

After this, we generate the getter function called “getDriverSalary” and return the driver’s salary. Now, after invoking the “main()”, we create an object of the class which is ”driverObj_1” and set the value of the driver salary by calling the “setDriverSalary()” function and passing “30000” as its parameter which is the salary of the driver. Then, we print this salary by calling the “getDriverSalary()” function.

Code 3:

#include <iostream>

using namespace std;

class Driver {

  private:
    int driverSalary;
  public:
    void setDriverSalary(int d_s) {
      driverSalary = d_s;
    }
    int getDriverSalary() {
      return driverSalary;
    }
};
int main() {
  Driver driverObj_1;
  driverObj_1.setDriverSalary(30000);


  cout << "The salary of the driver is: " << driverObj_1.getDriverSalary();

  return 0;

}

Output:

Here, we set the driver’s salary and get its salary after setting it and displaying it on the output screen.

Example 4:

The “Person” class is generated in this code where we declare three “private” variables named “P_name”, “P_city”, and “P_language” with the “string” data type. After this, we make a “public” constructor. Here, we place the “setPersonName()” function and put “string newName” as the parameter of the function. After this, we assign this “newName” to the “P_name” variable. Then, we create the “getPersonCity()” function and return “P_city”. In the same manner, we create another function with the “setPersonCity()”name. Then, we pass “string city” as the parameter.

The “city” variable is now assigned to the “P_city” variable. The ”getPersonLanguage()” is the next function here which also returns the “P_language”. Moreover, we also define the “setPersonLanguage()” function and pass it the “lang” string as its parameter. The “lang” is then assigned to the “P_language” variable. After this, we have two more functions, “lives()” and “speak()”, where we utilize the “cout()” statement.

After executing the “main()” method, we now generate an object of the class called “p_obj1”. Here, we set the person name by running the “setPersonName()” function and providing the person’s name which is “Samuel” as its parameter. After this, we set the city of the person by calling the “setPersonCity()” function and passing “London” as the parameter. Then, we also set the person’s language using the “setPersonLanguage()” function and passing “English” as its parameter. Now, we call the “lives()” and “speak()” functions separately with the object of the “p_obj1” class.

Code 4:

#include <iostream>

using namespace std;

class Person

{

    private :
        string P_name;
        string P_city;
        string P_language;
       
    public :
        void setPersonName(string newName) {
            P_name = newName;
        }

        string getPersonCity() {
            return P_city;
        }

        void setPersonCity(string city) {
            P_city = city;
        }

        string getPersonLanguage() {
            return P_language;
        }

        void setPersonLanguage(string lang) {
            P_language = lang;
        }
   
        void lives()
        {


            cout << P_name << " lives in " << P_city << endl;

        }

        void speak()
        {


            cout << P_name << " speaks " << P_language << endl;

        }

};

int main() {

    Person p_obj1;
    p_obj1.setPersonName("Samuel");
    p_obj1.setPersonCity("London");
    p_obj1.setPersonLanguage("English");
       
    p_obj1.lives();
    p_obj1.speak();
   
    return 0;


}

Output:

Here, it shows all the values that we set in our code as a result. We get this result by calling the function which we created.

Conclusion

We explored the getters and setters in C++ programming in this guide. We explained that the “getter” and “setter” methods offer a better abstraction and encapsulation of the class’s internal operations. In addition, we explored that the data validity functionality to safeguard the data member is retained, allowing the class to change its code without impacting the external code. We did this with the C++ codes by utilizing these getters and setters.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.