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.

230Part III: Introduction to Classeshave access to the protected members of StudentId. You could make Studenta friend of StudentId, but that violates the “you take care of your business,I’ll take care of mine” philosophy. Somehow, you need to invoke the constructorfor StudentId when Student is constructed.C++ does this for you automatically in this case, invoking the default constructorStudentId::StudentId() on id. This occurs after the Studentconstructor is called, but before control passes to the first statement in theconstructor. (Single-step the preceding program in the debugger to see what Imean. As always, be sure that inline functions are forced outline.) Followingis the output that results from executing this program:assigning student id 1constructing Student ChesterPress any key to continue . . .Notice that the message from the StudentId constructor appears before theoutput from the Student constructor. (By the way, with all these constructorsperforming output, you may think that constructors must output something.Most constructors don’t output a bloody thing.)If the programmer does not provide a constructor, the default constructorprovided by C++ automatically invokes the default constructors for datamembers. The same is true come harvesting time. The destructor for theclass automatically invokes the destructor for data members that havedestructors. The C++-provided destructor does the same.Okay, this is all great for the default constructor. But what if you want toinvoke a constructor other than the default? Where do you put the object?For example, assume that a student ID is provided to the Student constructor,which passes the ID to the constructor for class StudentId.Let me first show you what doesn’t work. Consider the following programsegment (only the relevant parts are included here — the entire program,ConstructSeparateID, is on the CD-ROM that accompanies this book):class Student{public:Student(char *pName = “no name”, int ssId = 0){cout

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

Saved successfully!

Ooh no, something went wrong!