Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C++ For Dummies (2004) [eng].pdf
Скачиваний:
84
Добавлен:
16.08.2013
Размер:
8.09 Mб
Скачать

Chapter 17: Making Constructive Arguments 233

be changed thereafter. How can the constructor assign a const data member a value? The problem is solved with the same “colon syntax” used to initialize complex 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 declaration assigns a value to the variable numberOfFeet when the object is created. The numberOfFeet cannot be modified once it’s been declared and initialized.

Programmers commonly use the “colon syntax” to initialize even non-const data members. Doing so isn’t necessary, but it’s common practice.

Constructing the Order of Construction

When there are multiple objects, all with constructors, programmers usually don’t care about the order in which things are built. If one or more of the con­ structors has 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 dec­ larations are 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 the class.

Destructors are invoked in the reverse order from constructors.

A static variable is a variable that is local to a function but retains its value from one function invocation to the next. A global variable is a variable declared outside a function.

Now, consider each of the preceding rules in turn.

234 Part III: Introduction to Classes

Local objects construct in order

Local objects are constructed in the order in which the program encounters their declaration. Normally, this is the same as the order in which the objects appear in the function, unless the function jumps around particular declara­ tions. (By the way, jumping around declarations is a bad thing. It confuses the reader and the compiler.)

Static objects construct only once

Static objects are similar to local variables, except that they are constructed only once. C++ must wait until the first time control passes through the static’s before constructing the object. Consider the following trivial ConstructStatic program:

//

//ConstructStatic - demonstrate that statics are only

//

constructed once

//

 

#include <cstdio>

 

#include <cstdlib>

 

#include <iostream>

 

using namespace std;

 

class DoNothing

{

public:

DoNothing(int initial)

{

cout << “DoNothing constructed with a value of “

<<initial

<<endl;

}

};

void fn(int i)

{

cout << “Function fn passed a value of “ << i << endl; static DoNothing dn(i);

}

int main(int argcs, char* pArgs[])

{

fn(10);

fn(20);

system(“PAUSE”); return 0;

}

Chapter 17: Making Constructive Arguments 235

Executing this program generates the following results:

Function fn passed a value of 10

DoNothing constructed with a value of 10

Function fn passed a value of 20

Press any key to continue . . .

Notice that the message from the function fn() appears twice, but the mes­ sage from the constructor for DoNothing appears only the first time fn() is called. This indicates that the object is constructed the first time that fn() is called, but not thereafter.

All global objects construct before main()

All global variables go into scope as soon as the program starts. Thus, all global objects are constructed before control is passed to main().

Initializing global variables can cause real debugging headaches. Some debug­ gers try to execute up to main() as soon as the program is loaded and before they hand over control to the user. This can be a problem because the con­ structor code for all global objects has already been executed by the time you can wrest control of your program. If one of these constructors has a fatal bug, you never even get a chance to find the problem. In this case, the program appears to die before it even starts!

You can approach this problem in several ways. One is to test each construc­ tor on local objects before using it on globals. If that doesn’t solve the prob­ lem, you can try adding output statements to the beginning of all suspected constructors. The last output statement you see probably came from the flawed constructor.

Global objects construct in no particular order

Figuring out the order of construction of local objects is easy. An order is implied by the flow of control. With globals, no such flow is available to give order. All globals go into scope simultaneously — remember? Okay, you argue, why can’t the compiler just start at the top of the file and work its way down the list of global objects?

That would work fine for a single file (and I presume that’s what most compil­ ers do). Unfortunately, most programs in the real world consist of several files that are compiled separately and then linked. Because the compiler has no control over the order in which these files are linked, it cannot affect the order in which global objects are constructed from file to file.

236 Part III: Introduction to Classes

Most of the time, the order of global construction is pretty ho-hum stuff. Once in a while, though, global variables generate bugs that are extremely difficult to track down. (It happens just often enough to make it worth mentioning in a book.)

Consider the following example:

class Student

{

public:

Student (int id) : studentId(id) {} const int studentId;

};

class Tutor

{

public:

Tutor(Student& s) : tutoredId(s.studentId) {} int tutoredId;

};

//set up a student Student randy(1234);

//assign that student a tutor Tutor jenny(randy);

Here the constructor for Student assigns a student ID. The constructor for Tutor records the ID of the student to help. The program declares a student randy and then assigns that student a tutor jenny.

The problem is that the program makes the implicit assumption that randy is constructed before jenny. Suppose that it were the other way around. Then jenny would be constructed with a block of memory that had not yet been turned into a Student object and, therefore, had garbage for a student ID.

The preceding example is not too difficult to figure out and more than a little contrived. Nevertheless, problems deriving from global objects being con­ structed in no particular order can appear in subtle ways. To avoid this prob­ lem, don’t allow the constructor for one global object to refer to the contents of another global object.

Members construct in the order in which they are declared

Members of a class are constructed according to the order in which they’re declared within the class. This isn’t quite as obvious as it may sound. Consider the following example: