Hi, I would like to get an advice, lets take SDL lib as an example.

Recently I've been declaring sprite sheets that certain classes use ( player, enemy... ) globally and thought that a better way would be to load sprite sheets inside a class thats using it but if lets say i create like 100 class objects at the same time, it would take up a lot more memory and every time the constructor would have more work ( loading the sprite, clipping it... ), could someone point me to the right direction on this one.

On a conceptual level, I would recommend looking into the Flyweight pattern. The basic principle is to have a class which represents the common aspects of the objects (e.g., sprite sheets) as class members, then have the Flyweight objects instantiate just the details which the specific object needs (e.g., position, color map). The Wikipedia page has a decent example of how to write a Flyweight class and Flyweight Factory (which also allows you to avoid repeated memory allocations by having a pre-existing pool of Flyweight objects to draw from).

On a practical level, you would probably have some abstract parent class for all of the objects you are using (the Flyweight class), and a Factory class which would be used to produce (or retrieve) objects of the appropriate sub-class. The Flyweight class would provide an interface for the shared behaviors, as well as holding any properties shared by all members as class ( static ) variables. The Flyweight Factory class would have a method that takes some sort of marker that indicates which subclass of the Flyweight class to use, as well as any properties specific to the Flyweight object; it would check to see if any objects of that sub-class already exist, and if so, returns one of them, otherwise, it would create a new object of the desired sub-class and return that. The parent Flyweight class (and it's sub-classes) would hold the shared information as static class variables; only the specifics of the particular object would need to be held by the individual objects themselves. The Flyweight Factory would also have a method that gets an object and puts it in the free object pool; instead of destroying the object, you would pass it back to the Factory.

Edit: You might find it helpful to use the Boost.Flyweight template, rather than writing a whole Flyweight system from scratch.

Edited 5 Years Ago by Schol-R-LEA: n/a

This question has already been answered. Start a new discussion instead.