-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23staticdatamem.cpp
More file actions
48 lines (42 loc) · 1.38 KB
/
Copy path23staticdatamem.cpp
File metadata and controls
48 lines (42 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
using namespace std;
// While we use static variable in a class, it retains it's value and is shared among objects, i.e. all objects will have same static variable
class Employee
{
int ID;
static int count; // A static variable, also called class variable is already initialized by 0 and there is no need to manually initialize
public:
void getData()
{
cout << endl
<< "Enter the Employee ID " << endl;
cin >> ID;
count++;
}
void setData()
{
cout << endl
<< "Employee " << count << " ID : [ " << ID << " ]" << endl;
}
static void countdisplay() // this is a static function which only accesses the static variables
{
cout << count << endl;
}
};
int Employee ::count; // this is to initialize a static variable, defining its scope
int main()
{
Employee Vasu, Dev, Aenansh;
Vasu.getData();
Vasu.setData();
Employee ::countdisplay(); // this scope doesn't require any object
Dev.getData();
Dev.setData();
Employee ::countdisplay();
Aenansh.getData();
Aenansh.setData();
Employee ::countdisplay();
/*without static variable, we need to initialize count with 0 then everytime we call a class function for each objects, the count
will be initialized by 0 instead of the incrementation from previous object function call */
return 0;
}