| 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 |
inline (compiler may substitute the call with the function body directly, avoiding call overhead)const (like getBalance() const) to guarantee they don't modify the object — lets them be called on const objects too#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;
}
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 trapclass 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.
const:
printBalance() above require getBalance() to be const?