Hello! Suppose there is a certain class

class Parent { protected: static Parent *Head_ptr; static Parent *Tail_ptr; Parent *NextObject_ptr; virtual void SomeVirtualMethod(void){} static void AllSomeVirtualMethods(void) { Parent *CurrentObject_ptr = Parent::Head_ptr; while (CurrentObject_ptr != NULL) { CurrentObject_ptr->SomeVirtualMethod(); CurrentObject_ptr = CurrentObject_ptr->NextObject_ptr; } } public: Parent() { if (Parent::Head_ptr == NULL) { Parent::Head_ptr = this; } else { Tail_ptr->NextObject_ptr = this; this->NextObject_ptr = NULL; } Parent::Tail_ptr = this; } }; 

If you create instances of the Parent class, then, by design, a pointer to each added object is recorded in the previous object. Thus, all the methods of the created objects of this class are called according to the generated list.

However, the task is complicated. I need to iterate through all the objects of each of the classes inherited from Parent.

In fact, I need the following order of calling virtual functions SomeVirtualMethod. The virtual methods of all objects of the first inherited class are called in turn, then the virtual methods of all objects of the second inherited class are called in succession, and so on for all of the inherited classes. How best to implement this workaround?

It also interests me in general how to bypass exactly the inherited classes and not their objects. For example, to read from each inherited class the value of a static variable inherited from the base class.

    1 answer 1

    I can offer to enable RTTI. After that, we perform a primary search of all objects and put them into std::multimap<std::type_info, Parent*> (that is, we group the pointers to objects according to the general actual type of the child class; and yes, the while can be rewritten into for ):

     static void AllSomeVirtualMethods(void) { std::multimap<std::type_index, Parent*> perTypeGrouping; for( Parent *CurrentObject_ptr = Parent::Head_ptr; CurrentObject_ptr != NULL; CurrentObject_ptr = CurrentObject_ptr->NextObject_ptr ) { perTypeGrouping.insert( std::type_index(typeid(*CurrentObject_ptr)), CurrentObject_ptr ); } } 

    After that we go through multimap y. Since the associative array guarantees orderliness by key, all objects of the same actual class will be in the neighborhood.

     for( std::multimap<std::type_index, Parent*>::iterator entry = perTypeGrouping.begin(), entry != perTypeGrouping.end(); ++entry ) entry->second->SomeVirtualMethod(); 
    • one
      Thanks for the interesting answer! Is there a way to implement this task without using RTTI and std? Is it possible to create a separate list and place there pointers to the first created objects of each of the heirs, and then go through the chain from the first object to pass all the objects of each of the heirs? - Ilia