Open In App

Memory Allocation in Static Data Members in C++

Last Updated : 14 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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 are initiated to zero when the first object of that class is created.
  • Static data members are visible only within the class but their lifetime is the entire program.

Relevance:
Static data members are usually used to maintain values that are common for the entire class. , For Example, to keep a track of how many objects of a particular class have been created.

Place of Storage:
Although static data members are declared inside a class, they are not considered to be a part of the objects. Consequently, their declaration in the class is not considered as their definition. A static data member is defined outside the class. This means that even though the static data member is declared in class scope, their definition persists in the entire file. A static member has file scope. However, since a static data member is declared inside the class, they can be accessed only by using the class name and the scope resolution operator.

Below is the program to illustrate memory allocation in static and non-static data members:

Program 1: to illustrate non-static members




// C++ program to illustrate
// non-static data members
using namespace std;
#include <iostream>
  
// Class
class GfG {
private:
    // Created a variable
    int count = 0;
  
public:
    // Member function to increment
    // value of count
    void set_count()
    {
        count++;
    }
  
    // Member function to access the
    // private members of this class
    void show_count()
    {
  
        // print the count variable
        cout << count << '\n';
    }
};
  
// Driver Code
int main()
{
    // Objects of class GfG
    GfG S1, S2, S3;
  
    // Set count variable to 1
    // for each object
    S1.set_count();
    S2.set_count();
    S3.set_count();
  
    // Function to display count
    // for each object
    S1.show_count();
    S2.show_count();
    S3.show_count();
  
    return 0;
}


Output:

1
1
1

Below is the illustration of memory allocation for the above program:

Explanation:
All three objects of class GfG S1, S2, and S3 share the member functions but have a separate copy of the data member count. In main(), the set_count() is explicitly called to set the value of count to 1. Now, each object has the value of its count = 1.

Program 2: to illustrate static members:




// C++ program to illustrate
// non-static data members
using namespace std;
#include <iostream>
  
// Class
class GfG {
private:
    // Created a static variable
    static int count;
  
public:
    // Member function to increment
    // value of count
    void set_count()
    {
        count++;
    }
  
    // Member function to access the
    // private members of this class
    void show_count()
    {
  
        // print the count variable
        cout << count << '\n';
    }
};
  
int GfG::count = 0;
  
// Driver Code
int main()
{
    // Objects of class GfG
    GfG S1, S2, S3;
  
    // Increment count variable
    // by 1 for each object
    S1.set_count();
    S2.set_count();
    S3.set_count();
  
    // Function to display count
    // for each object
    S1.show_count();
    S2.show_count();
    S3.show_count();
  
    return 0;
}


Output:

3
3
3

Below is the illustration of memory allocation for the above program:

Explanation:
All three objects of class GfG S1, S2, and S3 shares the member functions as well as the static data member. Only one copy of the static data member exists in the memory. There is no need for a function to explicitly set the value of count because the value of static data members has been initialized to 0 outside the class definition. Now, each object increments the value of count and hence the output.
Note: Memory for member functions and static data members is allocated per class and not per object. The class sample has no data member(except static count), but this does not mean no memory space will be allocated to the objects of Sample. In such cases, minimum memory is set aside for object. Therefore, the size of S1, S2, and S3 is 1 byte.



Similar Reads

Difference between Static and Dynamic Memory Allocation in C
Memory Allocation: Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space. The memory allocation is done either before or at the time of program execution. There are two types of memory allocations: Compile-time or Static Memory AllocationRun-time or Dynamic Memory Allocation Static
2 min read
C++ Static Data Members
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
4 min read
Implementation of all Partition Allocation Methods in Memory Management
Prerequisite: Partition Allocation Methods in Memory Management In Partition Allocation, when there is more than one partition freely available to accommodate a process request, a partition must be selected. To choose a particular partition, a partition allocation method is needed. A partition allocation method is considered better if it avoids int
15 min read
If memory allocation using new is failed in C++ then how it should be handled?
In this article, if memory allocation using new is failed in C++ then how it should be handled? When an object of a class is created dynamically using new operator, the object occupies memory in the heap. Below are the major thing that must be keep in mind: What if sufficient memory is not available in the heap memory, and how it should be handled?
3 min read
What is Dynamic Memory Allocation?
Resources are always a premium. We have strived to achieve better utilization of resources at all times; that is the premise of our progress. Related to this pursuit, is the concept of memory allocation.Memory has to be allocated to the variables that we create, so that actual variables can be brought to existence. Now there is a constraint as how
5 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
C++ Program to swap two members using Friend Function
Pre-requisite: Friend FunctionCASE 1: Given two numbers a &amp; b, swap these two numbers using the friend function of C++. Examples: Input : a = 5, b = 9 Output : a = 9, b = 5 Input : a = 4, b = 6 Output : a= 6, b = 4 Approach: Create a class Swap, declare three variables in it, i.e., a, b, and temp and create a constructor for inputs. Declare a f
3 min read
How to Create a Class with Private and Public Members in C++?
In C++, the classes are blueprints for creating objects with specific properties and methods that provide a feature of access specifiers to the user through which they can control the access of the data members present in a class. In this article, we will learn how to create a class with private and public members in C++. Define Private and Public
3 min read
Why Do I Have to Access Template Base Class Members Through the 'this' Pointer?
In C++, when we have a class template that inherits from a template base class, we need to explicitly use this pointer to access members of the base class. In this article, we will learn why it is necessary to access template base class members through 'this' pointer in C++. The Problem in Accessing Template Base Class Members Without this PointerW
3 min read
Practice Tags :