Inheriting Static Data Members

Started by
3 comments, last by Vincent_M 10 years, 12 months ago

I have the following classes in C++:

class CollectionItem {...};

class Collection {...};

Collection managers a list of CollectionItem instances. CollectionItem has a char[32] "name" property and a type[32] "type". The name property is meant to be unique for that specific CollectionItem instance while "type" is for grouping, and Collection is only meant to add CollectionItem instances who's "type" meets Collection's "key" char[32].

CollectionItem is meant to be an abstract class to be instanced like so:

class Object : public CollectionItem {}; // Object's inherited "type" will be "scene_object"

class PointLight : public CollectionItem {}; // PointLight's inherited "type" will be "scene_pointlight"

class Model : public CollectionItem {}; // Model's inherited "type" will be "scene_model"

As you can see all "Object" instances are meant to have the same value for "type", while PointLight instances will have their own group value, etc. The problem is that I'm using a bunch of redundant memory. Each instance of CollectionItem results in an extra 32 bytes of the same string... Thousands of these items can exist at once in some applications. I know that's only 32KB of fluff space per 1024 CollectionItems, but I'd like to cut that down if possible.

I'd like to make "type" static, and change its value for each class it inherits from. Problem is, inheriting classes don't get their own class-wide copy of that static data member. By design, inherited classes all share their superclass counterpart's static member.

I could just declare a static member of char[32] "type" in all subclasses, but Collection isn't going to evaluate subclass versions of "type", it's only going to see CollectionItem's type.

Any ideas?

Advertisement

I'm not sure i understand. When the object is built only one copy of type is included, and set to the appropriate value. Each object in your design needs to have this to be recognized. How is this redundant?

If you're concerned about redunant menory, why not just make multiple instances of the collections object and use them to roganize specific entites?

If you were to change "type" to a pointer, you could take advantage of a compiler optimization called "string pooling." So, regardless of how many CollectionItem instances you have, there will only be one copy of the string in memory for each derived type.

Just use a virtual function getType() that returns the type string literal.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

Actually, I think Paradigm Shifter has the solution. Sounds so simple, I can't believe I didn't even consider that. Perfect!

This topic is closed to new replies.

Advertisement