dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Mastering Class Member Initialization-4 : Page 4


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Defining Class Constants
Sometimes, you need an internal constant that all instances of the same class share. In earlier stages of C++, an anonymous enum was used for this purpose:

class Allocator { enum { PAGE_SIZE=1024 }; // };

Although this form is still in use, standard-compliant compilers offer a preferable method of defining class constants:

class Allocator { static const int PAGE_SIZE=1024; public: Allocator(int pages){ p=new char[pages*PAGE_SIZE];} // }; const int Allocator::PAGE_SIZE; //no initializer here

This kind of initialization is permitted only with const static members of integral types. For any other type, use a member initialization list:


class Math { const static double PI; // }; const double Math::PI= 3.14159265358979;

Knowing When and How
The primary form of initializing members is a member initialization list. For const data, references and subobjects whose constructors take arguments, the use of a member initialization list is mandatory. As a special case, const static members of an integral type are initialized inside the class body. Other static data members are initialized when defined, outside the class body.



Danny Kalev is a system analyst and software engineer with 13 years of experience, specializing in C++ and object-oriented analysis and design. He is a member of the ANSI C++ standardization committee and the author of ANSI/ISO C++ Professional Programmer's Handbook (Que, 1999, ISBN: 0789720221). Reavch him at dannykk@inter.net.il.
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