The Situation:
A have two classes, one inheriting the other, and the parent class being abstract (I plan on adding more child classes in the future). For reasons I won't bother mentioning, I'm making use of an STL container as a way for me to access all of the child objects in the heap. I've done so by making use of a map, with key type
int
and value type being a pointer to the parent class:
1 2 3 4 5 6 7 8 9
|
//PARENT.H
class Parent
{
protected:
static int n;
static std::map<int, Parent*> map;
public:
virtual void pureVirtual() = 0;
}
|
1 2 3 4 5 6 7 8 9 10
|
//PARENT.CPP
//Initialize static int
int Parent::n = 0;
//Initialize static map
std::map<int, Parent*> Parent::map = std::make_pair(-1, new Child); //THIS IS WHERE PROBLEMS ARISE
Parent::Parent()
{
n++;
}
|
1 2 3 4 5 6 7
|
//CHILD.H
class Child : public Parent
{
public:
Child();
void pureVirtual();
}
|
1 2 3 4 5 6 7 8 9 10 11
|
//CHILD.CPP
Child::Child()
{
//Add this object to the static map
map[n] = this;
}
void Child::purevirtual()
{
//Does nothing
}
|
The Problem:
In line 5 of
Parent.cpp, initializing the value of the element to
new Child
won't work, as according to the compiler, the Child class hasn't been declared yet, and including
Child.h
into the
Parent.h
only opens an even bigger can of worms.
I also can't initialize it as
new Parent
, seeing as the parent class is an abstract one.
The Question:
Is there a way I can initialize the static map properly. Making the Parent class abstract is not an option. Neither is making the map not static, though if there are some alternative approaches to the situation, do let me know.