Static Variable

// Static.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>

using namespace std;

class cl
{
static int resource;
public:
int get_resource();
void free_resource() {resource = 0;}
};
int cl::resource; // define resource
int cl::get_resource()
{
if(resource) return 0; // resource already in use
else {
resource = 1;
return 1; // resource allocated to this object
}
};
class Static_ty
{
static int i;
public:
static void init(int a) {
i = a;
}
void show()
{
std::cout << i ;
}
};
int Static_ty::i;
int _tmain(int argc, _TCHAR* argv[])
{
Static_ty::init(100);

Static_ty obj;
obj.show();


cl ob1, ob2;
if(ob1.get_resource()) cout << "ob1 has resource\n";
if(!ob2.get_resource()) cout << "ob2 denied resource\n";
ob1.free_resource(); // let someone else use it
if(ob2.get_resource())
cout << "ob2 can now use resource\n";
return 0;
}

Comments

Popular posts from this blog

Smart Pointers in C++ and How to Use Them

Operator Overloading in C++

How would you read in a string of unknown length without risking buffer overflow