Alright, I'm having trouble trying to figure out how to control the number of objects created in a class using a Static Member.
For example if this is the code I'm working on
#include <iostream>
#include <string>
usingnamespace std;
class B
{
private:
staticint lifeCount; //a static data member
staticint deathCount; //a static data member
constint size; //a static data member
char *x;
public:
B(); //default constructor
B(constint n); //constrcutor with parameter
void print(); //print A
staticvoid printStatic();//a static method
~B(); //destructor
};
int B:: lifeCount=0;
int B:: deathCount=0;
B::B():size(100) //head initialization of size
{
lifeCount++; //increase by one
x = newchar[size];
strcpy(x, "I see a head initialization.");
}
B::B(constint n): size(n)
{
lifeCount++;
x = newchar[n];
if (n>50)
strcpy(x, "Another head initialization here.");
else
x[0]='\0';
}
B::~B()
{
deathCount++;
printStatic();
delete[] x;
}
void B::printStatic()
{
cout<<lifeCount<<" many class B objects have been created up to this point."<<endl;
cout<<deathCount<<" many class B objects have died up to this point."<<endl;
}
How would I control it to where only 10 class B objects are created and "die".
Any help appreciated. My professor pretty much rushed through this section because of midterms and I guess forgot to go over it again.
if B's constructors are public, there is no way to prevent more Bs from being created. You would have to make the ctors private and make some kind of factory function which will only create an object if < 10 have previously been created.