Designing member functions in C++
What you will learn on this page
Section titled “What you will learn on this page”- What a member function’s signature tells its caller, and how to decide each part of it.
- The difference between commands and queries, and why queries are
const. - How to pass each parameter: by value, by
const&, as astd::string_vieworstd::span, or by value to keep it. - Which return type reports each kind of outcome: a value, a
bool, an outcomeenum,std::optional, a pointer, or an exception. - When to add
[[nodiscard]],noexcept, andexplicit, and when a function should bestaticor not a member at all. - How to keep the public interface small enough that callers cannot get around the class’s rules.
What a signature says
Section titled “What a signature says”A caller reads the declaration, not the body. The declaration must answer five questions:
| Part of the signature | The caller’s question | Example from the gym |
|---|---|---|
| name | what does it do? | check_in, allows_visit |
| parameters and their types | what must I give it, and does it keep it? | MemberId id, Day today; std::string name |
| return type | what do I get back, and how do I learn it failed? | CheckIn, const Member* |
const |
does it change the object? | int people_inside() const |
[[nodiscard]], noexcept |
must I use the result? can it throw? | [[nodiscard]] bool allows_visit(Day) const noexcept |
If a caller has to read the body or a comment to answer one of these, the signature can be better.
A first draft, and the final version
Section titled “A first draft, and the final version”Here is the kind of interface many people write first for the gym. Each member function matches a need from the previous lesson, but the signatures were chosen without thinking:
class Gym
first draft
Data members
int capacity;std::map<int, Member> members;std::set<int> inside;
Member functions
Gym(int capacity);void addMember(int id, const std::string& name, int lastDay, int visits);bool checkIn(int id, int day);void checkOut(int id);void setSuspended(int id, bool suspended);Member& getMember(int id);std::map<int, Member>& getMembers();int getPeopleInside();
And the final version, from the example:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Every answer the front desk can get from check_in: one way in, and one// value for each reason a person is turned away, so the desk can show it.enum class CheckIn { admitted, unknown_member, already_inside, gym_full, membership_expired, no_visits_left, suspended,};
// The text the desk shows for a result, such as "refused: the gym is full".// A free function, not a member, because an enum cannot have member// functions. std::string_view is a read-only view of text; here it points at// fixed text built into the program, so it never dangles.[[nodiscard]] std::string_view to_string(CheckIn result) noexcept;
// The front desk's view of the gym: who is enrolled and who is inside.// Owns the rules about the building (capacity, one entry per person) and// asks each Member about the rules that belong to the member.class Gym {public: // `capacity` is the most people allowed inside at once. // Throws std::invalid_argument unless capacity > 0. `explicit` stops a // plain int from silently turning into a Gym, for example when 50 is // passed to a function that expects a Gym. explicit Gym(int capacity);
// Takes the member by value and keeps it (a sink parameter). // Returns false, and changes nothing, if the ID is already enrolled. bool enrol(Member member);
// Lets the member in, or says why not. The gym's own rules (known // member, not already inside, room left) are checked first; then the // member is told to admit itself. A refusal changes nothing. // [[nodiscard]]: ignoring the answer would always be a mistake. [[nodiscard]] CheckIn check_in(MemberId id, Day today); // Returns false if the member was not inside. bool check_out(MemberId id);
// Staff actions. Each returns false if the ID is not enrolled. bool suspend(MemberId id); bool reinstate(MemberId id); bool renew(MemberId id, Membership membership);
[[nodiscard]] int people_inside() const noexcept { return static_cast<int>(inside_.size()); } // nullptr if not enrolled. Read-only, so callers cannot admit a member // without going through check_in(). The pointer stays valid until this // gym is destroyed, assigned to, or moved from. [[nodiscard]] const Member* find(MemberId id) const;
private: // Like find, but returns a pointer that can change the member, for the // gym's own commands. Private, so only Gym can change a member. Member* find_enrolled(MemberId id);
int capacity_; // The gym owns every Member by value, sorted by ID. std::map can sort by // MemberId because MemberId has a defaulted operator<=>, which gives `<`. std::map<MemberId, Member> members_; // owned, by ID // A set holds each ID at most once, which is the "one entry per person" // rule; its size is the number of people inside. std::set<MemberId> inside_; // IDs of members now inside};Every difference has a reason, and the rest of the page explains them:
| First draft | Final | Why |
|---|---|---|
Gym(int capacity) |
explicit Gym(int capacity), throws if ≤ 0 |
no silent conversion from int; no gym with a bad capacity |
addMember(int, const std::string&, int, int) |
bool enrol(Member member) |
four parameters, three of them int, are easy to swap; the result says whether the ID was taken |
bool checkIn(int id, int day) |
[[nodiscard]] CheckIn check_in(MemberId id, Day today) |
false cannot say why; the desk must show a reason |
void checkOut(int id) |
bool check_out(MemberId id) |
the caller can tell a member who was not inside |
setSuspended(int id, bool suspended) |
suspend(MemberId), reinstate(MemberId) |
setSuspended(4, false) is unclear at the call site |
Member& getMember(int id) |
const Member* find(MemberId id) const |
no reference to a member that does not exist; no way to change a member without the gym’s rules |
std::map<int, Member>& getMembers() |
(removed) | it handed the gym’s data to anyone |
int getPeopleInside() |
[[nodiscard]] int people_inside() const noexcept |
a query: const, cannot fail |
Commands and queries
Section titled “Commands and queries”A query reports something about the object and changes nothing. A command changes the object. Keeping the two apart is called command-query separation.
| Kind | Gym examples | Signature rules |
|---|---|---|
| query | people_inside, find, allows_visit, visits_between |
const; return the answer; usually [[nodiscard]]; often noexcept |
| command | check_in, enrol, suspend, use_visit, admit |
not const; return an outcome if the caller needs one, otherwise void |
Why it matters:
- Asking twice gives the same answer. A caller, a test, or a debugger can
call a query as often as it likes. If
allows_visitused a visit, calling it twice would use two. constobjects get only queries. Code that receives aconst Gym&(a report, say) can read but cannot check anyone in. The compiler enforces it.
A command may return its outcome. check_in changes the gym and returns
why it did or did not. Strictly, that bends the rule; it is a common,
deliberate relaxation, and the standard library does the same
(std::set::insert inserts and returns whether it did). The trouble the rule
mainly guards against is a query with a hidden change, not a command that
reports what happened.
| Kind | How to name it | Gym examples | Avoid |
|---|---|---|---|
| command | a verb from the domain, saying what happens | check_in, suspend, renew, enrol |
process, handle, update, doCheckIn |
| query returning a value | the thing returned | people_inside, last_day, name |
get_ on everything, calculate_ when nothing is calculated |
query returning bool |
a question that reads as yes or no | is_suspended, allows_visit |
suspended (adjective or verb?), check_suspended |
| factory | what it creates | unlimited_until, visit_pass |
create, make with a flag parameter |
Name a function from the caller’s side. admit(today) says what the gym
wants. validate_and_update(today) says how the body works, and has to be
renamed when the body changes. A name with “and” in it often hides two
functions.
Parameters: how to pass each one
Section titled “Parameters: how to pass each one”The question for each parameter is: does the function only read it, change the caller’s object, or keep it? Then use this table:
| What the function does with it | How to pass it | Gym example |
|---|---|---|
| reads it, and it is small (a few words) | by value: int, MemberId, Day, an enum, small values |
check_in(MemberId id, Day today), renew(MemberId, Membership) |
| reads it, and it is large or not copyable | const T& |
check_out(const MemberAccount& member, ...) in the MOD-08 exercise |
| reads text without keeping it | std::string_view |
EmailAddress::parse(std::string_view) in MOD-02 |
| reads a sequence without keeping it | std::span<const T> |
(see “When a requirement changes”) |
| keeps it (stores it in a data member) | by value, then std::move it in |
Member(MemberId, std::string name, Membership), enrol(Member member) |
| changes the caller’s object | T&, and say so in the name |
charge_late_return(Member& member, ...) in MOD-02 |
| may be absent | std::optional<T> (small values) or const T* |
std::optional<int> visits in the getter-style version |
The “keeps it” row is called a sink parameter. Member’s constructor
takes name by value and moves it into the data member:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Builds a member from an ID, a name, and a membership. `name` is a "sink"// parameter: the member keeps it, so it is taken by value and then moved// into the data member. std::move(name) hands over the string's contents// instead of copying them again; `name` itself is not used afterwards.// The ID and the membership are small, so they are simply copied.Member::Member(MemberId id, std::string name, Membership membership) : id_(id), name_(std::move(name)), membership_(membership) {}A caller with a temporary pays one move; a caller with a named string pays
one copy, which it would pay anyway; a caller who no longer needs its string
can std::move it in. const std::string& would always copy inside the
function. Gym::enrol does the same with a whole Member:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Adds a member, unless their ID is already taken.bool Gym::enrol(Member member) { // Copy the ID out first, so nobody has to wonder whether `member` has // already been moved from when id() is called. const MemberId id = member.id(); // try_emplace inserts the pair (id, member) only if `id` is not a key // yet. If the key exists it does nothing: unlike `members_[id] = ...`, // it never replaces the existing member. std::move(member) moves the member // into the map instead of copying it. try_emplace returns a pair: // .first points at the entry, .second is true only if it inserted. return members_.try_emplace(id, std::move(member)).second;}It copies the ID into a local before moving member, so a reader does not
have to work out whether member has already been moved from when id() is
called.
Do not use output parameters (bool find(int id, Member& out)) to return
values. Return the value: const Member* find(MemberId) const. An output
parameter makes the caller declare an object before the call, and makes it
unclear whether the object is changed on failure. The exception is a large
buffer that the caller reuses across many calls, such as
void read_into(std::vector<std::byte>& buffer), where returning a new one
each time would allocate.
Return types: how to report each outcome
Section titled “Return types: how to report each outcome”Decide what can happen when the function runs, then choose the type that makes every outcome visible to the caller:
| What can happen | Return type | Gym example |
|---|---|---|
| always succeeds, with an answer | the value | int people_inside() const |
| always succeeds, nothing to report | void |
void Member::suspend() |
| succeeds or not, and the caller does not need to know why | bool |
bool check_out(MemberId), bool enrol(Member) |
| succeeds, or fails for one of several reasons the caller shows or acts on | an enum class of outcomes |
CheckIn check_in(...), Admission admit(Day) |
| an answer that may not exist, and that is normal | std::optional<T> |
std::optional<int> visits_left() const |
| an existing object that may not exist | const T* (null if absent) |
const Member* find(MemberId) const |
| a part of this object that always exists | const T&, valid while this object is |
const std::string& name() const |
| a read-only look at a sequence inside this object | std::span<const T>, valid until the next change |
std::span<const Day> visit_days() const |
| the caller broke a precondition (a bug) | throw an exception | visit_pass(0, ...), use_visit when not allowed, Gym(0) |
Two rows need explaining.
- Why
findreturns a pointer, notstd::optional. Before C++26,std::optional<const Member&>is not allowed (C++26 adds it), andstd::optional<Member>would return a copy, which the caller could change without effect. Aconst Member*refers to the real member and is null when there is none. A pointer cannot say how long it stays valid, so that belongs in a comment. Here the comment says it is valid until the gym is destroyed, assigned to, or moved from. Members are never removed, andstd::mapdoes not move its elements when others are added, so enrolling more members is safe. - Exceptions for bugs, values for outcomes. A refused check-in is normal: it happens every day, and the desk shows the reason. It is a return value. Asking for a pass with zero visits is a mistake in the calling code, and continuing would create an object that breaks its own rules. It throws. The lesson on errors and failure contracts covers this choice in detail.
const, [[nodiscard]], noexcept, explicit
Section titled “const, [[nodiscard]], noexcept, explicit”These four keywords are part of the signature, and each one is a promise the compiler or the caller relies on.
| Keyword | Put it on | Gym examples | Leave it off |
|---|---|---|---|
const (after the parameter list) |
every query | people_inside, find, allows_visit, name |
every command |
[[nodiscard]] |
queries, and commands whose result it is almost always a bug to ignore | check_in, admit, the Membership factories |
commands whose result is often fine to ignore (check_out of someone who already left) |
noexcept |
functions that cannot fail: simple getters, flag changes, to_string |
Member::suspend, allows_visit, visit_days |
anything that allocates (admit appends to a vector) or throws (use_visit) |
explicit |
constructors callable with one argument | explicit Gym(int capacity) |
copy and move constructors; constructors meant as conversions (rare) |
Some details:
[[nodiscard]]turns a silent bug into a warning. If a caller writesgym.check_in(id, today);and ignores a refusal, the desk lets someone in who was refused. With[[nodiscard]], the compiler warns.enrolandcheck_outare not marked in the example. That is a judgement call: a duplicate enrolment may be worth a warning too, and some teams mark every non-voidfunction.noexceptis a promise first. If anoexceptfunction throws, the program callsstd::terminate. Mark only functions that truly cannot throw. It also changes what some code does: when astd::vectorgrows, it moves its elements only if the move constructor isnoexcept(or the type cannot be copied); otherwise it copies them to stay safe (CPP-08).- Without
explicit, anintis aGym.void open(Gym gym); open(50);would compile and create a gym with capacity 50.explicitmakes the conversion a compile error;open(Gym(50))says what it means.
Static member functions and free functions
Section titled “Static member functions and free functions”Not every function belongs on an object.
Named constructors. Membership has two ways to be created, which differ
in meaning, not just in arguments. A constructor would need a flag or a magic
value (Membership(30, -1)). Two static member functions, with the real
constructor private, make each call say what it creates:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What a member has paid for: valid until a last day, and either unlimited// or limited to a number of visits. Owns the rule "may this membership be// used today?", so no other class needs to know how a membership works.class Membership {public: // The two ways to create a Membership. They are "named constructors": // `static` member functions, called on the class itself, as in // Membership::unlimited_until(30), with no object needed first. Each name // says which kind of membership you get, which a plain constructor with // a magic "-1 visits means unlimited" argument could not. // // As many visits as the member likes, up to and including `last_day`. [[nodiscard]] static Membership unlimited_until(Day last_day); // A pass for `visits` visits, usable up to and including `last_day`. // Throws std::invalid_argument unless visits > 0, so a pass with zero // (or a negative number of) visits can never exist. [[nodiscard]] static Membership visit_pass(int visits, Day last_day);
// A query: may this membership be used on `today`? True when today is // not after the last day and, for a pass, at least one visit is left. // `const` means it changes nothing, so asking twice is safe. `noexcept` // promises it never throws. [[nodiscard]] bool allows_visit(Day today) const noexcept; // A command: uses one visit (none for an unlimited membership). // Throws std::logic_error unless allows_visit(today): a caller that uses // a visit without asking first has a bug, and the exception reports it. void use_visit(Day today);
[[nodiscard]] Day last_day() const noexcept { return last_day_; } // How many visits are left on a pass; std::nullopt (an empty optional) // means unlimited, so "no limit" is not a fake number such as -1. [[nodiscard]] std::optional<int> visits_left() const noexcept { return visits_left_; }
private: // The real constructor is private, so code outside the class can only // use the two named functions above, and both of them build a valid // membership. The part after the colon copies each argument into its // data member. Membership(Day last_day, std::optional<int> visits_left) noexcept : last_day_(last_day), visits_left_(visits_left) {}
Day last_day_; // the last day the membership can be used std::optional<int> visits_left_; // std::nullopt: unlimited};Membership::visit_pass(2, 60) cannot be misread, and visit_pass checks
that the pass has at least one visit, so no pass with zero visits exists.
Free functions. A function that needs only the public interface does not
need to be a member. to_string(CheckIn) is a free function in the gym
namespace: an enum cannot have member functions, and keeping display text
out of Gym keeps the class about the rules. Free functions in the same
namespace are found by argument-dependent lookup, so callers write
to_string(result) without a prefix.
Helpers that only one .cpp file uses go in an unnamed namespace in that
file, like from_admission in gym.cpp. They are not part of the interface
at all.
A useful test: could this function be written using only the public
interface? If yes, a free function keeps the class smaller and its private
data more private. visits_between could be (it could use visit_days()),
but it stays a member because counting a member’s visits is a question about
the member, and a reader looks for it there. Both choices are reasonable.
Keep the public interface small
Section titled “Keep the public interface small”Every public member function is a promise: callers will use it, and changing it means changing them. Start with the needs table, and add a public function only when a caller needs it. The gym’s interface, by caller:
| Caller | Can do | Cannot do |
|---|---|---|
| front desk | check_in, check_out, find (read-only) |
admit a member without the gym’s checks; change a membership |
| staff | enrol, suspend, reinstate, renew |
change visits left, except by renewing with a whole new membership; edit the visit history |
| manager | people_inside, find then visits_between |
change anything through a const Gym& |
The “cannot do” column is the point. A rule is enforced only if there is no
public way around it. Member::admit is public, so that Gym can call it
and tests can test it, but callers outside the gym only ever get a
const Member*, and admit is not const.
find_enrolled, which returns a non-const Member*, is private: it is how
Gym’s own commands reach a member to tell it something.
When not to
Section titled “When not to”- Do not add
[[nodiscard]]andnoexcepteverywhere by habit. A wrongnoexceptterminates the program; a[[nodiscard]]on a result that is often ignored trains people to ignore warnings. - Do not invent an outcome
enumfor a function with one way to fail.boolis clearer when there is only “it worked” or “it did not”. - Do not hide a plain record behind getters. A
structwith public members (Hold,Sale) has no rules to protect. - Do not wrap every
intin its own type. Do it when two values could be confused and the mistake would compile, as with member IDs. (Days and visit counts are bothintin this example to keep it short, which is exactly the kind of mix-up a real system would prevent with a day type.)
Trade-offs
Section titled “Trade-offs”Careful signatures take longer to write and make headers longer:
[[nodiscard]] CheckIn check_in(MemberId id, Day today); is longer than
bool checkIn(int, int);. They pay back every time someone calls the
function, because the compiler catches swapped arguments, ignored refusals,
and changes through a const object, and the caller does not need to read
the body. For a private helper used in one place, the plainer signature is
often fine.
Common mistakes
Section titled “Common mistakes”- Getters and setters for every data member instead of the commands and queries callers need.
- Returning
boolwhen the caller must show why it failed. - Returning a non-
constreference to internals, which lets callers skip the rules. - Forgetting
conston queries, so aconstobject cannot be asked anything. const std::string&for a parameter that is stored, which always copies. Take it by value and move it.- Storing a
std::string_viewparameter. - Throwing for normal outcomes (a refused check-in) or returning error codes for bugs (a pass with zero visits).
boolflag parameters that cannot be read at the call site.
When a requirement changes
Section titled “When a requirement changes”The desk asks for a family check-in: several members arrive together and are checked in with one action.
- The new command takes a read-only sequence of IDs it does not keep:
std::span<const MemberId> ids. A caller can pass astd::vector, astd::array, or a plain array. - It returns one outcome per member:
std::vector<CheckIn>, in the same order asids. - It raises a question for the gym before any code: if there is room for
two of a family of three, are two let in, or none? “Two” is a loop over
check_in. “None” needs every member checked before any is admitted. The gym checks itself that the whole family fits under its capacity. For each member’s own refusals it needs aconstquery that answers without using a visit, soMembergains[[nodiscard]] Admission can_admit(Day today) const.admitkeeps its signature and callscan_admitbefore changing anything. - If none are let in, the result still has one entry per member: each
member’s own refusal, and
gym_full(or a newfamily_refusedoutcome, if the desk must tell the cases apart) for those who could have come in.
// Checks in a group (a family, say) on `today`. `ids` is a read-only view of// the caller's IDs: std::span<const MemberId> accepts a std::vector, a// std::array, or a plain array, without copying, and the function must not// keep it. The result has one CheckIn per ID, in the same order as `ids`.[[nodiscard]] std::vector<CheckIn> check_in_all(std::span<const MemberId> ids, Day today);No existing signature changes; one query is added and admit is
reorganized inside. That is the benefit of the small interface: new needs
become new functions.
Exercise: Fix six signatures
Each declaration below comes from a different class. Say what is wrong with
it, and write a better one. Assume the types named (Book, Money, and so
on) exist.
// Declarations only: return type, Class::name, then the parameters.bool Library::getBook(std::string title, Book& out);void Account::setBalance(int cents);int Thermostat::temperature();void Playlist::add(const std::string& title); // stores the titlevoid Printer::print(Document doc, bool color, bool duplex);std::vector<Loan>& Member::loans();Show the explained answer
-
getBookuses an output parameter, copies the title string for a lookup, and is notconst. Return the book, or nothing, and read the title as a view:[[nodiscard]] const Book* find(std::string_view title) const;(If the library’s map is
std::map<std::string, Book>, give it the comparatorstd::less<>so thatfindcan look up astd::string_viewwithout making astd::string.) -
setBalancelets any caller set any balance, and anintof cents can be confused with any other number. Replace it with the commands the account’s rules allow, with a money type:void deposit(Money amount);[[nodiscard]] WithdrawResult withdraw(Money amount); // ok, insufficient_funds, ... -
temperatureis a query that is notconst, so aconst Thermostat&cannot be asked. It also returns a bareint(which unit?):[[nodiscard]] Celsius temperature() const noexcept;(
noexceptonly if reading the temperature cannot fail. If it reads a sensor that can fail, returnstd::optional<Celsius>or an outcome.) -
Playlist::addstores the title, so takingconst std::string&always copies inside the function. Take it by value and move it in:void add(std::string title); // body: titles_.push_back(std::move(title)); -
printtakes the document by value (a copy, if it is large) and twoboolflags that cannot be read at the call site (print(doc, true, false)). Pass the document byconst&and the choices as named values:enum class Color { mono, color };enum class Sides { one, two };struct PrintOptions { Color color = Color::mono; Sides sides = Sides::one; };void print(const Document& doc, PrintOptions options);A call is now
print(doc, {.color = Color::color, .sides = Sides::one}), using C++20 designated initializers so each choice is named. -
loansreturns a non-constreference to the member’s data, so any caller can add, remove, or edit loans, skipping whatever rules the member applies. Return a read-only view, and add commands for the changes callers really need:[[nodiscard]] std::span<const Loan> loans() const noexcept; // valid until the next change
Summary
Section titled “Summary”- A signature answers five questions for the caller: what it does, what it needs, what it returns, whether it changes the object, and what can go wrong. Make each answer visible in the declaration.
- Queries are
constand change nothing; commands change the object and may return their outcome. - Pass small values by value, large read-only objects by
const&, text and sequences you only read asstd::string_viewandstd::span, and parameters you keep by value withstd::move. Never store a view. - Report outcomes with the narrowest type that shows them all:
boolfor yes or no, anenum classfor reasons,std::optionalfor “no answer”,const T*for “maybe this object”. Throw only when the caller broke a precondition. - Use
[[nodiscard]]where ignoring the result is a bug,noexceptwhere failure is impossible, andexpliciton one-argument constructors. - Use named
staticfunctions for ways of creating an object that differ in meaning, and free functions for what needs only the public interface. - Keep the public interface to what callers need. A rule holds only if there is no public way around it.