![]() |
VOOZH | about |
Static data members are class members declared using the static keyword. Unlike non-static members, a static data member belongs to the class itself, not to individual objects.
Characteristics of Static Data Members:
class ClassName {
static data_type data_member_name;
};
Static data members are useful for maintaining data shared among all instances of a class. The C++ Course explains how to implement static data members, ensuring you understand their significance in C++ programming.
Example: Below is the C++ program to demonstrate the working of static data members:
Accessing static data member: 2
Static data members are declared inside the class but must be defined outside the class. If a static data member is not explicitly defined, the compiler will generate an error.
1. Declaration inside the class
class GFG {
public:
static int count; // Declaration only
};
2.Definition outside the class
int GFG::count = 0; // Definition and Initialization (outside the class)
Note: The static data members are initialized at compile time so the definition of static members should be present before the compilation of the program
The C++ 17 introduced the inline definition of the static data members of type integral or enumeration which was not allowed in the previous standards. This simplifies the definition of the static data members.
Syntax
class A {
public:
static inline int x = 10;
};
This eliminates the need for a separate definition outside the class.
We can access the static data member without creating the instance of the class. Just remember that we need to initialize it beforehand. There are 2 ways of accessing static data members:
The class name and the scope resolution operator can be used to access the static data member even when there are no instances/objects of the class present in the scope.
Syntax
Class_Name :: var_name
Example:
A::x
We can also access the static data member using the objects of the class using dot operator.
Syntax
object_name . var_name
Example
obj.x
Note: The access to the static data member can be controlled by the class access modifiers.
The following example demonstrates:
Output
Static Object Created
accessing static member without creating the object: 11
A's Constructor Called
A's Constructor Called
Printing values from each object and classname
obj1.s.val: 11
obj2.s.val: 11
A::s.val: 11
Note: In C++, we cannot declare static data members in local classes.