Haffi112
Haffi112

Reputation: 523

C++ class with selectable properties

I'm writing a graph library and as an example I have a special class for an Edge. This class has some properties besides source (Vertex) and target (Vertex) like for example weight (double), reliability (double), delay (double), presence (double) etc.

The thing is however that I do not always need to use all of these properties and I would like to save memory by not having to specify them. Is there any standard way of achieving that instead of defining a base class with the core properties and then defining child classes which either have the properties or not? I'm asking because I do not want to have exponentially many possible child classes based on which properties I need at any given time.

Upvotes: 0

Views: 149

Answers (1)

John Zwinck
John Zwinck

Reputation: 249394

If the properties are only a few (less than 20, say), you are probably better off just including them in your class and setting them to NAN when they are not present. It's only 8 bytes per property anyway.

If you have many properties but most objects have only a few, you could store them in a map<Property, double> where Property is an enum of all possible properties. If you care a lot about compact store, better to store them in an array<pair<Property, double>, N> instead, assuming you have some maximum number of properties (N).

Upvotes: 1

Related Questions