Learning Hub Search Ctrl K

Legacy C++ › 3. Classes and Object-Oriented Programming

friend, static Members and Nested Classes

Controlled access, class-wide data and helper types.

intermediate #friend#static-members#nested-classes#encapsulation

Explanation

friend grants a function or another class access to a class’s private members. Friendship is granted (not taken), is not inherited, and is not mutual. Use sparingly. Operators and tightly coupled helper classes are the usual cases.

static members belong to the class, not to any object:

  • a static data member exists once, is declared in the class and defined in exactly one .cpp file;
  • a static member function has no this and can only touch static members and its arguments.

A nested class is declared inside another class’s scope. It is a separate type, convenient for helper or implementation types.

Example

#include <iostream>

class Counter {
public:
    Counter() : secret_(42) { ++count_; }
    ~Counter() { --count_; }
    static int count() { return count_; }          // no object needed

    class Id {                                      // nested helper type
        int v_;
    public:
        explicit Id(int v) : v_(v) {}
        int value() const { return v_; }
    };

    friend void debugDump(const Counter&);          // non-member with private access
private:
    static int count_;                              // declaration
    int secret_;
};

int Counter::count_ = 0;                            // definition (once, in a .cpp)

void debugDump(const Counter& c) { std::cout << "secret=" << c.secret_ << "\n"; }

int main() {
    Counter a;
    {
        Counter b;
        std::cout << Counter::count() << "\n";      // 2
    }
    std::cout << Counter::count() << "\n";          // 1
    Counter::Id id(7);
    std::cout << id.value() << "\n";
    debugDump(a);
    return 0;
}

Common pitfalls

  • Forgetting the out-of-class definition of a static data member gives a linker error (“unresolved external”).
  • Too many friends erode encapsulation; if everything is a friend, redesign.
  • friend is not inherited: a friend of Base cannot access Derived’s privates.
  • Static members in headers across many translation units are initialized in unspecified order (see Scope, Storage Duration and Linkage).
  • Using a static data member to hold per-object state creates hidden shared state.

Legacy vs modern

C++11 allows in-class initialization of non-static members; C++17 adds inline static members, so no separate definition is needed.

Exercises

1. Can a static member function be const?

No. const qualifies this, and a static function has no this.