Classes and objects · core
static members and static locals
static means one copy with a long life. A static data member is shared by every object of the class, and a static local variable keeps its value between calls.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- A static data member has one copy for the whole class, shared by all objects. It is not stored inside each object.
- Declare it in the class and define it once outside:
int Student::count = 0;. Since C++17 you can writeinline static int count = 0;inside the class instead. - A static member function belongs to the class, not to an object. It has no this, so it cannot use non-static members directly. Call it as Student::getCount().
- Good uses: counting the objects created (count++ in the constructor), shared constants, and helper functions that need no object.
- Bug:
static string name;in Student. Every new student overwrites the one shared name, so all students show the last name. Make it a normal member. - A static local variable is initialised once, the first time the code reaches it, and keeps its value between calls. A normal local is created again on every call.
- Globals and statics start at zero when not initialised. An uninitialised normal local holds an unknown value, and reading it is undefined.
- static on a global variable or function makes it visible only inside its own .cpp file.
The red pen
Common traps: mistake → fix
Mistake: static means constant
Fix: it means one shared copy with a long life; const means it cannot change.
Mistake: Each object has its own copy of a static member
Fix: there is one copy for the class.
Mistake: A static member function can use this
Fix: it has no this.
Mistake: A static local goes back to its first value on every call
Fix: it is initialised once.
Easy to hard
Questions interviewers ask, easy to hard
- What does static mean on a class member? Give an example.
- Every student in your list shows the same name. What could cause it?
- Can a static member function use a non-static member? Why not?
- What does this function with a static counter and a normal counter print when called three times?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.