devxlogo

Make a Collection of All Inherited Classes

Make a Collection of All Inherited Classes

Say you want to have several classes-modifiers, and you want to execute a certain virtual function for each of them. The ideal solution is to create an abstract class with a purely virtual function, inherit your implementation classes from this base class and make a collection of all the implementation classes. The problem is that, the user needs to remember to create exactly one copy of each implementation class and correctly “register” it. The following example helps to solve this problem by automatically creating exactly one instance of each implementation of the class modifier:

 #include template  class AutoMake{  virtual void trick() {t;} // virtual function uses _static variable  static T t;};template  T AutoMake::t;template   class Modifier : AutoMake{protected:  Modifier() {vec.push_back(this);}private:  std::vector vec;};class ModifierImpl1 : public Modifier {};class ModifierImpl2 : public Modifier {};That's all: already in main(...) function you will have _2 pointers inModifier::vec (with ModifierImpl1* and ModifierImpl2* types);
See also  5 Tips for Choosing the Right Medical Software for Your Practice
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist