views:

125

answers:

1

I would like to call a static method from a class that I'll determine at run-time, but which I know subclasses a given class. So let's say I have these classes

class super {
    public:
    super();
    static super *loadMe (ifstream &is);
}

class subA : public super {
   public:
   subA();
   static super *loadMe (ifstream &is);
}

class subB : public super {
   public:
   static super *loadMe (ifstream &is);
   private:
   subB();
}

And let's say I want to determine at run-time (based on what's in the file) whether to load a subA or subB next. One way I could do this would be to use an empty object to invoke the method

super getLoadType (ifstream &is) { if(complicatedFunctionOfIs(is)) return subA(); return subB()}

super *newObj = getLoadType(is).loadMe(is);

but I've made the no-argument constructor of subB private, so I can't do that here. But I don't actually need a super object, just the class type of a super subclass. So is there a way to represent that as a variable?

EDIT: I'm aware that in this case, I could return a function pointer, but I'm considering more complex examples that might involve needing to call more than one static function.

+9  A: 

You might want to look at the Factory Pattern. If you are designing a plugin architecture you can simple have a function that returns a pointer to the desired factory. Polymorphism can then do the rest for you.

doron
+1: The Factory pattern is probably the best bet here.
DeadMG