Lesson 4 of 7
static Members & Functions
A `static` data member belongs to the **class**, not to any instance. All instances share the same static member. A `static` member function can only access static members - it has no `this` pointer. Use static members for: instance counting, singletons, class-level constants (though `constexpr static` is preferred), and factory methods.
static Data Members, static Functions & Singleton
#include <iostream>
#include <string>
#include <stdexcept>
class Connection {
static int active_count_; // declaration (not definition)
static int max_connections_;
int id_;
std::string host_;
public:
// ── static function - factory method ─────────────────────
static Connection* create(const std::string& host) {
if (active_count_ >= max_connections_) {
throw std::runtime_error("Max connections reached");
}
return new Connection(host); // uses private constructor
}
// ── static getter ─────────────────────────────────────────
static int active_count() { return active_count_; }
static int max_connections() { return max_connections_; }
static void set_max(int n) { max_connections_ = n; }
int id() const { return id_; }
const std::string& host() const { return host_; }
~Connection() {
--active_count_;
std::cout << "Connection " << id_ << " closed
";
}
private:
// Private constructor - enforce creation via factory
explicit Connection(const std::string& host)
: id_(++active_count_), host_(host)
{
std::cout << "Connection " << id_ << " opened to " << host_ << "
";
}
};
// ── Out-of-class definition of static members ────────────────
// (required for non-inline/non-constexpr static data members)
int Connection::active_count_ = 0;
int Connection::max_connections_ = 3;
// ── constexpr static - preferred for compile-time constants ──
class Config {
public:
static constexpr int VERSION = 2;
static constexpr double TIMEOUT_S = 30.0;
static constexpr const char* APP_NAME = "MyApp";
// These ARE their definition (no out-of-class def needed in C++17)
};
int main() {
std::cout << "Max: " << Connection::max_connections() << "
"; // 3
std::cout << "Active: " << Connection::active_count() << "
"; // 0
Connection* c1 = Connection::create("db.example.com");
Connection* c2 = Connection::create("cache.example.com");
std::cout << "Active: " << Connection::active_count() << "
"; // 2
delete c1; // ~Connection: active_count_ decremented
std::cout << "Active: " << Connection::active_count() << "
"; // 1
delete c2;
std::cout << "Config v" << Config::VERSION
<< " app=" << Config::APP_NAME << "
";
return 0;
}Common Mistakes
- Forgetting out-of-class definition of static data members (pre-C++17) - `static int count;` in the class is a **declaration**. You need `int MyClass::count = 0;` in exactly one .cpp file. Missing this gives 'undefined reference'. In C++17, `inline static int count = 0;` can be defined in the header.
- Calling instance methods from a static function - static functions have no `this`. You cannot call `host()` from `Connection::create` on an implicit instance. You can call static methods or work with explicit pointers.
- Singleton abuse - overusing static/singleton makes code untestable (global state). Use Dependency Injection (pass the object as a constructor argument) when possible. Reserve singletons for logging, configuration, or connection pools.
Tip
Tip
Practice static Members Functions in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Class-Level Shared State in Static Data Segment vs Per-Instance Heap/Stack State
Practice Task
Note
Practice Task - (1) Write a working example of static Members Functions from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with static Members Functions is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- A `static` data member belongs to the **class**, not to any instance.
- Forgetting out-of-class definition of static data members (pre-C++17) - `static int count;` in the class is a **declaration**. You need `int MyClass::count = 0;` in exactly one .cpp file. Missing this gives 'undefined reference'. In C++17, `inline static int count = 0;` can be defined in the header.
- Calling instance methods from a static function - static functions have no `this`. You cannot call `host()` from `Connection::create` on an implicit instance. You can call static methods or work with explicit pointers.
- Singleton abuse - overusing static/singleton makes code untestable (global state). Use Dependency Injection (pass the object as a constructor argument) when possible. Reserve singletons for logging, configuration, or connection pools.
Finished this lesson?