I have some arrangement of objects, and their interrelations (a kind of topology) are independent of the type of the object. I want to use the same structure and interrelations with different contained classes, subclassed from the same container class. In my container class the relations can be fully described knowing only that the contained classes are contained in a grid; no question whether the grid is populated or not. That is, the classes derived from the container must populate the grid first in their constructor, then they are ready to go. That is, I can go with an empty container and if the derived classes in their constructor populate the grid with the corresponding objects, everything works fine. However, the constructor must populate the grid to provide a reasonable functionality. If it would not be a constructor, I would make it abstract. I can leave it empty, leaving the duty to populate it in the subclasses, or I can have a method Populate() as abstract, but that should be called form the constructor. Which (or which other) method is the best?
Constructors can't be virtual.
Calling a virtual method in the base's constructor is problematic, because the derived object doesn't exist yet.
What you can instead do is provide a factory function that calls populate
after constructing the object.
class Base
{
template <typename Derived, typename... Args>
static Derived make(Args&&... args)
{
Derived result(std::forward<Args>(args)...);
result.populate();
return result;
}
protected:
Base() = default;
virtual void populate() = 0;
};