Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


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.




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.



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