What is a best practice to allow one instance of object?

Started by
1 comment, last by frob 9 years, 10 months ago
You can see in the code snippet, m_crowd is allocated as many times as different derived objects are created. If I make the object static, the m_crowd will be the last copy of allocation. I make a base class because I want to make a generic container so that all objects can be tested for collisions. Am I better off to make this variable global? do I loose the cohesion feature of OOP if I do so? Thanks Jack
class OgreDetourCrowdBase {
   OgreDetourCrowdBase();
   dtCrowd *m_crowd;
};

class OgreDetourCrowdCB : public OgreDetourCrowdBase {
   OgreDetourCrowdCB();
};

class OgreDetourCrowdVNA : public OgreDetourCrowdBase {
   OgreDetourCrowdVNA();
};

OgreDetourCrowdBase::OgreDetourCrowdBase()
{ 
    m_crowd = dtAllocCrowd();
}
Advertisement

If you make it static, then you don't want to allocate and overwrite it every time you create an object. Allocate it once at startup at the appropriate time, or make it an object and let it manage its own lifetime if that's possible.

I'm probably missing something, but your question is asking about collision tests.

That is normally done by adding information to a collision system, not by having a static objects that everything must belong to.

Trying to make it a part of the design where all objects self-register is fairly dangerous. All objects must self register. There is no way to make an object that doesn't self register. If you are passing parameters or making an array, every temporary object is absolutely required to self register. If you are making an off screen object it still must register for the collision system. If you are making an object and it is not part of the world yet, it still must register for collisions. In such a design, this is mandatory. You cannot create any object, for any duration, without it automatically getting registered.

A typical approach is that when things get added to the world (not object construction) you also create zero or more physics objects which get included for collision detection and response. When an object is removed from the world (not object destruction) you also remove any associated physics objects.

This topic is closed to new replies.

Advertisement