Sign in to follow this  

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

This topic is 4614 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites
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.)

Share this post


Link to post
Share on other sites
Sign in to follow this