Answers

Question and Answer:

  Home  C++ Static Data

⟩ Explain the uses of static class data?

1. To provide access control mechanism to some shared resource used by all the objects of a class

2. To keep track of no of objects in existence of a particular class

Following example illustrates first case, to make use of static data member for access control:

#include <iostream>

using namespace std;

class MyClass

{

static int resource;

public:

int get_resource()

{

if (resource)

return 0;

else

{

resource = 1;

return 1;

}

}

void free_resource()

{

resource =0;

}

};

int MyClass::resource;

int main()

{

MyClass ob1, ob2;

if(ob1.get_resource())

cout <<”Resources with ob1”;

if(!ob2.get_resource())

cout <<”Resources denied to ob2”;

ob1.free_resource();

return 0;

}

Thus, the static member variable resource makes sure at a time only one object can access it.

Now, consider the second use: to keep track of no of objects:

#include <iostream>

using namespace std;

class MyClass

{

public:

static int cnt;

MyClass()

{

cnt++;

}

~MyClass()

{

cnt--;

}

};

void func()

{

MyClass temp;

cout << “No of Objects : “<< MyClass::cnt<<”n”;

}

int MyClass::cnt;

int main()

{

cout <<”Entered main()n”:

MyClass ob1;

cout << “No of Objects : “<< MyClass::cnt <<”n”;

MyClass ob2;

cout << “No of Objects : “<< MyClass::cnt<<”n”;

func();

cout << “No of Objects : “<< MyClass::cnt<<”n”;

return 0;

}

Output would be:

Entered main()

No of Objects: 1

No of Objects: 2

No of Objects: 3

No of Objects: 2

Thus, only one copy of static member variable cnt is maintained for all the objects created and its value is incremented or decremented whenever and object is created or destroyed.

 252 views

More Questions for you: