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 231The constructor for StudentId has been changed to accept a value externally(the default value is necessary to get the example to compile, for reasonsthat will become clear shortly). Within the constructor for Student, theprogrammer (that’s me) has (cleverly) attempted to construct a StudentIdobject named id.If you look at the output from this program, you notice a problem:assigning student id 0constructing student Chesterassigning student id 1234This message from mainPress any key to continue . . .The first problem is that the constructor for StudentId appears to beinvoked twice, once with zero and a second time with the expected 1234. Thenyou can see that the 1234 object is destructed before the output string inmain(). Apparently the StudentId object is destructed within the Studentconstructor.The explanation for this rather bizarre behavior is clear. The data member idalready exists by the time the body of the constructor is entered. Instead ofconstructing the existing data member id, the declaration provided in theconstructor creates a local object of the same name. This local object isdestructed upon returning from the constructor.Somehow, you need a different mechanism to indicate “construct the existingmember; don’t create a new one.” This mechanism needs to appear beforethe open brace, before the data members are declared. C++ provides a constructfor this, as shown in the following ConstructDataMembers program://// ConstructDataMember - construct a data member// to a value other than the default//#include #include #include #include using namespace std;const int MAXNAMESIZE = 40;class StudentId{public:StudentId(int id = 0){value = id;cout

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

Saved successfully!

Ooh no, something went wrong!