Access functions are member functions which are used to get or modify private data members of a class. There are two types of access functions: getter and setter. As name implies getter is something that gets the private data member value. And setter modifies the value of the private data member.

For example,

#include <iostream>
 
class Point
{
 
private:
    int m_x{};
    int m_y{};
 
public:
    void print() const
    {
        std::cout << m_x << ", " << m_y << "\n";
    }
 
    int x() const
    {
        return m_x;
    }
 
    int y() const
    {
        return m_y;
    }
 
    void setX(int x)
    {
        m_x = x;
    }
 
    void setY(int y)
    {
        m_y = y;
    }
};
 
int main(int argc, char const *argv[])
{
    Point p{};
    p.print();
 
    p.setX(4);
    p.setY(6);
    
    p.print();
    return 0;
}

For setters, we usually prefix them with set so make the intent clear that they would be modifying the data members. Thus, they are not const member functions.

For getters, we can prefix them with get but here I used the data member name directly. That’s why I have also prefixed data members name with m_.

Why do we need to make data members private if we require to create access functions to access and modify them? We could just make them public? Well, there where we need to understand the benefits-of-encapsulation.

References

  1. https://www.learncpp.com/cpp-tutorial/access-functions/