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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


advertisement
 

Use Class Member Initializers for Cleaner and Easier-to-Maintain Constructors -2 : Page 2

A new C++0x feature called a class member initializer allows you to specify a single initializer in the very declaration of a data member. Learn how to use this feature to simplify your constructors' code, reduce potential bugs, and make your code more readable.


advertisement

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


The Repeated Initializers Problem

In contemporary C++, a member-declarator can contain a constant initializer only if the affected member is both static and of a const integral type, or if it's a const enumeration type. For example, the following is allowed in C++98 and C++03:

class A { static const int MAX=1024; public: A(); //.. };



However, the next class declaration example is ill-formed because b is neither a const static data member of an integral type nor a const enumeration:

class C { int b=1024; //error bool f; double d; //.. };

Because of this restriction, programmers are forced to repeat the initialization of b in every constructor of class C:

class C { int b; bool f; double d; public: C(): b(1024), f(false), d(0.0) {} C(bool flag) : b(1024), f(flag), d(0.0) {} C(bool flag, double dbl): b(1024), f(flag), d(dbl){} };

Such repetition is both laborious and error prone. Why not let a programmer specify the initializer for b only once? A new C++0x proposal allows you to do exactly that—and even more.



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