Type Purpose Example
Accessor ("getter") Reads a data member's value without modifying it double getBalance() const { return balance; }
Mutator ("setter") Modifies a data member's value in a controlled way void deposit(double amt) { balance += amt; }
Utility/helper Performs a computation using the object's data double area() { return length * width; }
Constructor/Destructor Special member functions for initialization/cleanup see the Objects and Classes page

Full worked example — all member function types together

#include <iostream>
using namespace std;

class Student
{
private:
    string name;
    float marks;

public:
    Student(string n, float m) : name(n), marks(m) {}   // constructor

    // Accessor / getter
    float getMarks() const { return marks; }

    // Mutator / setter
    void setMarks(float m) { if (m >= 0 && m <= 100) marks = m; }   // controlled -- validates input

    // Utility / helper -- computes something from the object's own data
    string getGrade() const
    {
        if (marks >= 90) return "A";
        else if (marks >= 80) return "B";
        else return "C";
    }

    // inline by virtue of being defined inside the class body
    void show() const { cout << name << ": " << marks << " (" << getGrade() << ")" << endl; }
};

int main()
{
    Student s("Ali", 85);
    s.show();               // Ali: 85 (B)
    s.setMarks(95);
    s.show();               // Ali: 95 (A)
    return 0;
}

Why mutators validate instead of just assigning

Compare setMarks() above to directly exposing marks as public. The mutator can reject invalid input (e.g., marks = -10 or 150), something a public field can never do — this is the practical reason accessors/mutators exist instead of just making everything public.

const member functions — a common exam trap

class Wallet
{
    double balance;
public:
    double getBalance() const { return balance; }   // promises not to modify the object
    // double getBalance() const { balance += 1; return balance; }  -- ERROR: can't modify in a const function
};

void printBalance(const Wallet& w)
{
    cout << w.getBalance();   // only works because getBalance() is marked const
}

Without const on getBalance(), this function couldn't be called on a const Wallet& parameter at all — a frequent source of confusing compiler errors for students.

Important MCQs

  1. A member function that only reads a data member's value without changing it is called a(n):
  2. A member function marked const:
  3. A function defined entirely inside the class body is implicitly treated as:
  4. Why use a mutator ("setter") instead of a public data member directly?

Self-Test Questions

  1. What's the practical benefit of a mutator function over a public data member?
  2. Why does printBalance() above require getBalance() to be const?
  3. What does "implicitly inline" mean for a function defined inside a class body?

📌 Sample & Repeated FPSC Questions (2016–2026)