Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

C++  Module 7 – Classes, objects and RAII

C++ static members, friends and nested types

Share one value across all objects with static members, give chosen functions private access with friends and hidden friends, and nest types in classes.

  • Intermediate
  • 20 minutes
  • Examples run with Clang 21.0.0, GCC 16.2.0 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Use static data members and static member functions, and define them correctly before and after C++17
  • Use friend functions and friend classes to give chosen non-members access to private members
  • Explain why hidden friends are found only through their class, and what that prevents
  • Define nested types and member aliases that generic code can read
What you’ll learn

What you will learn

  • Use static data members and static member functions, and define them correctly before and after C++17
  • Use friend functions and friend classes to give chosen non-members access to private members
  • Explain why hidden friends are found only through their class, and what that prevents
  • Define nested types and member aliases that generic code can read
On this page

sizeof(Ticket) is 24 bytes with Apple clang, exactly its one std::string, although every ticket also changes a shared counter. A static member belongs to a class rather than to any one object. A static data member: A data member declared static: one variable for the whole program, shared by every object of the class and stored in none of them, so sizeof does not count it. Since C++17, inline static declares and defines it inside the class. exists once for the whole program, however many objects there are, so it suits a count of live objects or a setting that every object shares. A static member function: A member function declared static: it belongs to the class and runs without an object, so it has no this, can use only static members and the objects it is given or creates, and is called as Class::f(). runs without an object, has no this: Inside an ordinary member function, a pointer to the object the function was called on: in a.add(4'000), this is &a. A member name such as total_ in the body means this->total_. More in “C++ classes, member functions and access control” pointer and is called through the class, as in Ticket::live(). A friend declaration: A declaration inside a class, such as friend bool f(const A&); or friend class B;, that lets that function or every member function of that class use the class's private members. Friendship is not inherited, transitive or mutual. declaration lets a non-member function or another class use the class’s private members; a friend function defined inside the class, a hidden friend: A friend function defined inside its class and declared nowhere else. Ordinary lookup does not find it; argument-dependent lookup does, and only when an argument has the class's type, so conversions cannot pull other types to it., is found only through arguments of that class, which keeps it out of unrelated code.

This lesson counts tickets with a static member, shows the link error that C++17’s inline variables removed, grants private access with friends, compares hidden friends with operators at namespace scope, and nests a type inside a playlist. Every example runs with Apple clang 21 and GCC 16.

A static data member exists once for the whole class

Ticket counts the tickets that exist at the moment. Each constructor adds one to live_ and the destructor takes one away, and because live_ is static, all the tickets change the same counter:

ticket_counter.cpp C++ · ticket_counter.cpp
// A static data member: one counter shared by every Ticket, not one per object.
#include <print>
#include <string>
#include <utility>

class Ticket {
public:
    explicit Ticket(std::string passenger) : passenger_(std::move(passenger)) { ++live_; }
    Ticket(const Ticket& other) : passenger_(other.passenger_) { ++live_; }
    Ticket& operator=(const Ticket&) = default;
    ~Ticket() { --live_; }

    // A static member function has no object, so it is called on the class: Ticket::live().
    static int live() { return live_; }

    // A constant that belongs to the class; static constexpr members are inline since C++17.
    static constexpr int max_per_booking = 6;

private:
    std::string passenger_;
    inline static int live_ = 0;   // inline (C++17): declared and defined here, once for the program
};

int main() {
    std::println("at the start:      live() = {}", Ticket::live());
    Ticket a("Asha");
    {
        Ticket b("Dev");
        Ticket c = b;   // the copy constructor counts too
        std::println("inside the block: live() = {}", Ticket::live());
    }
    std::println("after the block:  live() = {}", Ticket::live());
    std::println("a.live() makes the same call: {}", a.live());
    std::println("at most {} tickets per booking", Ticket::max_per_booking);
    std::println("sizeof(Ticket) = {}, sizeof(std::string) = {}", sizeof(Ticket), sizeof(std::string));
}
Three tickets, then one Python · ticket_session.py
from session import run

# ticket_counter.cpp built and run with Apple clang, then with GCC 16.
run("""
clang++ -std=c++23 -Wall -Wextra ticket_counter.cpp -o ticket_counter && ./ticket_counter
g++-16 -std=c++23 -Wall -Wextra ticket_counter.cpp -o ticket_counter-gcc && ./ticket_counter-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra ticket_counter.cpp -o ticket_counter && ./ticket_counter
at the start:      live() = 0
inside the block: live() = 3
after the block:  live() = 1
a.live() makes the same call: 1
at most 6 tickets per booking
sizeof(Ticket) = 24, sizeof(std::string) = 24
$ g++-16 -std=c++23 -Wall -Wextra ticket_counter.cpp -o ticket_counter-gcc && ./ticket_counter-gcc
at the start:      live() = 0
inside the block: live() = 3
after the block:  live() = 1
a.live() makes the same call: 1
at most 6 tickets per booking
sizeof(Ticket) = 32, sizeof(std::string) = 32

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 ticket_session.py

Three Ticket objects each hold their own passenger name, while one live_ counter in static storage is shared by all three.Three TicketsTicket::live_ = 3one int for the whole program,in static storage, not inside any objecta: passenger_ = "Asha"b: passenger_ = "Dev"c, a copy of b:passenger_ = "Dev"every constructor adds 1,every destructor takes 1 away

Ordinary members live in each object, a static member once

Text description of the diagram

The diagram shows the memory of the Ticket example while three tickets exist.

  1. Each of the three Ticket objects, a, b and c, holds its own data member passenger_: "Asha", "Dev" and, in c, the copy of b, "Dev" again. Copying or destroying one object does not touch the others.
  2. The static data member Ticket::live_ is not inside any of them. It is a single int in static storage, created before main starts and kept until the program ends, so sizeof(Ticket) does not include it.
  3. Every constructor of Ticket adds 1 to that one counter and every destructor subtracts 1, so while these three tickets exist it holds 3.

Inside the block three tickets exist, a, b and the copy c. When the block ends, b and c are destroyed and the count falls to 1. The last line shows where the counter lives: a Ticket is exactly as large as its one ordinary member, the std::string, 24 bytes with Apple’s library and 32 with GCC’s, because a static data member is stored once, outside every object, static storage duration: The lifetime of a global, a variable at namespace scope or a static variable: it exists for the whole run of the program. Variables with thread storage duration, declared thread_local, exist once per thread instead. More in “C++ const, constexpr, consteval and constinit”. Step through main and watch the one counter that all three tickets change:

Interactive · step by step Three tickets, one counter Step through main of ticket_counter.cpp. The left column holds the Ticket objects, the right one the static member live_ that every constructor and destructor changes.
Three tickets, one counter, step 7 of 7. Showing Ticket::live_ (1), a. In focus: Ticket::live_.++live_Ticket::live_1a"Asha"not part of sizeof(Ticket)

The drawing shows the whole scene; its 7 steps are listed below.

Every step as text
  1. Before any ticket. live_ is declared inline static int live_ = 0;: one int for the whole program, there before main starts. The first line printed at the start: live() = 0.
  2. Ticket a("Asha"). The constructor stores the passenger and runs ++live_. There is only one live_, so it is now 1.
  3. Ticket b("Dev"). Inside the block, b is made the same way, and the same counter becomes 2.
  4. The copy counts too. Ticket c = b; runs the copy constructor, which also adds 1: three tickets, and the program printed inside the block: live() = 3.
  5. The block ends. At the closing brace the block's tickets are destroyed in the reverse order of their creation, c first. Its destructor runs --live_: 2.
  6. Then b. b is destroyed next, and the counter falls to 1: after the block: live() = 1. a.live() makes the same call as Ticket::live() and also gives 1.
  7. Not inside any object. sizeof(Ticket) printed 24 with Apple clang and 32 with GCC, exactly sizeof(std::string) with each library: the counter is stored once, outside every ticket.

Two kinds of declaration define a static member inside the class:

  • inline static int live_ = 0; declares the member and defines it in one place, which C++17 made possible (paper P0386R2). Every file that includes the class shares the one variable.
  • static constexpr int max_per_booking = 6; is a constant known while compiling. Since C++17 a static constexpr member is automatically inline, so it needs no definition elsewhere either.

A static data member that changes is a global variable with a class name in front of it. The C++ Core Guidelines advise against changeable globals (rule I.2), because any code anywhere can change them and threads can race on them. A counter like this one is fine in a single-threaded program; the concurrency module makes such counters safe with std::atomic.

Checkpoint

Check: One static data member for the whole class

  1. Question 1 of 2 Ticket a("Asha"); is made, then inside a block Ticket b("Dev"); and Ticket c = b;. What does Ticket::live() return inside the block?

    Type a number.

    A hint

    Does the copy constructor change the counter too?

    Show the answer: Question 1 of 2

    Answer: 3 tickets

    Every constructor of Ticket, the copy constructor included, adds 1 to the one live_, so three tickets give 3: the program printed inside the block: live() = 3, and 1 after the block, once b and c were destroyed.

  2. Question 2 of 2 GCC 16 printed sizeof(Ticket) = 32, sizeof(std::string) = 32. Why is the static member live_ not counted?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: It is stored once for the whole program, outside every Ticket object

    A Ticket is exactly as large as its one ordinary member, the std::string: 24 bytes with Apple's library and 32 with GCC's. The counter lives in static storage, once.

Without inline, a static member needs one definition elsewhere

Without inline, a static data member declared in a class is only a declaration. Exactly one source file must also define it, with a line such as int Config::retries = 3; outside the class. Forget that line and every file still compiles, because the compiler sees the declaration, but the linker: The last stage of a build: it joins the object files of a program and the libraries it uses into one executable, matching every symbol a file uses with exactly one definition. More in “How C++ compiles: preprocess, compile and link” finds no variable:

missing_definition.cpp C++ · missing_definition.cpp
// Before C++17: a static data member declared in the class still needs one definition outside it.
struct Config {
    static int retries;          // a declaration only
};

// int Config::retries = 3;      // the definition this program forgot

int main() { return Config::retries; }
It compiles, and the link fails Python · definition_session.py
from session import run

# Compiling missing_definition.cpp works; linking it fails, with both compilers.
run("""
clang++ -std=c++23 -c missing_definition.cpp -o missing_definition.o && clang++ missing_definition.o -o missing_definition
g++-16 -std=c++23 -c missing_definition.cpp -o missing_definition-gcc.o && g++-16 missing_definition-gcc.o -o missing_definition-gcc
""")

Output

$ clang++ -std=c++23 -c missing_definition.cpp -o missing_definition.o && clang++ missing_definition.o -o missing_definition
Undefined symbols for architecture arm64:
  "Config::retries", referenced from:
      _main in missing_definition.o
ld: symbol(s) not found for architecture arm64
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
[exit status 1]
$ g++-16 -std=c++23 -c missing_definition.cpp -o missing_definition-gcc.o && g++-16 missing_definition-gcc.o -o missing_definition-gcc
Undefined symbols for architecture arm64:
  "Config::retries", referenced from:
      _main in missing_definition-gcc.o
ld: symbol(s) not found for architecture arm64
collect2: error: ld returned 1 exit status
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 definition_session.py

Both compilers build the object file without a word and stop when they link it, at the same symbol. Step through the build, from the declaration to the failed link and the fix:

Interactive · stage by stage A static member that is declared and never defined Step through the build of missing_definition.cpp, from the source file to the link that fails, then the two fixes.
A static member that is declared and never defined, step 5 of 5. Showing missing_definition.cpp, compile: -c (Config::retries: wanted), link (undefined symbol), the fix. In focus: the fix.add the definitionmissing_definition.cppstatic int retries;compile: -cConfig::retries: wantedlinkundefined symbolthe fixone definitionadd the definition

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. A declaration only. struct Config { static int retries; }; declares the member, and main returns Config::retries. The definition, int Config::retries = 3;, is commented out.
  2. It compiles. Compiling with -c succeeds with both compilers, silently: the declaration tells the compiler the type, so it writes the read of Config::retries into the object file and leaves the address to the linker.
  3. The link fails. The linker looks for the variable in every object file and finds none: Undefined symbols for architecture arm64: "Config::retries", referenced from: _main.
  4. The same with GCC. GCC 16 stops at the same stage with the same report, followed by collect2: error: ld returned 1 exit status. The compiler never complained; only linking can find a missing definition.
  5. Two fixes. Before C++17, write int Config::retries = 3; in exactly one .cpp file of the program. Since C++17, inline static int retries = 3; in the class declares and defines it at once.

The usual fix in older code is that one definition in the class’s .cpp file. Putting it in the header instead gives the opposite error as soon as two files include the header: a duplicate symbol: A name in an object file's table, such as a function's mangled name. nm marks a symbol the file defines in its code with T, and one it uses but leaves to another file with U. More in “How C++ compiles: preprocess, compile and link”. inline static avoids both problems, so prefer it whenever you can build as C++17 or later.

A static member function has no this

A static member function has no object, so it has no this and cannot name the object’s ordinary members. It can use the class’s static members, its private constructors included, which makes it the natural place for a named constructor: A static member function that creates and returns an object, such as Temperature::from_celsius(20), so that its name says what the argument means. The constructor it calls is often private. such as Temperature::from_celsius(20) that says in which unit its argument is. Reading kelvin_, though, needs an object, and both compilers refuse:

static_function_error.cpp C++ · static_function_error.cpp
// A static member function has no this pointer, so it cannot read an object's members.
class Temperature {
public:
    static Temperature from_celsius(double c) { return Temperature(c + 273.15); }   // fine: makes an object
    static double celsius() { return kelvin_ - 273.15; }   // error: whose kelvin_?

private:
    explicit Temperature(double k) : kelvin_(k) {}
    double kelvin_;
};

int main() { return Temperature::celsius() > 0; }
Whose kelvin_? Python · static_function_session.py
from session import run

# What each compiler says about static_function_error.cpp.
run("""
clang++ -std=c++23 -fsyntax-only static_function_error.cpp
g++-16 -std=c++23 -fsyntax-only static_function_error.cpp
""")

Output

$ clang++ -std=c++23 -fsyntax-only static_function_error.cpp
static_function_error.cpp:5:38: error: invalid use of member 'kelvin_' in static member function
    5 |     static double celsius() { return kelvin_ - 273.15; }   // error: whose kelvin_?
      |                                      ^~~~~~~
1 error generated.
[exit status 1]
$ g++-16 -std=c++23 -fsyntax-only static_function_error.cpp
static_function_error.cpp: In static member function 'static double Temperature::celsius()':
static_function_error.cpp:5:38: error: invalid use of member 'Temperature::kelvin_' in static member function
    5 |     static double celsius() { return kelvin_ - 273.15; }   // error: whose kelvin_?
      |                                      ^~~~~~~
static_function_error.cpp:9:12: note: declared here
    9 |     double kelvin_;
      |            ^~~~~~~
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 static_function_session.py

from_celsius compiles because it makes the object it works on: it calls the private constructor with c + 273.15 and returns the new Temperature. A static member function cannot be virtual or const either, since both describe how it treats an object. You may call one through an object, as a.live() did in the ticket example, but the object is ignored, so Ticket::live() says what really happens. The table sets the two kinds of member function side by side:

An ordinary member function and a static one, as Ticket and Temperature use them
Criterion Ordinary member functionStatic member function
Called as a.f(), on an objectTicket::live(), on the class
Has this Yes: the object it is called onNo: there is no object
Reads ordinary members Of its objectOnly of objects it is given or makes
Private constructors May call themMay call them: from_celsius does
virtual or const AllowedNot allowed

Checkpoint

Check: Defining a static data member, before and after C++17 · Static member functions have no this

  1. Question 1 of 2 struct Config { static int retries; }; is defined nowhere, and main reads Config::retries. Where did the build of missing_definition.cpp stop?
    Show the answer: Question 1 of 2

    Answer: When linking, with Undefined symbols for architecture arm64 and "Config::retries"

    Without inline, a static data member declared in a class is only a declaration. Exactly one source file must define it, or every file compiles and the link fails.

  2. Question 2 of 2 Which line of this class does not compile?

    Read the code, then choose one answer.

    class Temperature {
    public:
        static Temperature from_celsius(double c) { return Temperature(c + 273.15); }   // line A
        static double celsius() { return kelvin_ - 273.15; }                            // line B
        double kelvin() const { return kelvin_; }                                        // line C
    private:
        explicit Temperature(double k) : kelvin_(k) {}
        double kelvin_;
    };
    Show the answer: Question 2 of 2

    Answer: Line B

    A static member function can use static members, its parameters and the objects it creates, and it may call private constructors. It cannot read an object's members without an object.

A class names its friends, and friendship goes no further

A class can name the non-members that may use its private members. A friend function is an ordinary function with that access, and a friend class gives it to every member function of the other class:

friends.cpp C++ · friends.cpp
// A friend function and a friend class: non-members that the class lets read its private members.
#include <cstdint>
#include <print>

class Wallet {
public:
    explicit Wallet(std::int64_t paise) : paise_(paise) {}

    friend bool same_balance(const Wallet& a, const Wallet& b);   // a non-member with access
    friend class Auditor;                                          // every member of Auditor has access

private:
    std::int64_t paise_;
};

bool same_balance(const Wallet& a, const Wallet& b) { return a.paise_ == b.paise_; }

class Auditor {
public:
    static std::int64_t total(const Wallet& a, const Wallet& b) { return a.paise_ + b.paise_; }
};

int main() {
    Wallet mine(25000), yours(25000);
    std::println("same balance? {}", same_balance(mine, yours));
    std::println("total {} paise", Auditor::total(mine, yours));
}
A friend function and a friend class Python · friends_session.py
from session import run

# friends.cpp built and run with both compilers.
run("""
clang++ -std=c++23 -Wall -Wextra friends.cpp -o friends && ./friends
g++-16 -std=c++23 -Wall -Wextra friends.cpp -o friends-gcc && ./friends-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra friends.cpp -o friends && ./friends
same balance? true
total 50000 paise
$ g++-16 -std=c++23 -Wall -Wextra friends.cpp -o friends-gcc && ./friends-gcc
same balance? true
total 50000 paise

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 friends_session.py

Step through who may read Wallet’s balance, and who may not:

Interactive · step by step Who may read Wallet's private balance Step through the friend declarations of friends.cpp. The left column is Wallet; on the right are the functions and classes that try to read its paise_.
Who may read Wallet's private balance, step 6 of 6. Showing Wallet, same_balance(), Auditor, class Junior : Auditor, Auditor's friend. In focus: Wallet, Auditor.reads paise_reads paise_no accessno accessno accessWalletprivate: paise_same_balance()a friend functionAuditora friend classclass Junior : Auditorderived from AuditorAuditor's frienda friend of Auditor

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Private to Wallet. Wallet keeps its balance in the private member paise_. Only Wallet's own member functions may read it, unless Wallet names a friend in its own definition.
  2. A friend function. friend bool same_balance(const Wallet&, const Wallet&); gives one non-member function the access: it compares a.paise_ with b.paise_, and the program printed same balance? true.
  3. A friend class. friend class Auditor; gives it to every member function of Auditor: Auditor::total read both balances and printed total 50000 paise.
  4. Not inherited. A class derived from Auditor gets no access to paise_: friendship belongs to Auditor itself, not to the classes built on it.
  5. Not transitive. A friend of Auditor is not a friend of Wallet. Only Wallet can name its own friends.
  6. Not mutual. And Wallet gets no access to the private members of Auditor. Each class grants friendship in its own definition, and no outside code can make itself a friend.

Friendship follows four rules:

  • The class grants it, in its own definition. No outside code can make itself a friend.
  • It is not inherited: a class derived from Auditor gets no access to Wallet.
  • It is not transitive: a friend of Auditor is not a friend of Wallet.
  • It is not mutual: Wallet has no access to the private members of Auditor.

Use friends sparingly. Guideline C.4 keeps a function out of the class unless it works on the class’s private representation, and a friend gives that access to a function that cannot be a member, such as an operator whose left operand has another type. The previous lessons’ comparison and output operators are the common case; a class and a helper that are designed together, such as a container and its iterator, are the other. When a function can do its job through the public interface, it should be neither a member nor a friend.

A hidden friend is found only through its own class

A friend function that is defined inside the class, and declared nowhere else, is called a hidden friend. It belongs to the enclosing namespace, yet ordinary lookup there does not find it: only argument-dependent lookup: The rule that an unqualified function call also searches the namespaces of its argument types, so total(first, second) finds shop::billing::total when the arguments are shop::billing::Invoice. It is also how operator<< is found. More in “Scope, storage duration, linkage and namespaces” does, when an argument has the class’s type (paper P1601R0 describes the technique). Calls in the usual form work, and naming the function explicitly does not:

hidden_friend.cpp C++ · hidden_friend.cpp
// Hidden friends: defined inside the class, found only through the class of an argument.
#include <print>

namespace geo {

struct Meters {
    double value = 0;
    Meters(double v) : value(v) {}   // implicit on purpose: 2.5 converts to Meters

    friend bool operator==(Meters a, Meters b) { return a.value == b.value; }   // a hidden friend
};

}  // namespace geo

int main() {
    geo::Meters length(2.5);
    std::println("length == 2.5 is {}", length == 2.5);   // found through Meters, then 2.5 converts
    std::println("2.5 == length is {}", 2.5 == length);   // the same, with the operands the other way round
}
hidden_lookup_error.cpp C++ · hidden_lookup_error.cpp
// A hidden friend is not a member of its namespace for ordinary lookup.
namespace geo {
struct Meters {
    double value = 0;
    friend bool operator==(Meters a, Meters b) { return a.value == b.value; }
};
}  // namespace geo

int main() {
    geo::Meters a{1}, b{1};
    bool same = a == b;                       // fine: found through the class of a and b
    bool also = geo::operator==(a, b);        // error: qualified lookup cannot see it
    return same && also;
}
Found through Meters, invisible by name Python · hidden_session.py
from session import run

# hidden_friend.cpp with both compilers, then what they say about naming the hidden friend directly.
run("""
clang++ -std=c++23 -Wall -Wextra hidden_friend.cpp -o hidden_friend && ./hidden_friend
g++-16 -std=c++23 -Wall -Wextra hidden_friend.cpp -o hidden_friend-gcc && ./hidden_friend-gcc
clang++ -std=c++23 -fsyntax-only hidden_lookup_error.cpp
g++-16 -std=c++23 -fsyntax-only hidden_lookup_error.cpp
""")

Output

$ clang++ -std=c++23 -Wall -Wextra hidden_friend.cpp -o hidden_friend && ./hidden_friend
length == 2.5 is true
2.5 == length is true
$ g++-16 -std=c++23 -Wall -Wextra hidden_friend.cpp -o hidden_friend-gcc && ./hidden_friend-gcc
length == 2.5 is true
2.5 == length is true
$ clang++ -std=c++23 -fsyntax-only hidden_lookup_error.cpp
hidden_lookup_error.cpp:12:22: error: no member named 'operator==' in namespace 'geo'
   12 |     bool also = geo::operator==(a, b);        // error: qualified lookup cannot see it
      |                      ^~~~~~~~~~
1 error generated.
[exit status 1]
$ g++-16 -std=c++23 -fsyntax-only hidden_lookup_error.cpp
hidden_lookup_error.cpp: In function 'int main()':
hidden_lookup_error.cpp:12:22: error: 'operator==' is not a member of 'geo'
   12 |     bool also = geo::operator==(a, b);        // error: qualified lookup cannot see it
      |                      ^~~~~~~~~~
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 hidden_session.py

length == 2.5 and 2.5 == length both work: lookup finds the operator through length, a Meters, and then the double converts. geo::operator==(a, b) fails because qualified lookup searches the namespace itself, where the hidden friend was never made visible.

That invisibility is the point. An operator at namespace scope is a candidate for every comparison in its namespace, and implicit conversions can pull in types that were never meant to meet it:

namespace_scope.cpp C++ · namespace_scope.cpp
// An operator== at namespace scope, and a type that converts to Meters: two Feet compare as Meters.
#include <print>

struct Meters {
    double value = 0;
    Meters(double v) : value(v) {}
};
bool operator==(Meters a, Meters b) { return a.value == b.value; }   // namespace scope: ordinary lookup finds it

struct Feet {
    double value = 0;
    operator Meters() const { return Meters(value * 0.3048); }        // an implicit conversion to Meters
};

int main() {
    Feet f{10}, g{10};
    std::println("Feet == Feet compiles and gives {}", f == g);   // both Feet quietly became Meters
}
hidden_blocks.cpp C++ · hidden_blocks.cpp
// The same design with a hidden friend: no operand is a Grams, so the operator is never considered.
#include <print>

struct Grams {
    double value = 0;
    Grams(double v) : value(v) {}
    friend bool operator==(Grams a, Grams b) { return a.value == b.value; }   // hidden friend
};

struct Ounces {
    double value = 0;
    operator Grams() const { return Grams(value * 28.349523125); }           // an implicit conversion to Grams
};

int main() {
    Ounces x{1}, y{1};
    std::println("{}", x == y);   // error: lookup for operator== never looks inside Grams
}
Two Feet compare; two Ounces do not Python · conversions_session.py
from session import run

# namespace_scope.cpp builds and runs; hidden_blocks.cpp does not compile (first error of each compiler).
run("""
clang++ -std=c++23 -Wall -Wextra namespace_scope.cpp -o namespace_scope && ./namespace_scope
g++-16 -std=c++23 -Wall -Wextra namespace_scope.cpp -o namespace_scope-gcc && ./namespace_scope-gcc
clang++ -std=c++23 -fsyntax-only hidden_blocks.cpp 2>&1 | grep -m1 error:
g++-16 -std=c++23 -fsyntax-only hidden_blocks.cpp 2>&1 | grep -m1 error:
""")

Output

$ clang++ -std=c++23 -Wall -Wextra namespace_scope.cpp -o namespace_scope && ./namespace_scope
Feet == Feet compiles and gives true
$ g++-16 -std=c++23 -Wall -Wextra namespace_scope.cpp -o namespace_scope-gcc && ./namespace_scope-gcc
Feet == Feet compiles and gives true
$ clang++ -std=c++23 -fsyntax-only hidden_blocks.cpp 2>&1 | grep -m1 error:
hidden_blocks.cpp:17:26: error: invalid operands to binary expression ('Ounces' and 'Ounces')
$ g++-16 -std=c++23 -fsyntax-only hidden_blocks.cpp 2>&1 | grep -m1 error:
hidden_blocks.cpp:17:26: error: no match for 'operator==' (operand types are 'Ounces' and 'Ounces')

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 conversions_session.py

Two Feet compare equal through the namespace-scope operator== for Meters, after both are converted. Nobody wrote a comparison for Feet, and a version that compared feet differently would never be called. The hidden friend of Grams is considered only when an operand is a Grams, so two Ounces do not compare at all, which is what their author intended. Because a hidden friend is a candidate only for its own type, a comparison that fails to compile also comes with a shorter list of candidates in the error message. The standard library specifies many of its own operators as hidden friends. Step through both comparisons and see where each lookup searches:

Interactive · step by step An operator at namespace scope against a hidden friend Step through two comparisons of types that convert. The left column is Feet and the operator== of Meters at namespace scope; the right one Ounces and the hidden friend of Grams.
An operator at namespace scope against a hidden friend, step 7 of 7. Showing f == g: two Feet, x == y: two Ounces, operator== for Meters, Grams' operator==, compiles (true, as Meters), error (no operator== found). In focus: Grams' operator==.ordinary lookupnever searchedf == g: two Feetno == of its ownx == y: two Ouncesno == of its ownoperator== for Metersat namespace scopeGrams' operator==a hidden friendcompilestrue, as Meterserrorno operator== found

The drawing shows the whole scene; its 7 steps are listed below.

Every step as text
  1. Two Feet. f == g compares two Feet. Nobody wrote an operator== for Feet, but Feet converts to Meters.
  2. Found by ordinary lookup. The operator==(Meters, Meters) declared at namespace scope is found by ordinary lookup, so it is a candidate for every == there. Both Feet convert to Meters, which makes it viable.
  3. A comparison nobody wrote. The line compiles and printed Feet == Feet compiles and gives true: two Feet compared as Meters, through a comparison written for another type.
  4. Two Ounces. x == y compares two Ounces, which also convert, to Grams. This time the operator== is a hidden friend: defined inside Grams and declared nowhere else.
  5. Only the operands' classes. Ordinary lookup does not see a hidden friend. Argument-dependent lookup searches the classes of the operands, and both are Ounces, so Grams is never searched.
  6. No operator==. No operator== is found, and both compilers reject the line, as the author of Grams intended: invalid operands to binary expression ('Ounces' and 'Ounces').
  7. Through its own class. With an operand of its own class a hidden friend works as usual: in hidden_friend.cpp, length == 2.5 and 2.5 == length find it through length, a Meters, and then 2.5 converts.

Key idea

A hidden friend is found only by argument-dependent lookup through an operand of its own class, so implicit conversions cannot drag unrelated types to it, and a failed comparison lists fewer candidates.

Checkpoint

Check: Friend functions, friend classes and their rules · Hidden friends and argument-dependent lookup

  1. Question 1 of 2 class Wallet declares friend class Auditor;. Which of these may read Wallet's private paise_?

    Choose every answer that is right.

    Show the answer: Question 1 of 2

    Answer:

    • same_balance, which Wallet declares as a friend function
    • Auditor::total, a static member function of Auditor

    A class grants friendship in its own definition, to named functions and classes only, and the access is neither inherited, transitive nor mutual.

  2. Question 2 of 2 Grams defines friend bool operator==(Grams, Grams) inside the class, and Ounces converts to Grams. What happens to Ounces{1} == Ounces{1}?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: It does not compile, because lookup never searches Grams for two Ounces operands

    Argument-dependent lookup searches the classes of the operands. The conversion to Grams does not make Grams one of them, so the hidden friend stays out of reach, which is what its author intended.

Nested types and aliases let templates ask a class for its types

Nested types, such as Playlist::Song, and member type alias: A type alias declared inside a class, such as using value_type = Song;. Generic code reads it as typename Container::value_type, the convention every standard container follows., such as using value_type = Song;, keep names that belong together inside the class that uses them.

A type declared inside a class is a member like any other, named with the class in front, Playlist::Song, and it follows the class’s access rules. Member aliases give generic code a way to ask a class about its types, the convention that every standard container follows with value_type, size_type and their relatives:

nested_types.cpp C++ · nested_types.cpp
// A nested type and member aliases: Playlist names its element type the way the standard containers do.
#include <compare>
#include <cstddef>
#include <print>
#include <string>
#include <vector>

class Playlist {
public:
    struct Song {                     // a nested type, called Playlist::Song outside the class
        int seconds = 0;
        std::string title;
        auto operator<=>(const Song&) const = default;   // seconds first, so a longer song is larger
    };

    using value_type = Song;          // member aliases, as std::vector<Song> has
    using size_type = std::size_t;

    void add(Song s) { songs_.push_back(s); }
    size_type size() const { return songs_.size(); }
    auto begin() const { return songs_.begin(); }
    auto end() const { return songs_.end(); }

private:
    std::vector<Song> songs_;
};

// Generic code reads the element type through the alias, so it works with any such container.
template <class Container>
typename Container::value_type largest(const Container& c) {
    typename Container::value_type best = *c.begin();
    for (const auto& item : c)
        if (best < item) best = item;
    return best;
}

int main() {
    Playlist evening;
    evening.add({245, "Monsoon Rain"});
    evening.add({312, "Long Drive"});
    evening.add({198, "Chai Break"});

    Playlist::Song longest = largest(evening);
    std::println("{} songs, the longest is {} ({} s)", evening.size(), longest.title, longest.seconds);

    std::vector<int> marks{71, 94, 88};
    std::println("the largest mark is {}", largest(marks));   // the same template, for std::vector<int>
}
One template, two containers Python · nested_session.py
from session import run

# nested_types.cpp built and run with both compilers.
run("""
clang++ -std=c++23 -Wall -Wextra nested_types.cpp -o nested_types && ./nested_types
g++-16 -std=c++23 -Wall -Wextra nested_types.cpp -o nested_types-gcc && ./nested_types-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra nested_types.cpp -o nested_types && ./nested_types
3 songs, the longest is Long Drive (312 s)
the largest mark is 94
$ g++-16 -std=c++23 -Wall -Wextra nested_types.cpp -o nested_types-gcc && ./nested_types-gcc
3 songs, the longest is Long Drive (312 s)
the largest mark is 94

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 nested_session.py

largest never names Song. It asks the container for typename Container::value_type, so the same template finds the longest song in a Playlist and the highest mark in a std::vector<int>. The typename keyword is required in the declaration of best, inside the function body, because the name depends on a template parameter; the templates module explains why, and where C++20 lets you leave it out, as in the return type. Song defaults <=> with seconds declared first, so a longer song compares greater. Step through both calls of largest:

Interactive · step by step One template asks two containers for their element type Step through both calls of largest. The left column is the Playlist evening, the right one the vector marks; the boxes below show what typename Container::value_type means for each.
One template asks two containers for their element type, step 5 of 5. Showing Playlist evening, std::vector<int> marks, best: a Playlist::Song (Long Drive (312 s)), best: an int (94). In focus: best: a Playlist::Song, best: an int.value_typevalue_typePlaylist eveningvalue_type = Songstd::vector<int> marksvalue_type = intbest: a Playlist::SongLong Drive (312 s)best: an int94

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. A template that names no type. largest never names Song. It declares typename Container::value_type best = *c.begin();, asking the container for the type of its elements.
  2. A playlist. For largest(evening), Container is Playlist, whose member alias value_type is Song, so best is a Playlist::Song, starting with the first song, 245 seconds.
  3. Songs compare by length. Song defaults <=> with seconds declared first, so best < item compares lengths: 312 seconds beats 245, and 198 does not beat 312.
  4. A vector of marks. For largest(marks), Container is std::vector<int>, whose value_type is int. The same template returns 94, the largest of 71, 94 and 88.
  5. Why typename. Container::value_type depends on a template parameter, so the compiler cannot know it is a type until largest is used; typename says so.

A nested class is a member of its enclosing class, so its member functions may use the enclosing class’s private members. The reverse does not hold: the enclosing class has no special access to the private members of the nested one. That is why the exercise below makes IdGenerator a friend of its nested Id.

Checkpoint

Check: Nested types and member aliases

  1. Question 1 of 2 largest declares typename Container::value_type best. How does it work for both a Playlist and a std::vector<int>?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Each container names its element type with a member alias value_type, Song for the playlist and int for the vector

    Member aliases give generic code a way to ask a class about its types. The same template found Long Drive (312 s) in the playlist and 94 among the marks.

  2. Question 2 of 2 In the exercise, IdGenerator has a nested class Id with a private constructor. Why does Id declare friend class IdGenerator;?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: An enclosing class has no special access to the private members of a class nested in it

    A nested class is a member of its enclosing class and may use its private members. The enclosing class gets no special access the other way, so next() may call Id's private constructor only because Id names it a friend.

Practise: an id generator

IdGenerator hands out ids 1, 2, 3 and so on, and counts how many it has handed out. Its nested class Id wraps the number, has a private constructor, so that only IdGenerator can make one, and compares with defaulted hidden friends. Complete id_generator.h:

  1. Add one counter for the whole program, as a static data member.
  2. Make next() return a new Id with the next number, starting from 1.
  3. Make issued() return how many ids have been handed out.
The starter code and its sample tests

C header · id_generator.h

// Starter code for the practice exercise: give IdGenerator its counter and complete next() and issued().
#pragma once
#include <compare>
#include <cstdint>

class IdGenerator {
public:
    // A class-local type: an id is not just any integer, and only IdGenerator can make one.
    class Id {
    public:
        std::uint32_t value() const { return value_; }

        friend bool operator==(Id, Id) = default;   // hidden friends, found only through an Id argument
        friend auto operator<=>(Id, Id) = default;

    private:
        explicit Id(std::uint32_t v) : value_(v) {}
        friend class IdGenerator;                    // so that next() may call the private constructor
        std::uint32_t value_;
    };

    // TODO: return a new Id: 1 for the first call in the program, then 2, 3 and so on.
    static Id next() { return Id(0); }

    // TODO: return how many ids next() has handed out so far.
    static std::uint32_t issued() { return 0; }

private:
    // TODO: one counter for the whole program, shared by every call.
};

C++ · id_generator_tests.cpp

// Sample tests for id_generator.h. Build: clang++ -std=c++23 -Wall -Wextra id_generator_tests.cpp -o id_generator_tests
#include <cstdint>
#include <print>
#include <type_traits>
#include "id_generator.h"

// Checked while compiling: an Id cannot be made from a plain number.
static_assert(!std::is_constructible_v<IdGenerator::Id, std::uint32_t>, "only IdGenerator makes ids");
static_assert(!std::is_convertible_v<std::uint32_t, IdGenerator::Id>, "a number never turns into an id by itself");
static_assert(sizeof(IdGenerator::Id) == sizeof(std::uint32_t), "an Id costs no more than its number");

int checks = 0;
int failures = 0;

void check(bool ok, const char* what) {
    ++checks;
    if (!ok) {
        ++failures;
        std::println("FAIL {}", what);
    }
}

int main() {
    check(IdGenerator::issued() == 0, "no ids before the first call");
    IdGenerator::Id first = IdGenerator::next();
    IdGenerator::Id second = IdGenerator::next();
    check(first.value() == 1, "the first id is 1");
    check(second.value() == 2, "the second id is 2");
    check(IdGenerator::issued() == 2, "issued() counts the ids handed out");

    IdGenerator::Id copy = first;
    check(copy == first && first != second, "ids compare equal only to themselves and their copies");
    check(first < second, "a later id is larger");

    bool increasing = true;
    IdGenerator::Id previous = second;
    for (int i = 0; i < 1000; ++i) {
        IdGenerator::Id id = IdGenerator::next();
        if (!(previous < id)) increasing = false;
        previous = id;
    }
    check(increasing, "1,000 more ids, each larger than the one before");
    check(IdGenerator::issued() == 1002 && previous.value() == 1002, "the count and the last id agree");

    std::println("{} of {} checks passed", checks - failures, checks);
    return failures == 0 ? 0 : 1;
}

The tests start with three static_asserts, which the compiler checks: an Id cannot be made or converted from a plain number, and it is no larger than the number it holds. They pass already, because the starter’s design ensures them. At run time the starter passes only the check that no ids exist yet:

The sample tests against the starter code Python · id_session.py
from session import run

# The sample tests run against the starter code, before any TODO is done.
run("""
clang++ -std=c++23 -Wall -Wextra id_generator_tests.cpp -o id_generator_tests && ./id_generator_tests
g++-16 -std=c++23 -Wall -Wextra id_generator_tests.cpp -o id_generator_tests-gcc && ./id_generator_tests-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra id_generator_tests.cpp -o id_generator_tests && ./id_generator_tests
FAIL the first id is 1
FAIL the second id is 2
FAIL issued() counts the ids handed out
FAIL ids compare equal only to themselves and their copies
FAIL a later id is larger
FAIL 1,000 more ids, each larger than the one before
FAIL the count and the last id agree
1 of 8 checks passed
[exit status 1]
$ g++-16 -std=c++23 -Wall -Wextra id_generator_tests.cpp -o id_generator_tests-gcc && ./id_generator_tests-gcc
FAIL the first id is 1
FAIL the second id is 2
FAIL issued() counts the ids handed out
FAIL ids compare equal only to themselves and their copies
FAIL a later id is larger
FAIL 1,000 more ids, each larger than the one before
FAIL the count and the last id agree
1 of 8 checks passed
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 id_session.py

Edit id_generator.h until both compilers print 8 of 8 checks passed. This generator is safe only while one thread calls it; two threads calling next() at once would race on the counter, which the concurrency module fixes.

NanoID, ULID & Snowflake ID Generator Compare counting ids like these with random and time-ordered ids, generated in the browser.

Then test the rules on classes this lesson did not write, from a Sensor that counts its readings to an Outer with a nested Inner. The idea you are least sure of is asked first, and a pick that misses says what it overlooked:

Practice that adapts to you

Practise this lesson

13 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 13 While three Ticket objects exist, how many live_ variables does the program have?

    Choose one answer.

    Show the answer: Question 1 of 13

    Answer: One, shared by every Ticket

    Every constructor adds 1 to the same live_, which is why it counted 3 inside the block.

  2. Question 2 of 13 class Sensor { double reading_; inline static int count_ = 0; }; What is sizeof(Sensor) on a typical 64-bit computer?

    Choose one answer.

    Show the answer: Question 2 of 13

    Answer: 8, the size of reading_ alone

    A static data member is stored once for the whole program, outside every object, so it adds nothing to the size of an object. Only reading_, a double of 8 bytes, is inside each Sensor.

  3. Question 3 of 13 A header declares struct Config { static int retries; }; and no file defines Config::retries. A function reads Config::retries. When does the build fail?

    Choose one answer.

    Show the answer: Question 3 of 13

    Answer: When linking, with an undefined symbol

    Inside the class, a static data member that is not inline is only a declaration, which is enough to compile any file that uses it. The linker then finds no definition. Writing inline static int retries = 3; in the class (C++17) declares and defines it at once.

  4. Question 4 of 13 static constexpr int max_per_booking = 6; is declared in Ticket. Does it need a definition outside the class?

    Choose one answer.

    Show the answer: Question 4 of 13

    Answer: No; since C++17 a static constexpr member is automatically inline, declared and defined in the class

    inline static (C++17, paper P0386R2) and static constexpr members are declared and defined in one place, and every file that includes the class shares the one variable.

  5. Question 5 of 13 Which line of this class does not compile?

    Read the code, then choose one answer.

    class Counter {
    public:
        static int total() { return total_; }        // line A
        static int mine() { return mine_; }          // line B
        int both() const { return total_ + mine_; }  // line C
    private:
        inline static int total_ = 0;
        int mine_ = 0;
    };
    Show the answer: Question 5 of 13

    Answer: Line B

    A static member function has no this, so it can name static members such as total_ but not mine_, which belongs to an object. An ordinary member function such as both() can use both kinds.

  6. Question 6 of 13 Which of these can a static member function not be?

    Choose every answer that is right.

    Show the answer: Question 6 of 13

    Answer:

    • const
    • volatile
    • virtual

    virtual, const and volatile all describe how a function treats the object it is called on, so a static member function, which has none, cannot have them.

  7. Question 7 of 13 class Wallet declares friend class Auditor;. Which of these are true?

    Choose every answer that is right.

    Show the answer: Question 7 of 13

    Answer:

    • Every member function of Auditor may use Wallet's private members
    • A class derived from Auditor gets no access to Wallet's private members

    Friendship is granted by the class that declares it, and it is neither inherited, transitive nor mutual. Only Auditor's own member functions get access to Wallet.

  8. Question 8 of 13 Which of these functions is the clearest case for a friend of Point?

    Choose one answer.

    Show the answer: Question 8 of 13

    Answer: operator<< for streams, which needs Point's private members and whose left operand is the stream

    A friend gives private access to a function that cannot be a member, such as an operator whose left operand has another type. When a function can work through the public interface, it should be neither a member nor a friend.

  9. Question 9 of 13 What makes a friend function a hidden friend?

    Choose one answer.

    Show the answer: Question 9 of 13

    Answer: It is defined inside the class and declared nowhere else

    A friend function defined inside its class belongs to the enclosing namespace, yet only argument-dependent lookup finds it, when an argument has the class's type (paper P1601R0).

  10. Question 10 of 13 operator== is a hidden friend of geo::Meters, which has an implicit constructor from double. Which line does not compile?

    Read the code, then choose one answer.

    geo::Meters a{1}, b{1};
    bool p = a == b;                  // line A
    bool q = a == 1.0;                // line B
    bool r = geo::operator==(a, b);   // line C
    Show the answer: Question 10 of 13

    Answer: Line C

    Argument-dependent lookup finds the hidden friend for lines A and B, because an operand is a Meters, and then 1.0 converts. A qualified name searches the namespace itself, where the hidden friend is not visible.

  11. Question 11 of 13 Two Feet compared equal through the operator== that Meters declares at namespace scope. What changes if that operator becomes a hidden friend of Meters?

    Choose one answer.

    Show the answer: Question 11 of 13

    Answer: Feet == Feet stops compiling, while comparisons with a Meters operand keep working

    An operator at namespace scope is a candidate for every comparison in its namespace; a hidden friend only for its own type. That is what keeps implicit conversions from dragging unrelated types to it.

  12. Question 12 of 13 Inside Playlist, what does using value_type = Song; declare?

    Choose one answer.

    Show the answer: Question 12 of 13

    Answer: A member alias, so that code outside can name Playlist's element type as Playlist::value_type

    Member aliases follow the convention of the standard containers, value_type, size_type and their relatives, so templates can ask a class about its types.

  13. Question 13 of 13 class Outer { int secret_ = 7; public: class Inner { public: int peek(const Outer& o) { return o.secret_; } }; }; Does peek compile?

    Choose one answer.

    Show the answer: Question 13 of 13

    Answer: Yes, because a nested class is a member and has the same access as other members

    A nested class is a member of its enclosing class, so its functions may use the enclosing class's private members. The reverse needs a friend declaration: Outer has no special access to Inner's private members.

Interview questions

Fresher · How does a static member function differ from an ordinary member function?

An ordinary member function is called on an object and receives that object as this, so it can read and change the object’s data members. A static member function belongs to the class but runs without any object: it has no this, so it can use only static members, its parameters and whatever objects it creates, and it is called as Class::function(). It still has the class’s access rights, so it may call private constructors, which makes it useful for named constructors such as Temperature::from_celsius() and for counters kept in static data members. A static member function cannot be virtual, const or volatile, because those qualifiers describe how a function treats the object it is called on.

An interviewer usually tests the answer on a design or two. Decide these three:

Checkpoint

Interview round: three follow-up questions

  1. Question 1 of 3 Follow-up: why give Temperature a private constructor and static functions such as from_celsius(), instead of a public constructor that takes a double?

    Choose one answer.

    Show the answer: Question 1 of 3

    Answer: Each function's name says which unit its argument is in, and the private constructor makes every Temperature go through them

    A named constructor is a static member function that may call the private constructor, which makes it the natural place for creation whose argument needs a name.

  2. Question 2 of 3 Follow-up: a reporting function needs a Wallet's balance, and Wallet already has a public balance() accessor. Should the function be a friend?

    Choose one answer.

    Show the answer: Question 2 of 3

    Answer: No; a function that can do its job through the public interface should be neither a member nor a friend

    Friends are for functions that need the representation but cannot be members, such as an operator whose left operand has another type, and for helpers designed with the class, such as an iterator.

  3. Question 3 of 3 Follow-up: C++14 code defines int Config::retries = 3; in the header, next to the class. What happens once two .cpp files include it?

    Choose one answer.

    Show the answer: Question 3 of 3

    Answer: The link fails with a duplicate symbol, because each file now defines the variable

    Before C++17 the definition belongs in exactly one .cpp file. With C++17, inline static int retries = 3; in the class avoids both the missing definition and the duplicate.

Two harder questions take these features into a large code base: operators that slow every build, and a static counter that hands out the same id twice:

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Mid to senior

    In a large code base, namespace app defines about 300 types, each with operator== and operator<< declared at namespace scope. Builds are slow, one failed comparison prints hundreds of lines of candidates, and two unrelated types once compared equal through an implicit conversion. Explain the common cause and how hidden friends address it.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    An IdGenerator hands out order ids with a static std::uint32_t counter and return ++counter_;. Under load, two orders occasionally get the same id. Explain why, fix it, say what your fix costs, and name what else could still give two orders the same id.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • A static data member exists once for the whole program and is not part of any object, so sizeof does not count it. Define it with inline static (C++17), or as static constexpr for a constant.
  • Without inline, a static data member needs exactly one definition outside the class, or the link fails.
  • A static member function has no this, uses only static members and the objects it is given or creates, and is called as Class::f().
  • Friendship is granted by the class and is not inherited, transitive or mutual; use it for operators and helper classes that need the representation.
  • A hidden friend, defined inside the class, is found only by argument-dependent lookup, so implicit conversions cannot drag unrelated types to it.
  • Nested types and member aliases such as value_type keep related names inside the class and let templates ask a class for its types.

Terms in this lesson

friend declaration
A declaration inside a class, such as friend bool f(const A&); or friend class B;, that lets that function or every member function of that class use the class's private members. Friendship is not inherited, transitive or mutual.
hidden friend
A friend function defined inside its class and declared nowhere else. Ordinary lookup does not find it; argument-dependent lookup does, and only when an argument has the class's type, so conversions cannot pull other types to it.
member type alias
A type alias declared inside a class, such as using value_type = Song;. Generic code reads it as typename Container::value_type, the convention every standard container follows.
named constructor
A static member function that creates and returns an object, such as Temperature::from_celsius(20), so that its name says what the argument means. The constructor it calls is often private.
static data member
A data member declared static: one variable for the whole program, shared by every object of the class and stored in none of them, so sizeof does not count it. Since C++17, inline static declares and defines it inside the class.
static member function
A member function declared static: it belongs to the class and runs without an object, so it has no this, can use only static members and the objects it is given or creates, and is called as Class::f().

Corrections

  • The diagram of the shared counter now shows c as the copy of b, with the passenger Dev, as the program makes it.
  • The section on nested types now says that typename is required in the declaration of best; since C++20 the return type may leave it out.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.