Accelerated C++: Practical Programming by Example by Andrew Koenig & Barbara E. Moo

Accelerated C++: Practical Programming by Example by Andrew Koenig & Barbara E. Moo

Author:Andrew Koenig & Barbara E. Moo [Koenig, Andrew & Moo, Barbara E.]
Language: eng
Format: epub
Tags: C, Programming Languages, Computers, Programming, General, C++ (Computer Program Language), C Plus Plus (Computer Program Language)
ISBN: 9780201703535
Google: OaVQAAAAMAAJ
Amazon: 020170353X
Barnesnoble: 020170353X
Publisher: Addison-Wesley
Published: 2000-08-01T07:00:00+00:00


As it stands, our Student_info class is in this third category: It is a class type, but we do not explicitly say how to construct Student_info objects. So, if we define a local Student_info variable, then the n and homework members will be automatically initialized to the empty string and vector respectively, because they are class objects with constructors. In contrast, default-initializing midterm and final will give them undefined values, meaning they will hold whatever garbage happens to be in memory when the object is created.

Given our simple operations, this behavior may appear harmless: None of our operations uses the value of midterm or final without first initializing the object by calling read, which assigns values to these members. However, it is normally good practice to ensure that every data member has a sensible value at all times. For example, it is possible that later we (or a subsequent maintainer of our code) will add operations that examine these data members. If we don't initialize them in the constructor, then these new operations might cause future failures. Moreover, as we'll see in §11.3.5/201, even though we do not explicitly use midterm or final, there are synthesized operations on the class that could do so. Any use other than writing to an undefined value is illegal (§3.1/38), and so, strictly speaking, we must initialize these values.

In practice, we'll want to define two constructors: The first constructor takes no arguments and creates an empty Student_info object; the second takes a reference to an input stream and initializes the object by reading a student record from that stream. This strategy allows our users to write code such as

Student_info s; // an empty Student_info Student_info s2(cin); // initialize s2 by reading from cin



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.