Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Getter and Setter In C++

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Hello Ninja. Do you want controlled access to private class data members, or Do you want to improve your code security and maintainability?

Then you are at the right place, and it will cover you with the getter and setter in c++ that helps to keep your private members private while allowing you to set and get value from the members in controlled access or manner. 

Whether a beginner or experienced in c++, this article will help you understand the fundamentals of getter and setter in c++.

getter and setter in c++

Getter in C++

Getter is a member function that helps to get the value of a private data member. It allows access to private members to get read by external code but not allowing them to modify it directly. 
The naming convention for getter generally uses the prefix “get” followed by the name of the data member with the first letter capitalised. For example, the getter member function name for the private data member, named “marks”, would be “getMarks”.

Syntax 

Here is an example syntax for getter functions that fetch the value of private data member called “marks.”

class Ninja{
private:
    int marks;
   String name=” Pro Ninja ”;
public:
    int getMarks() {
        return marks;
    }
};

 

Here, getMarks function returning a value, marks, which is a private data.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Setter in C++

Setter is a member function that helps to set the value of a private data member. It allows controlled access to private members and can provide a constraint on the input or validation before a value is set.
The naming convention for a setter generally uses the prefix “set” followed by the name of the data member with the first letter capitalised. For example, the setter member function name for the private data member, named “marks”, would be “setMarks”.

Syntax

Here is an example syntax for setter functions that sets the value of private data member called “marks.”

class Ninja_Student {
private:
    int marks;
public:
    void setMarks(int newMarks) {
        marks = newMarks;
    }
};

 

The setMarks function takes input as newMarks to set a value in the private data member named marks. 

Why classes need getter and setter?

Classes need getter and setter methods to control the access and modifications  of its private data members by incorporating additional checks and logic. It helps in maintaining the data validity. Getter and setter methods also improve code maintainability.

Examples to understand Getter and Setter In C++

In this section, we are going to implement the getter and setter in C++. 

Example 1

In this example, we will set values using the setter function and add validation to the input.

#include <iostream>
#include <string>
using namespace std;
class Student {
    private:
        string name;
        string course;
        int marks;
    public:
        void setName(string newName) {
            name = newName;
        }
         void setCourse(string newCourse) {
            course = newCourse;
        }
        // adding validation 
        void setMarks(int newMarks){
     if (newMarks < 0) {
     throw "Marks cannot be negative !!";
}
     //Set the value of the new marks
     marks = newMarks;
       }
        void Student_Info() {
            cout << "Name: " << name << endl;
            cout << "Course: " << course << endl;
            cout << "Marks: " << marks << endl;
        }
};
int main() {
    Student obj;
    obj.setName("Ninja Coder");
    obj.setMarks(99);
    obj.setCourse("DSA in C++");
    obj.Student_Info();
    return 0;
}

 

Output:

Output for setting value

In the above C++ code, we have demonstrated encapsulation using the setter methods and validated the private member before updating its value, making the code secure.

Example 2

In this example, we will get private data values using the getter function from the Student Class.

#include <iostream>
#include <string>
using namespace std;
class Student {
    private:
        string name;
        string course;
    public:
        void setName(string newName) {
            name = newName;
        }
        void setCourse(string newCourse) {
            course = newCourse;
        }
        string getName() {
            return name;
        }
        string getCourse() {
            return course;
        }
};
int main() {
    Student obj ;
    obj.setName("Dhruv Rawat");
    obj.setCourse("Information Technology");
    cout << "Name: " << obj.getName() << endl;
    cout << "Course: " << obj.getCourse() << endl;
    return 0;
}

 

Output:

Output to get private data

In the above code, we first set the value to the private data member using the setter method as done in the previous example and then use getter methods to retrieve the value of the private data member, which are name and course. This code shows the concept of encapsulation too.

Applications of Getter and Setter In C++

Let's now see some essential applications of the Getter and Setter In C++.

  • Data Validate: while setting up the data value, we can check if it is valid or not using the setter method which ensures data security and prevents error.
     
  • Access Control of Data: Restriction to certain data members could be provided using getter and setter methods. This ensures security as only authorised code can change and update the data.
     
  • Encapsulation: The technique to bind the code and data together and prevent direct access to the data from outside the class requires getter and setter methods. Encapsulation protects the data from unwanted changes and ensures data integrity.
     
  • Abstraction: getter and setter methods provide a level of abstraction. It hides the class implementation details or internal workings. This allows for easier code maintenance and changes without affecting the rest of the code.

Frequently Asked Questions

Why should we use getter and setter in c++?

We should use these methods to protect our data, ensuring data validation and having control access to the private data member. Getter and setter methods also improve code maintainability.

Can the getter and setter methods in c++ be overridden?

Yes, in C++, derived classes can override getter and setter functions to provide different implementations that are specific to the derived class. This is useful when the base class does not meet the specific requirements of the derived class

What is the advantage of using getters and setters in c++ instead of making member variables public?

getter and setter methods provide better encapsulation and abstraction of the class’s internal workings. It also allows the class to modify its code without affecting the external code along with the data validation feature to protect the data member.

Can the getter method return a reference rather than a value?

Yes, the getter method can return a reference instead of the value which is useful when we want to modify or access the data member directly without creating a copy of the object.

Conclusion

This article has explained the basics of getter and setter in C++. It has also given examples of getter and setter methods implemented in code and discussed their applications.
At last, we see some of the FAQs regarding getter and setter methods.

Hope you enjoyed reading this article, here are some more related articles:

To learn more about Data Structures and Algorithms, you can enroll in our DSA in C++ Course.

We hope you found this blog helpful in expanding your knowledge. Please give this article a thumbs up if you enjoyed it. 

"Have fun coding!"

Topics covered
1.
Introduction
2.
Getter in C++
2.1.
Syntax 
3.
Setter in C++
3.1.
Syntax
4.
Why classes need getter and setter?
5.
Examples to understand Getter and Setter In C++
5.1.
Example 1
5.2.
Example 2
6.
Applications of Getter and Setter In C++
7.
Frequently Asked Questions
7.1.
Why should we use getter and setter in c++?
7.2.
Can the getter and setter methods in c++ be overridden?
7.3.
What is the advantage of using getters and setters in c++ instead of making member variables public?
7.4.
Can the getter method return a reference rather than a value?
8.
Conclusion