LOGBOOK

HELP

Quiz Entry - updated: 2026.07.06

What does const after a method declaration mean?

A trailing const promises the method won't modify the object's state — so it can also be called on const objects.

class Vehicle {
public:
    int getNWheels() const;   // won't modify the object
    void setNWheels(int n);   // may modify the object
private:
    int _nwheels;
};

int Vehicle::getNWheels() const {
    return _nwheels;          // OK: just reading
    // _nwheels = 5;          // ERROR: can't modify in a const method
}

Why use it?

  • Documents intent (getter vs setter) and lets the compiler catch accidental modifications
  • Enables calling the method on const objects:
const Vehicle v(4);
v.getNWheels();   // OK: const method
v.setNWheels(6);  // ERROR: can't call a non-const method on a const object

Tip: "const-correctness" — marking everything that can be const — is a hallmark of good C++; it documents guarantees and lets the compiler enforce them.

Go deeper:

From Quiz: REVE1 / C++ Programming | Updated: Jul 06, 2026