The Analogy: The Buttons on the Machine
A washing machine has a drum, a heater and a pump inside. You never touch them. What you touch is a small set of buttons: start, pause, select programme, plus a display that reports the time remaining.
Methods are those buttons. Each one is a function that already knows which machine it belongs to — press start on your machine and your drum turns, not your neighbour's. Some buttons do something and some only report something, and a well-built machine makes that difference obvious: the display cannot start a wash. In C++ that distinction is spelled const.
Syntax or Core Structure
A method can be defined inside the class, or declared inside and defined outside with the ClassName:: prefix.
#include <iostream>
#include <string>
class Thermostat {
double target{20.0};
double current{18.0};
int changes{0};
public:
// Defined inline -- short, so it lives in the class body.
double getTarget() const { return target; }
double getCurrent() const { return current; }
int changeCount() const { return changes; }
// Declared here, defined below.
bool setTarget(double celsius);
std::string status() const;
// A default argument: declared once, on the declaration.
void nudge(double by = 0.5);
};
bool Thermostat::setTarget(double celsius) { // note the ClassName::
if (celsius < 5.0 || celsius > 30.0) { return false; }
target = celsius;
++changes;
return true;
}
std::string Thermostat::status() const {
if (current < target - 0.5) { return "heating"; }
if (current > target + 0.5) { return "cooling"; }
return "steady";
}
void Thermostat::nudge(double by) { // no default repeated here
setTarget(target + by); // methods may call methods
}
int main() {
Thermostat t;
std::cout << t.status() << "\n"; // heating
t.setTarget(19.0);
t.nudge(); // uses the 0.5 default
std::cout << t.getTarget() << " " << t.changeCount() << "\n"; // 19.5 2
return 0;
}
Two rules from that listing: the default argument goes on the declaration only, and status() calling nothing that modifies state is what earns it const.
Technical Depth: The Hidden Parameter
Every method takes an invisible this
t.setTarget(19.0) compiles to something like Thermostat_setTarget(&t, 19.0). The object's address arrives as this, which is why one shared copy of the code can serve a million objects.
const on a method changes the type of that hidden pointer:
| Method | Type of this | Can modify members? |
|---|---|---|
void f(); | Thermostat* | Yes |
void f() const; | const Thermostat* | No |
static void f(); | no this at all | No members to modify |
That is the whole mechanism. A const method cannot modify members because this points to const.
const spreads, in both directions
A const object can only have const methods called on it, and a const method can only call other const methods:
void report(const Thermostat& t) {
std::cout << t.status(); // OK -- status() is const
// t.nudge(); // ERROR -- nudge() is not const
}
So one missing const deep in a class blocks every const& parameter above it. Mark query methods const as you write them; retrofitting is far more work.
const overloading
A method may be overloaded on its own const-ness, which is how containers return a modifiable element to non-const callers and a read-only one otherwise:
class Buffer {
std::vector<int> data;
public:
int& at(std::size_t i) { return data[i]; } // chosen for non-const
const int& at(std::size_t i) const { return data[i]; } // chosen for const
};
Buffer b;
b.at(0) = 5; // fine
const Buffer& cb = b;
// cb.at(0) = 5; // ERROR -- const overload returns const int&
static methods belong to the class, not an object
Mark a method static when it needs no object. It has no this, cannot touch non-static members, and is called through the class name:
class Temperature {
public:
static double toFahrenheit(double c) { return c * 9.0 / 5.0 + 32.0; }
static int activeSensors; // declaration only
};
int Temperature::activeSensors = 0; // definition, in a .cpp file
std::cout << Temperature::toFahrenheit(100.0); // 212 -- no object needed
Static data members are shared by every object, so a static counter is the standard way to track "how many of these exist".
mutable, for the caching exception
Occasionally a logically-const method needs to write to a member — a cached result, a hit counter. mutable exempts that one member from const:
class Report {
std::string body;
mutable std::size_t reads{0};
public:
const std::string& text() const {
++reads; // allowed: 'reads' is mutable
return body;
}
};
Use it sparingly and only for state the outside world cannot observe. A mutable member that changes visible behaviour is a lie in the signature.
Methods can be deleted or defaulted
class Handle {
public:
Handle() = default; // "generate the obvious one"
Handle(const Handle&) = delete; // "this one must not exist"
};
= delete produces a clear compiler error at the call site instead of a mysterious link failure, and works on ordinary methods too — a common trick for banning an unwanted overload.
Where the definition lives
| Placement | Effect |
|---|---|
| Inside the class body | Implicitly inline; fine for one-liners |
Outside, in the header, marked inline | Needed, or multiple translation units clash |
Outside, in a .cpp | Callers recompile only on interface changes |
A method defined inside the class body is implicitly inline, which is why headers full of one-line getters link cleanly. Move a body to a header outside the class and you must write inline yourself, or the linker reports a duplicate definition.
Real World Example: A Playlist
Queries, commands, a static factory and a static counter, all in one small class.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
class Playlist {
std::string name;
std::vector<std::string> tracks;
std::size_t position{0};
mutable std::size_t queryCount{0}; // diagnostics only
static std::size_t playlistsCreated; // shared by all objects
public:
explicit Playlist(std::string title) : name(std::move(title)) {
++playlistsCreated;
}
// --- Queries: all const, all counted.
std::size_t size() const { ++queryCount; return tracks.size(); }
bool empty() const { ++queryCount; return tracks.empty(); }
const std::string& title() const { ++queryCount; return name; }
std::string nowPlaying() const {
++queryCount;
if (tracks.empty()) { return "(nothing)"; }
return tracks[position];
}
std::size_t queries() const { return queryCount; }
// --- const overloading: writable for non-const callers, read-only otherwise.
std::string& at(std::size_t i) { return tracks.at(i); }
const std::string& at(std::size_t i) const { return tracks.at(i); }
// --- Commands: not const, and each returns whether it did anything.
Playlist& add(const std::string& track) {
tracks.push_back(track);
return *this; // chainable
}
bool remove(const std::string& track) {
const auto it = std::find(tracks.begin(), tracks.end(), track);
if (it == tracks.end()) { return false; }
tracks.erase(it);
if (position >= tracks.size()) { position = 0; } // keep the invariant
return true;
}
bool next() {
if (tracks.empty()) { return false; }
position = (position + 1) % tracks.size();
return true;
}
void shuffleToFront(const std::string& track, int /*unusedSeed*/ = 0) {
const auto it = std::find(tracks.begin(), tracks.end(), track);
if (it != tracks.end()) { std::rotate(tracks.begin(), it, it + 1); }
}
// --- Statics: no object required.
static std::size_t createdSoFar() { return playlistsCreated; }
static Playlist fromTracks(const std::string& title,
const std::vector<std::string>& items) {
Playlist p(title);
for (const std::string& t : items) { p.add(t); }
return p;
}
};
std::size_t Playlist::playlistsCreated = 0; // one definition, outside the class
// A const reference proves the query methods really are const.
void describe(const Playlist& p) {
std::cout << p.title() << ": " << p.size()
<< " tracks, playing " << p.nowPlaying() << "\n";
// p.next(); // would not compile
}
int main() {
Playlist morning("Morning");
morning.add("Blue in Green").add("So What").add("Flamenco Sketches");
Playlist evening = Playlist::fromTracks("Evening", {"Naima", "Alabama"});
describe(morning);
morning.next();
describe(morning);
morning.at(0) = "Blue In Green"; // non-const overload -> writable
const Playlist& frozen = morning;
std::cout << frozen.at(0) << "\n"; // const overload -> read-only
std::cout << morning.remove("So What") << "\n"; // 1
std::cout << morning.remove("Not There") << "\n"; // 0
std::cout << "Playlists created: " << Playlist::createdSoFar() << "\n"; // 2
std::cout << "Queries on morning: " << morning.queries() << "\n";
return 0;
}
The method set is split down the middle on purpose. size, empty, title and nowPlaying are const, which is precisely what lets describe take a const Playlist& and pay nothing for a copy — remove const from any one of them and describe stops compiling, which is the mechanism doing its job. queryCount is mutable so those const methods can still increment it; that is legitimate because the count is pure diagnostics and no caller's behaviour depends on it. at is overloaded on const-ness so morning.at(0) = ... works while frozen.at(0) is read-only, and both bodies call tracks.at rather than tracks[] so an out-of-range index throws instead of corrupting memory. The command methods return bool when they can fail — remove distinguishes "removed" from "wasn't there", and it repairs position afterwards, because erasing the last track while it is playing would otherwise leave position pointing past the end and make nowPlaying() undefined. add returns Playlist& so three tracks go in as one statement. Finally the two static members carry no this: createdSoFar() reports a count shared across every object, and fromTracks is a factory called as Playlist::fromTracks(...) with no existing playlist to hand. Note that playlistsCreated is declared in the class and defined once at file scope — omit that line and the code compiles but fails to link.
Common Mistakes
- Omitting
conston query methods. The class then cannot be used through aconst&, and the damage spreads to every caller. - Forgetting
ClassName::on an out-of-class definition. You have quietly written a free function, and the linker reports the method as undefined. - Repeating a default argument on the definition as well as the declaration. That is an error; put it on the declaration only.
- Accessing members from a
staticmethod. There is nothis, so there is no member to access. - Declaring a static data member but never defining it. It compiles; it does not link.
- Using
mutableto dodgeconston real state. If a caller can observe the change, the method was neverconst. - Defining a method outside the class in a header without
inline. Two translation units including it produce a duplicate-symbol error. - Breaking an invariant in one method that another relies on — erasing a track without fixing
positionis the classic version.
Best Practices
- Write
conston every method that does not modify the object, at the moment you write the method. - Separate queries from commands. A method should answer a question or change something, rarely both.
- Return a status from commands that can fail rather than failing silently.
- Keep one-line accessors in the class body and move anything substantial to a
.cpp. - Use
staticfor helpers that need no object, including factory functions. - Overload on
constwhen returning access to internals. - Restore every invariant before a method returns. If two methods disagree about the object's rules, one of them is a bug.
- Reach for
= deleteto ban an operation so the error appears at the call site.
Practice Exercises
- Const audit: Take the
Playlistclass, removeconstfromsize(), and try to compiledescribe. Paste the error into a comment, restore theconst, then write a second free function takingPlaylist&and callnext()from it to show the difference. - Static counter: Add a
static std::size_t tracksAddedEvertoPlaylist, increment it inadd, expose it through astaticmethod, and print it after building two playlists. Deliberately omit the out-of-class definition first and record the linker error. - Split the file: Move
Playlistintoplaylist.h(declarations plus one-line accessors) andplaylist.cpp(everything else), then compile withg++ main.cpp playlist.cpp -o app. Confirm that editing a method body in the.cppdoes not forcemain.cppto recompile.