Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: All
Aug 6, 1999

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] = '\0'; } /*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.

Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date