C++ classes - memory for 100+ instances of a class

Started by
4 comments, last by ade-the-heat 18 years, 10 months ago
I was reading the book about "Core Techniques and Algorithms for Game Programming" - it suggested that for a class (say a soldier) with many instances of it - say 100+ soldiers that the code that is common to all the soldiers - ie the Draw function and AI function can be stored in one single instance of a class - called a FlyWeight to save memory. The soldier class would then simply have its unique values for each soldier - eg position, velocity, health. This way we only have one instance of the Draw and AI and saving us loads of memory. Note how this is different from having a soldier class derived from a generic soldier class that would contain the Draw and AI functions (*) However, my question is for the second case (*): Will the memory the compiler will create of the 100+ soldiers be (approx) 100 times the size of the soldier class ? I would have thought that the compiler would be clever enough to just have one instance of the generic code ? Thanks Adrian
Advertisement
The functions do not factor into the size of the class. Take a class Foo:

class Foo{private:   int Data;public:   void DoStuff( );};


The function DoStuff will actually be implemented as if you had written it like this:

struct Foo{   int Data;};void DoStuff(Foo* this){    //Do Stuff}


So implementing functions in a seperate class will save no memory whatsoever.
Above: Unless they are talking abou virtual functions.
Note that virtual functions will add a mere 4 bytes (assuming you're using 32-bit memory address anyway) to your class (a pointer to the vtable).
Quote:Original post by ihatett
Above: Unless they are talking abou virtual functions.

Even then, there will only be one instance of each version of the function.

The Flyweight pattern has to do with sharing intrinsic states or resources. For example, your soldier object would contain a Flyweight to mesh data, instead of each instance having it's own instance of the mesh data. You would then request that the Flyweight draw the mesh with a transformation supplied by the soldier instance. (That is if I recall the Flyweight correctly.)
<span class="smallfont">That is not dead which can eternal lieAnd with strange aeons even death may die.   -- "The Nameless City" - H. P. Lovecraft</span>
thanks, that was helpful,

cheers

This topic is closed to new replies.

Advertisement