11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 17: Making Constructive Arguments 233be changed thereafter. How can the constructor assign a const data membera value? The problem is solved with the same “colon syntax” used to initializecomplex objects.class Mammal{public:Mammal(int nof) : numberOfFeet(nof) {}protected:const int numberOfFeet;};Ostensibly, a given Mammal has a fixed number of feet (barring amputation).The number of feet can, and should, be declared const. This declarationassigns a value to the variable numberOfFeet when the object is created. ThenumberOfFeet cannot be modified once it’s been declared and initialized.Programmers commonly use the “colon syntax” to initialize even non-constdata members. Doing so isn’t necessary, but it’s common practice.Constructing the Order of ConstructionWhen there are multiple objects, all with constructors, programmers usuallydon’t care about the order in which things are built. If one or more of the constructorshas side effects, however, the order can make a difference.The rules for the order of construction are as follows: Local and static objects are constructed in the order in which their declarationsare invoked. Static objects are constructed only once. All global objects are constructed before main(). Global objects are constructed in no particular order. Members are constructed in the order in which they are declared in theclass. Destructors are invoked in the reverse order from constructors.A static variable is a variable that is local to a function but retains its valuefrom one function invocation to the next. A global variable is a variabledeclared outside a function.Now, consider each of the preceding rules in turn.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!