0

I'm trying to implement something along the lines of:

Class EntityManager
{
   AddEntity(Entity e);
   RemoveEntity(Entity e);

   std::vector<Entity> entities;
}

Class Entity
{
   // Need a mechanism here to add and remove entities on the constructor and destructor of Entity
}

Hope this makes sense. Eventually Entity will contain a number of pure virtuals, when I inherit from Entity I want it to automatically add the entity to the vector, the EntityManager will then call the pure virtual functions on each entity.

Thanks for your time.

  • Can you clarify what "Circular reference problem" you're referring to? – cigien Sep 21 '20 at 22:14
  • Yeah sure. I may have misunderstood but I have a situation where the EntityManager has to include Entity so it can have a list of Entities. Also each Entity needs to include EntityManager so it can access the add and remove methods. I can fix the circular reference issue by forward declaring but I feel like I've made a design error to reach this point. – Jamiernmd Sep 21 '20 at 22:25
  • Yes, that's likely. You can probably avoid circular references for your problem, but that depends. Also, please don't post clarifications to the question as comments, just edit the question. – cigien Sep 21 '20 at 22:26

1 Answers1

0

If you're using virtual functions you need pointers, so Entity* is your base type here, or perhaps one wrapped in a smart pointer.

When you use Entity you're saying "these elements are all literally Entity and are exactly the same size" while Entity-derived classes may be quite different and significantly larger.

As a pointer there's no size information baked in, that's all a function of how it was allocated, which is typically via new with the correct class called.

If you want to automatically add these to something as they're created then you need to add code to your base class constructor.

So long as the adding code is in the .cpp implementation of Entity then there's no circular references problem. Declare Entity first and the EntityManager knows enough to build on.

tadman
  • 208,517
  • 23
  • 234
  • 262