The Wayback Machine - https://web.archive.org/web/20240824164410/https://www.geeksforgeeks.org/cpp-static-data-members/
Open In App

C++ Static Data Members

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Static data members are class members that are declared using static keywords. A static member has certain special characteristics which are as follows:

  • Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.
  • It is initialized before any object of this class is created, even before the main starts outside the class itself.
  • It is visible can be controlled with the class access specifiers.
  • Its lifetime is the entire program.

Syntax

className {
     static data_type data_member_name;
     .....
}

Example

Below is the C++ program to demonstrate the working of static data members:

C++
// C++ Program to demonstrate the use of
// static data members
#include <iostream>
using namespace std;

// class definition
class A {
public:
    // static data member here
    static int x;
    A() { cout << "A's constructor called " << endl; }
};

// we cannot initialize the static data member inside the
// class due to class rules and the fact that we cannot
// assign it a value using constructor
int A::x = 2;

// Driver code
int main()
{
    // accessing the static data member using scope
    // resultion operator
    cout << "Accessing static data member: " << A::x
         << endl;

    return 0;
}

Output
Accessing static data member: 2

Defining Static Data Member

As told earlier, the static members are only declared in the class declaration. If we try to access the static data member without an explicit definition, the compiler will give an error.

To access the static data member of any class we have to define it first and static data members are defined outside the class definition. The only exception to this are static const data members of integral type which can be initialized in the class declaration.

Syntax

datatype class_name::var_name = value...;

For example, in the above program, we have initialized the static data member using the following statement:

int A::x = 10

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

Inline Definition of Static Data Member since C++ 17

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

// inside class definition
...
static inline data_type var_name = value/expression;
....

Accessing a Static Member

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:

1. Accessing static data member using Class Name and Scope Resolution Operator

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

2. Accessing static data member through Objects

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.

Example to Verify the Properties of the Static Data Members

The below example verifies the properties of the static data member that are told above:

C++
// C++ Program to demonstrate
// the working of static data member
#include <iostream>
using namespace std;

// creating a dummy class to define the static data member
// it will inform when its type of the object will be
// created
class stMember {
public:
    int val;
    // constructor to inform when the instance is created
    stMember(int v = 10): val(v) {
        cout << "Static Object Created" << endl;
    }
};

// creating a demo class with static data member of type
// stMember
class A {
public:
    // static data member
    static stMember s;
    A() { cout << "A's Constructor Called " << endl; }
};

stMember A::s = stMember(11);

// Driver code
int main()
{

    // Statement 1: accessing static member without creating
    // the object
    cout << "accessing static member without creating the "
            "object: ";
    // this verifies the independency of the static data
    // member from the instances
    cout << A::s.val << endl;
    cout << endl;

    // Statement 2: Creating a single object to verify if
    // the seperate instance will be created for each object
    cout << "Creating object now: ";
    A obj1;
    cout << endl;

    // Statement 3: Creating multiple objects to verify that
    // each object will refer the same static member
    cout << "Creating object now: ";
    A obj2;
    cout << "Printing values from each object and classname"
         << endl;

    cout << "obj1.s.val: " << obj1.s.val << endl;
    cout << "obj2.s.val: " << obj2.s.val << endl;
    cout << "A::s.val: " << A::s.val << endl;

    return 0;
}


Output

Static Object Created
accessing static member without creating the object: 11

Creating object now: A's Constructor Called 

Creating object now: 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.

Static Data Member in C++ – FAQs

Can static data members be private?

Yes, static data members can be private. They follow the same access control rules as regular data members and can be accessed through public member functions of the class.

Can we initialize a static data member within the class definition?

No, static data members must be defined outside the class definition. However, they can be initialized inline if they are of integral or enumeration type (C++17 onwards).

Can we inherit static data members ?

Static data members are class-specific and cannot be inherited. But we can access the static data member in the derived class directly using variable name

Can we have static member functions in a class?

Yes, static member functions can be defined in a class. They can access static data members but cannot access non-static data members or this pointer.



Previous Article
Next Article

Similar Reads

