I have an abstract base class called Base
that other programmers are to write implementations for. In some other part of the application, I want to catch all implementations that have been written and construct a single instance of each. If this could be done with no additional instructions to others beyond "implement Base", that would be beautiful. However, the code I have below, requires that each implementation register itself. It also doesn't work.
#include <iostream>
#include <vector>
class Base;
std::vector<Base*>* registrationList = new std::vector<Base*>;
class Base {
public:
Base(){}
virtual void execute() = 0;
};
class ImplementationOne: public Base {
public:
ImplementationOne(){registrationList->push_back(this);}
void execute(){std::cout << "Implementation One." << std::endl;}
static int ID;
};
class ImplementationTwo: public Base {
public:
ImplementationTwo(){registrationList->push_back(this);}
void execute(){std::cout << "Implementation Two." << std::endl;}
static int ID;
};
int main(int argc, const char * argv[]){
std::cout << "Registration List size: " << registrationList->size() << std::endl;
for(auto it = registrationList->begin() ; it != registrationList->end() ; ++it){
(dynamic_cast<Base*>(*it))->execute();
}
return 0;
}
I get an output of: Registration List size: 0
, so it is clear that the implementations were never instantiated. It is probably obvious that this wouldn't happen, but I am a beginner and this is the best I could come up with. I assumed that static int ID;
would force instantiation of each implementation, which would then register themselves. I can see static
does not result in instantiation. I leave it in my code here since it shows my intent.
What can I do to get automatic instantiation of each implementation? Is it possible?