11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

236Part III: Introduction to ClassesMost of the time, the order of global construction is pretty ho-hum stuff. Oncein a while, though, global variables generate bugs that are extremely difficultto track down. (It happens just often enough to make it worth mentioning ina 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 studentStudent randy(1234);// assign that student a tutorTutor jenny(randy);Here the constructor for Student assigns a student ID. The constructor forTutor records the ID of the student to help. The program declares a studentrandy and then assigns that student a tutor jenny.The problem is that the program makes the implicit assumption that randy isconstructed before jenny. Suppose that it were the other way around. Thenjenny would be constructed with a block of memory that had not yet beenturned 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 littlecontrived. Nevertheless, problems deriving from global objects being constructedin no particular order can appear in subtle ways. To avoid this problem,don’t allow the constructor for one global object to refer to the contentsof another global object.Members construct in the orderin which they are declaredMembers of a class are constructed according to the order in which they’redeclared within the class. This isn’t quite as obvious as it may sound. Considerthe following example:

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

Saved successfully!

Ooh no, something went wrong!