Re: Some misc C++ questions (multimap, derived class function
argument, virtual static)
On Sep 13, 12:37 pm, Pete Becker <p...@versatilecoding.com> wrote:
Digital Puer wrote:
However, apparently I cannot have a virtual static method
in C++ (or in Java). What is the best way to force that all
derived classes have such a factory method?
Specification and testing. Beyond that, why do you care? If someone
wants to derived from your class but not provide a factory, what harm
does it do?
Because I want to enforce the existence of a factory method
in all derived classes. Every derived class will have its own
data, and I want the class to be able to produce a Base *
though the factory. I would like this factory method to be
usable by a consumer of the Base class:
void consumer()
{
Base *randomItem = Derived::createInstance(); // factory
doSomething(randomItem);
}
You are right that I could write an English specification that
says that all derived classes must have a factory method,
but I want to have that enforced in the Base class.
I guess a better approach would be to move the factory method
into another class that knows about the Derived class.
void consumer(Factory &factory)
{
Base *randomItem = factory.createInstanceOfDerived();
doSomething(randomItem);
}