devxlogo

Take Advantage of the Automatic Initialization of Static Objects

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.

See also  Digital Signage Solutions for Agile Software Development Teams
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist