Static members in a class are elements (fields, methods, or nested classes) that belong to the class itself rather than to instances of the class. This means there is only one instance of the static member shared among all instances of the class.
Static members example in C++ language:
C++
class MyClass {
public:
// Static variable
static int staticVariable;
// Static method
static void staticMethod() {
cout<<"EasyExamNotes.com"
}
};
// Initialize the static variable (mandatory in C++)
int MyClass::staticVariable = 0;
In C++, you access static members using the class name or through an instance of the class:
C++
// Accessing static variable
int value = MyClass::staticVariable;
// Invoking static method
MyClass::staticMethod();
// Alternatively, through an instance (not recommended for static members)
MyClass obj;
int valueFromInstance = obj.staticVariable;
obj.staticMethod();