Static class members
Static class members in C++ refer to class-level variables or functions that are shared among all instances of the class, rather than being specific to each object. Static members are useful when you want to maintain a single shared state or behavior across all instances of a class.
1. Static Member Variables
A static member variable is shared across all instances of a class. Instead of each object having its own copy, only one copy of a static variable exists, regardless of the number of objects created. Static member variables are useful for maintaining information that is common to all instances, such as a counter to track how many objects have been created.
- Declaration: Declared within the class using the
static
keyword. - Initialization: Initialized outside the class definition, typically in the global scope. This ensures that only one instance of the static variable exists.
- Access: Accessed using either an object of the class or by the class name itself.
2. Static Member Functions
A static member function can access only static variables and other static functions within the class. It does not operate on specific instances and thus does not have access to the this
pointer, meaning it cannot directly access non-static members of the class.
- Declaration: Declared using the
static
keyword inside the class. - Access: Can be called using either an object or directly with the class name.
Explanation
- Static Variable (
count
): Keeps track of the number ofCounter
objects created. It is initialized to0
outside the class. - Static Function (
getCount
): Returns the current value ofcount
. Since it's static, it can be called without an object. - Constructor: Each time an object is created, the constructor increments the static
count
variable.
No comments:
Post a Comment