I currently have a program that has multiple derived classes. All instances of a derived class are stored inside of that class's static vector of pointers. I also have a static vector of pointers which is inside of the base class which stores any object that has been derived from it. Whenever I add an object I currently have two push backs, one for the derived class and one for the base class. This means I also have to do two deletions when I want to get rid of an object. Is there anyway I can store the static vectors of pointers of all my derived classes in my base class? I keep thinking about using a 2d vector in my base class, would that work?

class Derived_class : public Base_class
     static std::vector<Derived_class *> Lamps

class Derived_class2 : public Base_class
     static std::vector<Derived_class2 *> Tables

class Base_class
     static std::vector<Base_class *> Furniture

Sorry in advance for any faux pas or if I'm not giving enough information.

1 Answer 1


You could keep an associative container in the base, mapping something representing the derived type to a list of instances.

The typeid operator returns a std::type_info reference, which by itself isn't usable as a key. std::type_index can be constructed from a std::type_info and is suitable as a key in a container.

Your code would then look something like this:

std::unordered_map<std::type_index, std::vector<Base_class*>> instances;

As a side note, you may want to evaluate if a vector is a suitable structure or if you want something with cheaper lookup/erase.

  • If that code to register instances is in the constructor of Base_class, then it is likely that typeid(*this) always reports the type Base_class. This is because during the execution of a base-class constructor, the object is actually of that type. It becomes an object of the derived type once the derived class' constructor starts to execute. Commented Sep 14, 2016 at 10:39
  • Good catch @BartvanIngenSchenau. I had indeed not specified where this would run. Any suggestions on a clean solution, or exercise for the reader? Commented Sep 14, 2016 at 11:00
  • If you're dealing with leaf types only, CRTP with Registrator<Derived> maybe? Commented Sep 14, 2016 at 12:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.