Take Advantage of the Automatic Initialization of Static Objects

By default, all static variables, structs and arrays are automatically initialized to binary zeros before program’s outset. Likewise, static objects are initialized to binary zeros before their constructor is activated. Therefore, if you write a class whose objects always have static storage, you can take advantage of the automatic zero-initialization of its members and avoid explicit initialization within the constructor:

 class Message{private:  char msg[100];public:  Message() { for (int i =0; i<100; i++) msg[i] = ''; } /*unnecessary if all Message objects are static*/  Fill (const char *text);  const char * Read() const { return msg;} };

The constructor of Message initializes the array of characters 'msg' to binary zeros. If every Message object is static (it is declared as a local static object, a global object, or a namespace member), the constructor is unnecessary and can be removed as an optimization measure. Note that this assumption (i.e., that all Message objects are static) should be properly documented.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: