I'm a little stuck in another of Bruce Eckel's exercises. I'm given the following class "Framis" which sets aside a chunk of memory in the static data area for Framis objects, then uses an array of bytes to determine which blocks have been allocated. The new and delete operators are overloaded to utilize this allocation system:
Code:
class Framis {
enum { sz = 10 };
char c[sz]; // To take up space, not used
static unsigned char pool[];
static bool alloc_map[];
public:
enum { psize = 100 }; // frami allowed
Framis() { out << "Framis()\n"; }
~Framis() { out << "~Framis() ... "; }
void* operator new(size_t) throw(bad_alloc);
void operator delete(void*);
};
unsigned char Framis::pool[psize * sizeof(Framis)];
bool Framis::alloc_map[psize] = {false};
// Size is ignored -- assume a Framis object
void*
Framis::operator new(size_t) throw(bad_alloc) {
for(int i = 0; i < psize; i++)
if(!alloc_map[i]) {
out << "using block " << i << " ... ";
alloc_map[i] = true; // Mark it used
return pool + (i * sizeof(Framis));
}
out << "out of memory" << endl;
throw bad_alloc();
}
void Framis::operator delete(void* m) {
if(!m) return; // Check for null pointer
// Assume it was created in the pool
// Calculate which block number it is:
unsigned long block = (unsigned long)m
- (unsigned long)pool;
block /= sizeof(Framis);
out << "freeing block " << block << endl;
// Mark it free:
alloc_map[block] = false;
}
I realize that this allocation system will not work for a class derived from Framis, because it relies on the size of Framis for calculations. So the question wants me to inherit from Framis and do what's needed to make the allocation work for the derived class. I figure I have to override the new and delete functions in order to use the correct size for the derived class, but I'm stumped as to what to do about the storage itself, i.e. pool[] and alloc_map[]. As I understand it I cannot override static data members in the derived class. But the initialization of pool[] uses size_of(Framis) and besides, I'm guessing that the derived class really needs its own storage area that's separate. So what can I do?