Memory Allocation in static data member in C++
In the language C++, we can create various data members using a class that is applicable to each object we create. The data members are initialized to their default value once an object of the class is created.
Some of the things to know about static keyword is-
- If the data member of the class if initiated with a static keyword then the memory allocation of that data member remains throughout the lifetime of the program.
- By default, the static data member is initialized with “0” once the first object of the class is created.
- Only a single copy of the static member is created throughout the whole program, unlike other data members.
An example of a program without a static keyword is shown below-
#include<iostream> using namespace std; class example{ private: int num=0; public: //function to increase the value of num by 1. void add(){ num++; } //function to display the value of num void display(){ cout<<num<<endl; } }; int main(){ //creating three objects of the class example example e1; example e2; example e3; //calling the add function e1.add(); e2.add(); e3.add(); //calling the display function e1.display(); e2.display(); e3.display(); return 0; }
Now here num is not declared as static therefore a new copy of num is made every time a new object is made of the class example. The output of the above code is as given below.
output: 1 1 1
An example of a program when we use the static keyword is as shown-
#include<iostream> using namespace std; class example{ private: static int num; public: void add(){ num++; } void display(){ cout<<num<<endl; } }; int example:: num=0; int main(){ example e1; example e2; example e3; e1.add(); e2.add(); e3.add(); e1.display(); e2.display(); e3.display(); return 0; }
Here the num data member is given the static keyword. Which makes our output like –
output: 3 3 3
This happened as when we declared num as static, only one copy of num was created for all of our three objects. Therefore when we called the add function num was increased and its value was stored until the program ended.
You may want to give a look to the following links also,
Leave a Reply