Defining a Constructor

Lines 14–18 of Fig. 3.7 define a constructor for class GradeBook. The constructor has the same name as its class, GradeBook. A constructor specifies in its parameter list the data it requires to perform its task. When you create a new object, you place this data in the parentheses that follow the object name (as we did in lines 47–48). Line 14 indicates that class GradeBook’s constructor has a string parameter called name. We declared this constructor explicit, because it takes a single parameter—this is important for subtle reasons that you’ll learn in Section 10.13. For now, just declare all single-parameter constructors explicit. Line 14 does not specify a return type, because constructors cannot return values (or even void). Also, constructors cannot be declared const (because initializing an object modifies it).

The constructor uses a member-initializer list (line 15) to initialize the courseName data member with the value of the constructor’s parameter name. Member initializers appear between a constructor’s parameter list and the left brace that begins the constructor’s body. The member initializer list is separated from the parameter list with a colon (:). A member initializer consists of a data member’s variable name followed by parentheses containing the member’s initial value. In this example, courseName is initialized with the value of the parameter name. If a class contains more than one data member, each data member’s initializer is separated from the next by a comma. The member initializer list executes before the body of the constructor executes. You can perform initialization in the constructor’s body, but you’ll learn later in the book that it’s more efficient to do it with member initializers, and some types of data members must be initialized this way.

Notice that both the constructor (line 14) and the setCourseName function (line 21) use a parameter called name. You can use the same parameter names in different functions because the parameters are local to each function—they do not interfere with one another.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset