In the last few chapters every member we wrote belonged to an object. Each Student had its own rollNo, each Account had its own balance, and inside member functions the this pointer told us which object we were working on.
But some information does not belong to any single object. How many students have been created so far? What ID should the next account get? What is the maximum number of users the app allows? These facts belong to the class as a whole.
C++ handles this with static members. In this chapter you will learn static data members, static member functions, how they are stored, the C++17 inline static shortcut, and the classic mistakes (including the famous "undefined reference" linker error).
What Is a Static Member?
A static member is a member that belongs to the class itself, not to any individual object. There is exactly one copy of a static data member, shared by every object of the class, and it exists even if no object has been created.
Compare the two kinds of data members:
class Student { int rollNo; static int count; };
object a object b object c
+----------+ +----------+ +----------+
| rollNo=1 | | rollNo=2 | | rollNo=3 | ← one rollNo PER object
+----------+ +----------+ +----------+
Student::count = 3 ← ONE count for the whole class
(lives in static storage, outside all objects)
A normal (non-static) member is called an instance member because every instance gets its own copy. A static member is sometimes called a class member or class variable.
Static Data Members
A static data member needs two things in classic C++:
- A declaration inside the class, using the keyword
static. - A definition outside the class (in exactly one
.cppfile), which actually creates the storage. The keywordstaticis not repeated there.
Let's count how many Student objects have been created:
#include <iostream>
class Student {
public:
int rollNo;
static int count; // declaration: one copy shared by all objects
Student(int r) : rollNo(r) {
++count;
}
};
int Student::count = 0; // definition: storage is created here
int main() {
std::cout << "Before: " << Student::count << '\n';
Student a(1);
Student b(2);
Student c(3);
std::cout << "After: " << Student::count << '\n';
std::cout << "Via a: " << a.count << '\n';
std::cout << "sizeof(Student) = " << sizeof(Student) << '\n';
std::cout << "sizeof(int) = " << sizeof(int) << '\n';
}
Output:
Before: 0
After: 3
Via a: 3
sizeof(Student) = 4
sizeof(int) = 4
Notice four things:
Student::countwas usable before any object existed. Static data members have static storage duration: they live for the whole program, just like global variables (see Variables & Data Types).- Every constructor call incremented the same variable, so the final value is 3.
a.countalso works, but it is misleading becausecountdoes not belong toa. PreferStudent::count.sizeof(Student)is 4, the size ofrollNoalone. A static member is not stored inside the object, so it does not add to the object's size.
Why does the definition go outside the class?
A class definition usually lives in a header file that is included in many .cpp files. If the class body itself created storage for count, every .cpp file would create its own copy and the linker would see many variables with the same name. So, traditionally, the class only declares the static member and exactly one .cpp file defines it. This is part of the One Definition Rule (ODR).
Initializing Static Members Inside the Class
Writing a separate definition is tedious, so C++ gradually added shortcuts:
| Form | Allowed since | Out-of-class definition needed? |
|---|---|---|
static int count; + int Student::count = 0; | C++98 | Yes (exactly one) |
static const int max = 100; (integral or enum type only) | C++98 | Only if it is odr-used (e.g. its address is taken). Since C++17 you can simply write inline or use constexpr instead. |
static constexpr double pi = 3.14159; | C++11 | No, since C++17 (a static constexpr data member is implicitly inline) |
inline static int count = 0; | C++17 | No |
#include <iostream>
#include <string>
class Config {
public:
static const int maxUsers = 100; // OK since C++98: const integral
static constexpr double pi = 3.14159; // C++11; implicitly inline in C++17
inline static std::string appName = "CSLP"; // C++17: inline static member
inline static int instances = 0; // C++17: no out-of-class definition needed
};
int main() {
std::cout << Config::maxUsers << '\n';
std::cout << Config::pi << '\n';
std::cout << Config::appName << '\n';
++Config::instances;
std::cout << Config::instances << '\n';
}
Output:
100
3.14159
CSLP
1
An inline variable (C++17) may appear in many translation units, and the linker merges them into one object. That is exactly what we want for a static member defined in a header. In modern code, inline static is the simplest choice for non-constant static members, and static constexpr for constants.
The "Undefined Reference" Error
If you declare a non-inline static data member but never define it, the program still compiles; the error only appears at link time, when the linker looks for the storage:
#include <iostream>
class Counter {
public:
static int count; // declared, but never defined
};
void print(const int& x) { std::cout << x << '\n'; }
int main() {
print(Counter::count); // binding a reference odr-uses count
}
Result (g++ 15, abridged):
s3.cpp:(.text+0x42): undefined reference to `Counter::count'
collect2: error: ld returned 1 exit status
The fix is either to add int Counter::count = 0; in one .cpp file, or to declare the member as inline static int count = 0; (C++17).
Static Member Functions
A function can be static too. A static member function belongs to the class, so you can call it without any object: ClassName::function().
Because it is not called on an object, a static member function has no this pointer (recall The this Pointer chapter). That single fact explains all its rules:
- It can directly access only static members (data and functions) of its class.
- It cannot directly access non-static members, because there is no object to take them from.
- It cannot be declared
const(aconstmember function promises not to change*this, and there is no*this). It also cannot bevirtual. - It still has full access to
privatemembers of the class, including private members of any object you pass to it.
Here is an ID generator. The next ID is private, shared, and read through a static function:
#include <iostream>
#include <string>
#include <utility>
class Account {
std::string owner;
int id;
inline static int nextId = 1001; // private, shared
public:
explicit Account(std::string name) : owner(std::move(name)), id(nextId++) {}
void show() const {
std::cout << id << " -> " << owner << '\n';
}
static int peekNextId() { // static member function: no 'this'
return nextId;
}
};
int main() {
std::cout << "Next id: " << Account::peekNextId() << '\n';
Account a("Asha");
Account b("Ravi");
Account c("Meera");
a.show();
b.show();
c.show();
std::cout << "Next id: " << Account::peekNextId() << '\n';
}
Output:
Next id: 1001
1001 -> Asha
1002 -> Ravi
1003 -> Meera
Next id: 1004
Step by step: nextId starts at 1001. Each constructor stores the current value in its own id and then increments the shared counter (nextId++ is post-increment, so the old value is used). After three accounts, nextId is 1004.
What a static function cannot do
class Student {
int marks = 0;
static int total;
public:
static void show() {
marks = 10; // error: no object, so whose marks?
this->marks = 10; // error: no 'this' in a static function
}
};
Compiler errors (g++ 15, abridged):
s5.cpp:6:9: error: invalid use of member ‘Student::marks’ in static member function
s5.cpp:7:9: error: ‘this’ is unavailable for static member functions
A static function can still work with objects you give it
"No this" does not mean "no access to objects". A static function can receive objects as parameters and, being a member, can read their private data. This is common for factory functions and helpers that combine two objects:
#include <iostream>
class Point {
int x, y;
public:
Point(int x, int y) : x(x), y(y) {}
// static factory: can read private members of any Point it is given
static Point midpoint(const Point& a, const Point& b) {
return Point((a.x + b.x) / 2, (a.y + b.y) / 2);
}
void print() const { std::cout << '(' << x << ", " << y << ")\n"; }
};
int main() {
Point p(2, 4), q(8, 10);
Point m = Point::midpoint(p, q);
m.print();
}
Output:
(5, 7)
Static vs Non-Static Members
| Feature | Non-static (instance) member | Static (class) member |
|---|---|---|
| Number of copies | One per object | One per class |
| Stored | Inside each object | In static storage, outside objects |
Counts towards sizeof(object) | Yes | No |
| Lifetime | Same as the object | Whole program |
| Access syntax | obj.member, ptr->member | Class::member (object syntax also compiles) |
Functions: has this? | Yes | No |
Functions: can be const / virtual? | Yes | No |
| Functions: can access | Static and non-static members | Only static members directly |
Worked Example: Counting Live Objects Correctly
A popular interview exercise: "Keep track of how many objects of a class are alive right now." The obvious solution increments in the constructor and decrements in the destructor:
#include <iostream>
class Tracker {
inline static int alive = 0;
public:
Tracker() { ++alive; }
~Tracker() { --alive; }
static int liveCount() { return alive; }
};
int main() {
Tracker a;
{
Tracker b = a; // copy: uses the implicit copy constructor!
std::cout << "Inside block: " << Tracker::liveCount() << '\n';
}
std::cout << "After block: " << Tracker::liveCount() << '\n';
}
Output:
Inside block: 1
After block: 0
Both numbers are wrong! Inside the block there are two live objects (a and b), and after the block one object (a) is still alive. What happened?
Tracker b = a; does not call our default constructor. It calls the copy constructor, which the compiler generated for us (see Constructors & Destructors). The generated copy constructor knows nothing about alive, so it never increments it. But when b is destroyed, our destructor does decrement. The count drifts down.
The fix is to count in every constructor:
#include <iostream>
class Tracker {
inline static int alive = 0;
public:
Tracker() { ++alive; }
Tracker(const Tracker&) { ++alive; } // count copies too
~Tracker() { --alive; }
static int liveCount() { return alive; }
};
int main() {
Tracker a;
{
Tracker b = a;
std::cout << "Inside block: " << Tracker::liveCount() << '\n';
}
std::cout << "After block: " << Tracker::liveCount() << '\n';
}
Output:
Inside block: 2
After block: 1
Lesson: if a class keeps any bookkeeping in static members, every way of creating an object (default, parameterized, copy, and later move constructors) must update it.
Static Local Variables Inside Member Functions
A static local variable inside a function (member or not) is created the first time control passes through its declaration and lives until the program ends. Combined with a static member function, this gives the well-known Meyers singleton, a class with exactly one instance:
#include <iostream>
class Logger {
Logger() { std::cout << "Logger created\n"; }
public:
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
static Logger& instance() {
static Logger obj; // created on first call; thread-safe since C++11
return obj;
}
void log(const char* msg) { std::cout << "[log] " << msg << '\n'; }
};
int main() {
std::cout << "main starts\n";
Logger::instance().log("first");
Logger::instance().log("second");
std::cout << std::boolalpha
<< (&Logger::instance() == &Logger::instance()) << '\n';
}
Output:
main starts
Logger created
[log] first
[log] second
true
"Logger created" is printed after "main starts", proving the object is created lazily on first use. Since C++11 the initialization of a static local variable is guaranteed to happen exactly once even if several threads call instance() at the same time. The = delete lines forbid copying, so nobody can make a second Logger.
This pattern also avoids the static initialization order fiasco: the order in which global and static-member variables in different .cpp files are dynamically initialized is unspecified, so one such variable must not rely on another during its own initialization. A function-local static is initialized when first needed, which sidesteps the problem.
The Many Meanings of static
The keyword static is overloaded with several meanings in C++, which confuses many students:
| Where it appears | Meaning |
|---|---|
| Local variable inside a function | Static storage duration: keeps its value between calls; initialized once |
| Global variable or free function at namespace scope | Internal linkage: visible only inside that .cpp file |
| Data member of a class | One shared copy for the whole class |
| Member function of a class | Called without an object; has no this |
Note that a static data member has external linkage (if the class does): it is one variable for the whole program, not one per file. This is the opposite of a static global variable.
Common Mistakes
- Forgetting the definition of a non-inline static data member, which gives "undefined reference" at link time. Use
inline static(C++17) or add the definition in one.cpp. - Repeating
staticin the definition:static int Student::count = 0;is an error. Writeint Student::count = 0;. - Defining the static member in a header (without
inline) that is included by several files, which gives "multiple definition" at link time. - Using
thisor instance members inside a static function. - Trying to initialize a static member in the constructor's member initializer list. The initializer list initializes the object's own members; a static member is not part of the object. You may assign to it in the constructor body, but that runs once per object.
- Forgetting the copy constructor when counting objects, as shown above.
Interview / Exam Questions
1. Does a static data member increase the size of an object?
No. It is stored once, in static storage, outside every object. sizeof of the class counts only non-static data members (plus padding and any hidden pointers the implementation adds).
2. Why can't a static member function access non-static data members directly?
Because it has no this pointer. A non-static member exists separately in each object, and a static function is not called on any object, so the compiler has no way to know which object's member you mean. You can still pass an object as a parameter and use obj.member.
3. Can a static member function be const or virtual?
No. const on a member function qualifies *this, and virtual dispatch works through the object; a static function has neither.
4. What is printed?
class A { public: static int n; A() { n++; } }; int A::n = 5;
int main() { A x, y[3]; std::cout << A::n; }
9. One constructor call for x and three for the array elements: 5 + 4 = 9.
5. What does inline static do, and which standard introduced it?
C++17 inline variables. It lets you define and initialize a static data member inside the class body; all translation units that include the header refer to the same single variable, so no separate out-of-class definition is needed.
6. When is a static data member constructed?
It has static storage duration, so it exists for the whole program. If its initializer is a constant expression (like int count = 0), it is constant-initialized: the value is already in place before any code runs. Otherwise (for example a std::string or a value computed by a function call) it is dynamically initialized; with common compilers this happens before main starts, although the standard allows an implementation to delay it until just before something from that file is first used. Objects with a destructor are destroyed after main returns. A function-local static, in contrast, is initialized the first time control reaches its declaration.
Summary
- A static data member has one copy per class, shared by all objects, and lives for the entire program.
- Classic C++ needs a declaration in the class and one definition outside; C++17
inline staticandstatic constexprremove that need. - A static member function is called as
Class::f(), has nothis, can directly use only static members, and cannot beconstorvirtual. - Static members do not contribute to
sizeofof objects. - When counting objects, remember the copy constructor.
- A function-local
staticgives lazy, thread-safe (C++11) one-time initialization, the basis of the Meyers singleton.
Next, in Friend Functions & Classes, we will see how a class can grant a non-member function or another class access to its private members.