Why don't we use single member function for set and get the data member value instead of separate accessor/getter and mutator/setter function?

85 views Asked by At

I just have a really quick question as I am trying to grasp C++ class concept. Why don't we use a single member function for set and get the data member value instead of separate accessor/getter and mutator/setter function?

Example Shown Below:

class Student
{
    private: 
            int rollno;
    public:     
            int setGetRollNo(int rn) {
                rollno = rn;
                return rollno;
            }
        
};


int main()
{   
    Student s1;
    cout << s1.setGetRollNo(123);

    
}

It works the same as when we try to do that we sperate the accessor and mutator function.

1

There are 1 answers

1
Ranoiaetep On

There is nothing wrong with having a function that can both access and mutate a member. However, the way you are doing is definitely incorrect. With the code you have right now, you cannot get the current value without setting it to a new value first.

Instead, a better way to do this is to do this is to return the reference of the member object:

class Student
{
    int rollno;
public:
    int& rollno_ref()
    {
        return rollno;
    }
};

Now you can use the same function both access and mutate the member like:

std::cout << student.rollno_ref();       // access
student.rollno_ref() = 10;               // mutate

One thing to note is that this function really doesn't do much beside exposing a reference to an existing member. To add more functionalities to it, you should look up proxy class.


Another thing to note is this function will not work on const Student. To make it work, you should supply its const version as well.