Say I have the following class hierarchy:
class Base
{
virtual int GetClassID(){ return 0;};
public:
Base() { SomeSingleton.RegisterThisObject(this->GetClassID());
}
class Derived
{
virtual int GetClassID(){ return 1;};
public:
Derived():Base(){};
}
Well, it’s all simplified from my real case, but that’s the general gist of it.
I want to avoid having to call RegisterThisObject in the constructor of each derived class, so I’m trying to move the call to the constructor of the base class.
Is there any pattern that I can use to acomplish this without using the virtual method in the constructor?
You might use the Curiously Recurring Template Pattern
Also, it will require extra work when you have multiple generations of derived classes (say
DerivedDerived : Derived). I’d suggest you simply avoid that but in other cases you might want to move the registration into a policy class instead (make the behaviour aggregatable as opposed to a part of the class identity)Traits
Expanding on my hint (make the behaviour aggregatable), you’d see something like this:
See Codepad.org