Static Methods and Data Members?

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

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
#include <iostream>
#include <string>
using namespace std;
class  B
{
private: 
	static int lifeCount;	//a static data member	
	static int deathCount;	//a static data member	
	const int size;			//a static data member
	char *x; 
public: 
	B();					//default constructor
	B(const int n);			//constrcutor with parameter
	void print();			//print A
	static void 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 = new char[size]; 
	strcpy(x, "I see a head initialization."); 
}
B::B(const int n): size(n)
{
	lifeCount++;			
	x = new char[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.
What do you mean by "control" it? Like only let the programmer make 10 objects before you reuse them or what?
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.
I got it, thanks.
Last edited on
Topic archived. No new replies allowed.