static const variables in abstract baseclass

2019-08-09 08:53发布

问题:

I've got a abstract baseclass, this is used for deriving some classes. Some properties of these classes are shared among all classes, and these should be unmodifiable.

To make a variable shared among all 10 classes I'll make it static.

class ABC{
public:
  static int *anArray;
  int index;
  static int tot_index;
  virtual void print()=0;
  ABC(){index=tot_index++;};
  virtual ~ABC(){};
};

This works fine, tot_index will contain the number of classes instantiated, and the index is the unique indentifier for each class.

The issue I have is that the *anArray, and number of derived classes is set at runtime, and after the classes have been instantiated I don't want to modify these values.

I'm abit puzzled by:

1) Where should I set the *anArray value? Just in some random of the derived class's?

2) If a variable should be unmodifiable, then I should set it to const. But If I don't know what the value is at compile time, how do I set it to const?

回答1:

Instead of using static variables there are some patterns that could achieve this.

The easiest to implement, albeit not the best for many reasons, would be putting your shared variables in a singleton base class (ref: GoF Singleton pattern).

Another, prettier solution could be some factory pattern, like the GoF Abstract Factory.

Edit: Also, for doc's comment, see: http://www.parashift.com/c++-faq/static-init-order-on-first-use.html

:)