Memory Allocation in Static Data Members in C++
C++ allows defining static data members within a class using the static keyword. When a data member is declared as static, then we must keep the following note in mind: Irrespective of the number of objects created, only a single copy of the static member is created in memory. All objects of a class share the static member. All static data members
4 min read
Difference between static and non-static method in Java
A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. Every method in java defaults to a non-static method without static keyword preceding it. Non-static methods can access any static method and static variable, without cr
6 min read
Difference between static and non-static variables in Java
There are three types of variables in Java: Local VariablesInstance VariablesStatic Variables The Local variables and Instance variables are together called Non-Static variables. Hence it can also be said that the Java variables can be divided into 2 categories: Static Variables: When a variable is declared as static, then a single copy of the vari
4 min read
Internal static variable vs. External static variable with Examples in C
The static variable may be internal or external depending on the place of declaration. Both kinds of static variables are stored in initialized data segments. Internal Static Variables Internal Static variables are defined as those having static variables which are declared inside a function and extend up to the end of the particular function. Synt
2 min read
Why non-static variable cannot be referenced from a static method in Java
Java is one of the most popular and widely used programming language and platform. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In java, methods can be declared as either static or non-static. In this article, let's discuss why non-static vari
4 min read
Class Loading and Static Blocks Execution Using Static Modifier in Java
Static is a keyword which when attached to the method, variable, Block makes it Class method, class variable, and class Block. You can call a static variable/method using ClassName. JVM executes the static block at “CLASS LOADING TIME” Execution Order: There is an order in which static block/method/variable gets initialized. Static BlockStatic Vari
3 min read
Understanding storage of static methods and static variables in Java
In every programming language, memory is a vital resource and is also scarce. Hence the memory must be managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. In this article, we will understand the storage of static methods and static variables in Java. Java Virtu
6 min read
Initialization of data members
In C++, class variables are initialized in the same order as they appear in the class declaration. Consider the below code. #include&lt;iostream&gt; using namespace std; class Test { private: int y; int x; public: Test() : x(10), y(x + 10) {} void print(); }; void Test::print() { cout&lt;&lt;&quot;x = &quot;&lt;&lt;x&lt;&lt;&quot; y = &quot;&lt;
1 min read
Can We Access Private Data Members of a Class without using a Member or a Friend Function in C++?
The idea of Encapsulation is to bundle data and methods (that work on the data) together and restrict access of private data members outside the class. In C++, a friend function or friend class can also access private data members. So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers. Altho
3 min read
Comparison of static keyword in C++ and Java
Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. Similarities between C++ and Java for Static KeywordStatic data members can be defined in both languages.Static member functions can be defined in both languages
6 min read
Static Objects in C++
Prerequisite: Static Keyword in C++ An object becomes static when a static keyword is used in its declaration. Static objects are initialized only once and live until the program terminates. They are allocated storage in the data segment or BSS segment of the memory. C++ supports two types of static objects: Local Static ObjectsGlobal Static Object
3 min read
C++ | Static Keyword | Question 1
Predict the output of following C++ program. #include &lt;iostream&gt; using namespace std; class Test { static int x; public: Test() { x++; } static int getX() {return x;} }; int Test::x = 0; int main() { cout &lt;&lt; Test::getX() &lt;&lt; &quot; &quot;; Test t[5]; cout &lt;&lt; Test::getX(); } (A) 0 0 (B) 5 5 (C) 0 5 (D) Compiler Error Answer: (
1 min read
C++ | Static Keyword | Question 2
#include &lt;iostream&gt; using namespace std; class Player { private: int id; static int next_id; public: int getID() { return id; } Player() { id = next_id++; } }; int Player::next_id = 1; int main() { Player p1; Player p2; Player p3; cout &lt;&lt; p1.getID() &lt;&lt; &quot; &quot;; cout &lt;&lt; p2.getID() &lt;&lt; &quot; &quot;; cout &lt;&lt; p
1 min read
C++ | Static Keyword | Question 3
Which of the following is true? (A) Static methods cannot be overloaded. (B) Static data members can only be accessed by static methods. (C) Non-static data members can be accessed by static methods. (D) Static methods can only access static members (data and methods) Answer: (D) Explanation: A static function is a special type of function which is
1 min read
C++ | Static Keyword | Question 4
Predict the output of following C++ program. #include &lt;iostream&gt; using namespace std; class A { private: int x; public: A(int _x) { x = _x; } int get() { return x; } }; class B { static A a; public: static int get() { return a.get(); } }; int main(void) { B b; cout &lt;&lt; b.get(); return 0; } (A) 0 (B) Linker Error: Undefined reference B::a
1 min read
C++ | Static Keyword | Question 5
#include&lt;iostream&gt; using namespace std; class Test { private: static int count; public: Test&amp; fun(); }; int Test::count = 0; Test&amp; Test::fun() { Test::count++; cout &lt;&lt; Test::count &lt;&lt; &quot; &quot;; return *this; } int main() { Test t; t.fun().fun().fun().fun(); return 0; } (A) Compiler Error (B) 4 4 4 4 (C) 1 1 1 1 (D) 1 2
1 min read
C++ | Static Keyword | Question 6
Output of following C++ program? #include &lt;iostream&gt; class Test { public: void fun(); }; static void Test::fun() { std::cout&lt;&lt;&quot;fun() is static\n&quot;; } int main() { Test::fun(); return 0; } Contributed by Pravasi Meet (A) fun() is static (B) Empty Screen (C) Compiler Error Answer: (C) Explanation: The above program fails in compi
1 min read
Count the number of objects using Static member function
Prerequisite : Static variables , Static Functions Write a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class. Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member fun
2 min read
Static method in Interface in Java
Static Methods in Interface are those methods, which are defined in the interface with the keyword static. Unlike other methods in Interface, these static methods contain the complete definition of the function and since the definition is complete and the method is static, therefore these methods cannot be overridden or changed in the implementatio
2 min read
“static const” vs “#define” vs “enum”
In this article, we will be analyzing "static const", "#define" and "enum". These three are often confusing and choosing which one to use can sometimes be a difficult task. static const static const : "static const" is basically a combination of static(a storage specifier) and const(a type qualifier). Static : determines the lifetime and visibility
4 min read
Why can't static methods be abstract in Java?
In Java, a static method cannot be abstract. Doing so will cause compilation errors.Example: Java Code // Java program to demonstrate // abstract static method import java.io.*; // super-class A abstract class A { // abstract static method func // it has no body abstract static void func(); } // subclass class B class B extends A { // class B must
3 min read
Initialize a static map in Java with Examples
In this article, a static map is created and initialized in Java. A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Method 1: Creating a static map variable. Instantiating it in a static block. Below is the implementation of the above approach: // Java program to creat
1 min read
Initialize a static Map using Java 9 Map.of()
In this article, a static map is created and initialised in Java using Java 9. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Java 9 feature - Map.of() method In Java 9, Map.of() was introduced which is a convenient way to create instances of Map
2 min read
Initialize a static Map in Java using Double Brace Initialization
In this article, a static map is created and initialised in Java using Double Brace Initialization. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Double Brace Initialization In Double Brace Initialization: The first brace creates a new Anonymous
2 min read
Difference between Static and Friend Function in C++
Static Function: It is basically a member function that can be called even when the object of the class is not initialized. These functions are associated with any object and are used to maintain a single copy of the class member function across different objects of the class. This function is denoted by using the static keyword. Friend Function: I
3 min read
Static Member Function in C++
The static keyword is used with a variable to make the memory of the variable static once a static variable is declared its memory can't be changed. To know more about static keywords refer to the article static Keyword in C++. Static Member in C++ Static members of a class are not associated with the objects of the class. Just like a static variab
4 min read
Static Keyword in C++
Prerequisite: Static variables in C The static keyword has different meanings when used with different types. We can use static keywords with: Static Variables: Variables in a function, Variables in a classStatic Members of Class: Class objects and Functions in a class Let us now look at each one of these uses of static in detail.Static Variables S
5 min read
Can Static Functions Be Virtual in C++?
In C++, a static member function of a class cannot be virtual. Virtual functions are invoked when you have a pointer or reference to an instance of a class. Static functions aren't tied to the instance of a class but they are tied to the class. C++ doesn't have pointers-to-class, so there is no scenario in which you could invoke a static function v
1 min read
Templates and Static variables in C++
Function templates and static variables: Each instantiation of function template has its own copy of local static variables. For example, in the following program there are two instances: void fun(int ) and void fun(double ). So two copies of static variable i exist. #include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; void fu
2 min read
Some interesting facts about static member functions in C++
1) static member functions do not have this pointer. For example following program fails in compilation with error "`this' is unavailable for static member functions " C/C++ Code #include&lt;iostream&gt; class Test { static Test * fun() { return this; // compiler error } }; int main() { getchar(); return 0; } 2) A static member function cannot be v
1 min read
Practice Tags :