Hi,
I've run into the following problem: I have a very simple base class:
Code:
class Base
{
public:
virtual const char *name() = 0;
virtual void whatever() = 0;
// ...
};
And a few derived classes, each one having exactly one instance:
Code:
class D1
{
public:
virtual const char *name() {
return "d1";
}
};
D1 the_d1;
class D2
{
public:
virtual const char *name() {
return "d2";
}
};
D2 the_d2;
And a std::map:
Code:
std::map<std::string, Base *> objects;
That gets filled and queried with these:
Code:
void add_object(Base &b) {
objects.insert(b.name(), &b);
}
Base *get_object(const char *name) {
iterator it = objects.find(name);
if(it != objects.end()) {
return it->second;
} else {
return 0;
}
}
OK. Now I want these global objects to register themselves in the map. Easy. Just do so in the constructors:
Code:
D1::D1() {
add_object(*this);
}
D2::D2() {
add_object(*this);
}
Only, I don't want to repeat the code that often. So the obvious idea is to put the code into the base constructor:
Code:
Base::Base() {
add_object(*this);
}
Only, this doesn't work. I can't call a virtual function from the base constructor because the vtable is not yet initialized.
So, I'm basically looking for a workaround for that. I want my global objects to register themselves in the map without having to put code in each and every constructor. Is this possible?
Edit: OK, now I wrote a wrapper to do the registering and that works. I wonder if there's a more elegant way...