static
keyword
When a variable in a class is declared static
, space for it is allocated for the lifetime of the program.
- No matter how many objects of that class have been created, there is only one copy of the static member. So same static member can be accessed by all the objects of that class.
Tip
A static member function can be called even if no objects of the class exist and the static function are accessed using only the class name and the scope resolution operator
::
.
Actually, static
is also a feature in C.
When should you ever use static?
Depending on what scope you declare
static
, it will achieve different outcomes:
- Static member fields: Use
static
to share a variable among all objects of a class; it belongs to the class and not any specific object.- Static member methods: Apply to member functions that can be called on the class itself rather than on instances of the class.
- Static variable inside function: Declare a local variable as
static
to retain its value between function calls (ex: count number of function calls)- Static global functions and variables: Use
static
for global variables or functions to restrict their visibility to the current file.More on StackOverflow.
Static Variables depending on each other
How do static variables get created? This is something fundamental you should understand.
What about
static
vsconstexpr
?They have slightly different uses cases.
static
is more about visibility and sharing values amongst objects / functions calls
static
: Shares a variable among all instances of a class, retains value between function calls, or restricts visibility in the global scope. Can be modified after initialization.constexpr
: Used for values that are known at compile time and will never change. Enables compile-time evaluation of expressions, optimizing performance.
In OOP, a A member variable (field) can be either
- An instance variable (one per instance of the class), or
- A class/static variable (one per class, full stop, independent of instances)
A member method can be either
- An instance method (operates on the this object, can call other instance methods directly w/o going thru another object), or
- A class/static method
- No implied “special”
this
object - Can’t call instance methods directly inside a static method; need to go thru another object
- Can call static methods, touch static class variable directly
- Can access objects passed to it as a parameter
- No implied “special”
Example
Python Static Method
This article is super helpful: https://www.programiz.com/python-programming/methods/built-in/staticmethod