LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 11 of 27

Static and Friend Members

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

Static and Friend Members · Study material

Cache results in a function-local static

A static local container is created on the first call and shared by every later call, which makes it a simple, thread-safe-to-initialize cache for an expensive pure function.

#include <iostream>
#include <unordered_map>

class MathCache {
public:
    static long long fib(int n) {
        static std::unordered_map<int, long long> memo;   // shared by all calls, created on first use
        if (n < 2) return n;
        if (auto it = memo.find(n); it != memo.end()) return it->second;
        return memo[n] = fib(n - 1) + fib(n - 2);
    }
};

int main() {
    std::cout << MathCache::fib(50) << ' ' << MathCache::fib(60) << '\n';   // the second call reuses the cache
    return 0;
}

Output

12586269025 1548008755920

Write binary operators as hidden friends

class Rational {
    int n_, d_;
public:
    Rational(int n, int d = 1) : n_(n), d_(d) {}
    // Member: only r + 2 works, 2 + r does not compile
    // Rational operator+(const Rational& o) const;

    // Hidden friend: r + 2 and 2 + r both work, found by ADL only
    friend Rational operator+(const Rational& a, const Rational& b) {
        return {a.n_ * b.d_ + b.n_ * a.d_, a.d_ * b.d_};
    }
    friend bool operator==(const Rational&, const Rational&) = default;
};

Prefer static inline and static constexpr (C++17)

// Before C++17: declaration in the header …
class Limits { public: static int max_users; static const double ratio; };
// … and a definition in exactly one .cpp file, or the linker complains
int Limits::max_users = 100;
const double Limits::ratio = 0.75;

// C++17: everything in the header, no separate definition
class Limits {
public:
    static inline int max_users = 100;
    static constexpr double ratio = 0.75;
};

Count instances correctly

class Tracked {
    static inline int alive_ = 0;
public:
    Tracked()               { ++alive_; }
    Tracked(const Tracked&) { ++alive_; }   // copies are objects too!
    Tracked(Tracked&&)      { ++alive_; }   // and so are moved-into objects
    ~Tracked()              { --alive_; }
    static int alive()      { return alive_; }
};

Forgetting the copy and move constructors is the classic bug: the compiler-generated ones do not touch your counter, so the count drifts negative.

Good static and friend habits

  • Use static inline / static constexpr for class-level data.
  • Prefer function-local statics to global objects (no initialization-order problems).
  • Use static factory functions with expressive names instead of many constructor overloads.
  • Make symmetric operators and <</>> hidden friends.
  • Befriend the narrowest thing possible: one function rather than a whole class.
  • Avoid mutable global state behind singletons; pass dependencies explicitly where you can.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links