Given all that I hear about the problems with global variables, is it possible to declare a windows CRITICAL_SECTION object as a member of a base class that will not be created for each derived class? I want to implement an instance counter that is threadsafe, so I thought about this and the best I can come up with, at the moment, is the following:
class mammal
{
protected:
int myCount;
CRITICAL_SECTION myCS;
public:
mammal();
~mammal();
virtual void Increment()=0;
virtual void Decrement()=0;
virtual void GetCount(int& myVal)=0;
virtual void walk()=0;
//. more mammal functions here
//.
//.
};
mammal::mammal()
{
myCount = 0;
InitializeCriticalSection(myCS);
}
mammal::~mammal()
{
DeleteCriticalSection(myCS);
}
class dog: virtual public mammal
{
public:
dog();
~dog();
void Increment();
void Decrement();
void Getcount(int& myVal);
void walk();
// more mammal functions
//
//
};
dog::dog()
{
Increment();
}
dog::~dog()
{
Decrement();
}
void dog::Increment()
{
EnterCriticalSection(myCS);
myCount++;
LeaveCriticalSection(myCS);
}
void dog::Decrement()
{
EnterCriticalSection(myCS);
myCount--;
LeaveCriticalSection(myCS);
}
int dog::GetCount(int& myVal)
{
EnterCriticalSection(myCS);
myVal = myCount;
LeaveCriticalSection(myCS);
}
Does this look like a reasonable way to implement CRITICAL_SECTION without making it a global?