0% found this document useful (0 votes)
6 views46 pages

chtp8_16

Chapter 3 of 'C++ How to Program' discusses the initialization of objects using constructors, which are special member functions that cannot return values and are called automatically when an object is created. It also emphasizes the importance of separating class definitions into header files for reusability and maintaining a clear interface from implementation. Additionally, the chapter covers the use of member initializer lists and the significance of using the scope resolution operator when defining member functions outside the class definition.

Uploaded by

Hamzih Alsmadi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views46 pages

chtp8_16

Chapter 3 of 'C++ How to Program' discusses the initialization of objects using constructors, which are special member functions that cannot return values and are called automatically when an object is created. It also emphasizes the importance of separating class definitions into header files for reusability and maintaining a clear interface from implementation. Additionally, the chapter covers the use of member initializer lists and the significance of using the scope resolution operator when defining member functions outside the class definition.

Uploaded by

Hamzih Alsmadi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 46

Chapter 3

Introduction to
Classes,
Objects and
Strings
C++ HOW TO PROGRAM, 9/E

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS


1
RESERVED.
Initializing Objects with Constructors
Each class can provide one or more constructors that can be used to
initialize an object of the class when the object is created.
A constructor is a special member function that must be defined
with the same name as the class, so that the compiler can distinguish
it from the class’s other member functions.
An important difference between constructors and other functions
is that constructors cannot return values, so they cannot specify a
return type (not even void).
Normally, constructors are declared public.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


2
Initializing Objects with Constructors (cont.)
C++ automatically calls a constructor for each object that is created,
which helps ensure that objects are initialized properly before
they’re used in a program.
The constructor call occurs when the object is created.
If a class does not explicitly include constructors, the compiler
provides a default constructor with no parameters.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


3
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
4
RESERVED.
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
5
RESERVED.
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
6
RESERVED.
Initializing Objects with Constructors (cont.)
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.
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 (:).

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


7
Initializing Objects with Constructors (cont.)
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.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


8
Initializing Objects with Constructors (cont.)
Line 47 creates and initializes a GradeBook
object called gradeBook1.
 When this line executes, the GradeBook constructor
(lines 14–18) is called with the argument "CS101
Introduction to C++ Programming" to initialize
gradeBook1’s course name.
Line 48 repeats this process for the GradeBook
object called gradeBook2, this time passing the
argument "CS102 Data Structures in C++"
to initialize gradeBook2’s course name.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


9
Initializing Objects with Constructors (cont.)
Any constructor that takes no arguments is called a default
constructor.
A class gets a default constructor in one of several ways:
 The compiler implicitly creates a default constructor in every class
that does not have any user-defined constructors. The default
constructor does not initialize the class’s data members, but does
call the default constructor for each data member that is an object of
another class. An uninitialized variable contains an undefined
(“garbage”) value.
 You explicitly define a constructor that takes no arguments. Such a
default constructor will call the default constructor for each data
member that is an object of another class and will perform
additional initialization specified by you.
 If you define any constructors with arguments, C++ will not implicitly
create a default constructor for that class.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


10
Initializing Objects with Constructors (cont.)
Like operations, the UML models constructors in
the third compartment of a class in a class diagram.
To distinguish a constructor from a class’s
operations, the UML places the word “constructor”
between guillemets (« and ») before the
constructor’s name.
It’s customary to list the class’s constructor before
other operations in the third compartment.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


11
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
12
RESERVED.
Placing a Class in a Separate File for
Reusability
One of the benefits of creating class definitions
is that, when packaged properly, our classes can
be reused by programmers—potentially
worldwide.
Programmers who wish to use our GradeBook
class cannot simply include the file from Fig. 3.7
in another program.
 As you learned in Chapter 2, function main begins the
execution of every program, and every program must
have exactly one main function.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


13
Placing a Class in a Separate File for
Reusability (cont.)
Each of the previous examples in the chapter consists of a
single .cpp file, also known as a source-code file, that
contains a GradeBook class definition and a main
function.
When building an object-oriented C++ program, it’s
customary to define reusable source code (such as a class) in
a file that by convention has a .h filename extension—
known as a header.
Programs use #include preprocessing directives to
include header files and take advantage of reusable software
components.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


14
Placing a Class in a Separate File for
Reusability (cont.)
Our next example separates the code from Fig. 3.7 into two
files—GradeBook.h (Fig. 3.9) and fig03_10.cpp
(Fig. 3.10).
 As you look at the header file in Fig. 3.9, notice that it contains only
the GradeBook class definition (lines 7–38) and the headers on
which the class depends.
 The main function that uses class GradeBook is defined in the
source-code file fig03_10.cpp (Fig. 3.10) in lines 8–18.
To help you prepare for the larger programs you’ll
encounter later in this book and in industry, we often use a
separate source-code file containing function main to test
our classes (this is called a driver program).

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


15
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
16
RESERVED.
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
17
RESERVED.
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
18
RESERVED.
Placing a Class in a Separate File for
Reusability (cont.)
Throughout the header (Fig. 3.9), we use std::
when referring to string (lines 11, 18, 24 and
37), cout (line 33) and endl (line 34).
Headers should never contain using directives
or using declarations (Section 2.7).
To test class GradeBook (defined in Fig. 3.9), you
must write a separate source-code file containing
a main function (such as Fig. 3.10) that
instantiates and uses objects of the class.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


19
Placing a Class in a Separate File for
Reusability (cont.)
To help the compiler understand how to use a class, we must
explicitly provide the compiler with the class’s definition
 That’s why, for example, to use type string, a
program must include the <string> header file.
 This enables the compiler to determine the amount of
memory that it must reserve for each object of the
class and ensure that a program calls the class’s
member functions correctly.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


20
Placing a Class in a Separate File for
Reusability (cont.)
The compiler creates only one copy of the class’s member
functions and shares that copy among all the class’s objects.
Each object, of course, needs its own data members,
because their contents can vary among objects.
The member-function code, however, is not modifiable, so it
can be shared among all objects of the class.
Therefore, the size of an object depends on the amount of
memory required to store the class’s data members.
By including GradeBook.h in line 4, we give the compiler
access to the information it needs to determine the size of a
GradeBook object and to determine whether objects of
the class are used correctly.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


21
Placing a Class in a Separate File for
Reusability (cont.)
A #include directive instructs the C++ preprocessor
to replace the directive with a copy of the contents of
GradeBook.h before the program is compiled.
 When the source-code file fig03_10.cpp is compiled, it now
contains the GradeBook class definition (because of the
#include), and the compiler is able to determine how to
create GradeBook objects and see that their member
functions are called correctly.
Now that the class definition is in a header file (without
a main function), we can include that header in any
program that needs to reuse our GradeBook class.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


22
Placing a Class in a Separate File for
Reusability (cont.)
Notice that the name of the GradeBook.h header file
in line 4 of Fig. 3.10 is enclosed in quotes (" ") rather
than angle brackets (< >).
 Normally, a program’s source-code files and user-defined
header files are placed in the same directory.
 When the preprocessor encounters a header file name in
quotes, it attempts to locate the header file in the same
directory as the file in which the #include directive
appears.
 If the preprocessor cannot find the header file in that
directory, it searches for it in the same location(s) as the C++
Standard Library header files.
 When the preprocessor encounters a header file name in
angle brackets (e.g., <iostream>), it assumes that the
header is part of the C++ Standard Library and does not look
in the directory of the program that is being preprocessed.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


23
Placing a Class in a Separate File for
Reusability (cont.)
Conventional software engineering wisdom says that to use an object
of a class, the client code needs to know only what member functions
to call, what arguments to provide to each member function and
what return type to expect from each member function.
 The client code does not need to know how those functions are
implemented.
If client code does know how a class is implemented, the client-code
programmer might write client code based on the class’s
implementation details.
Ideally, if that implementation changes, the class’s clients should not
have to change.
Hiding the class’s implementation details makes it easier to change
the class’s implementation while minimizing, and hopefully
eliminating, changes to client code.
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.
24
Separating Interface from Implementation
Interfaces define and standardize the ways in
which things such as people and systems interact
with one another.
The interface of a class describes what services a
class’s clients can use and how to request those
services, but not how the class carries out the
services.
A class’s public interface consists of the class’s
public member functions (also known as the
class’s public services).

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


25
Separating Interface from Implementation
(cont.)
In our prior examples, each class definition contained the complete
definitions of the class’s public member functions and the
declarations of its private data members.
It’s better software engineering to define member functions outside
the class definition, so that their implementation details can be
hidden from the client code.
 Ensures that you do not write client code that depends on the class’s
implementation details.
The program of Figs. 3.11–3.13 separates class GradeBook’s
interface from its implementation by splitting the class definition of
Fig. 3.9 into two files—the header file GradeBook.h (Fig. 3.11) in
which class GradeBook is defined, and the source-code file
GradeBook.cpp (Fig. 3.12) in which GradeBook’s member
functions are defined.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


26
Separating Interface from Implementation
(cont.)
By convention, member-function definitions are
placed in a source-code file of the same base
name (e.g., GradeBook) as the class’s header
file but with a .cpp filename extension.
Figure 3.14 shows how this three-file program is
compiled from the perspectives of the
GradeBook class programmer and the client-
code programmer—we’ll explain this figure in
detail.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


27
Separating Interface from Implementation
(cont.)
Header file GradeBook.h (Fig. 3.11) is similar to the one
in Fig. 3.9, but the function definitions in Fig. 3.9 are
replaced here with function prototypes (lines 11–14) that
describe the class’s public interface without revealing the
class’s member-function implementations.
A function prototype is a declaration of a function that tells
the compiler the function’s name, its return type and the
types of its parameters.
Including the header file GradeBook.h in the client code
(line 5 of Fig. 3.13) provides the compiler with the
information it needs to ensure that the client code calls the
member functions of class GradeBook correctly.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


28
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
29
RESERVED.
Separating Interface from Implementation
(cont.)
Source-code file GradeBook.cpp (Fig. 3.12) defines
class GradeBook’s member functions, which were
declared in lines 11–14 of Fig. 3.11.
Each member-function name (lines 9, 16, 22 and 28) is
preceded by the class name and ::, which is known as
the scope resolution operator.
This “ties” each member function to the (now separate)
GradeBook class definition (Fig. 3.11), which declares
the class’s member functions and data members.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


30
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
31
RESERVED.
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
32
RESERVED.
Separating Interface from Implementation
(cont.)
To indicate that the member functions in
GradeBook.cpp are part of class GradeBook, we must
first include the GradeBook.h header file (line 5 of
Fig. 3.12).
This allows us to access the class name GradeBook in the
GradeBook.cpp file.
When compiling GradeBook.cpp, the compiler uses the
information in GradeBook.h to ensure that
 the first line of each member function matches its prototype in the
GradeBook.h file, and that
 each member function knows about the class’s data members and
other member functions

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


33
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
34
RESERVED.
Separating Interface from Implementation
(cont.)
Before executing this program, the source-code files in
Fig. 3.12 and Fig. 3.13 must both
 be compiled,
 then linked together—
 the member-function calls in the client code need to be tied to the
implementations of the class’s member functions—a job performed
by the linker.
The diagram in Fig. 3.14 shows the compilation and
linking process that results in an executable
GradeBook application that can be used by instructors.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


35
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
36
RESERVED.
Validating Data with set Functions
The program of Figs. 3.15–3.17 enhances class
GradeBook’s member function setCourseName to
perform validation (also known as validity checking).
Since the interface of the class remains unchanged,
clients of this class need not be changed when the
definition of member function setCourseName is
modified.
This enables clients to take advantage of the improved
GradeBook class simply by linking the client code to
the updated GradeBook’s object code.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


37
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
38
RESERVED.
Validating Data with set Functions (cont.)
The C++ Standard Library’s string class defines a member
function length that returns the number of characters in a
string object.
A consistent state is a state in which the object’s data member
contains a valid value.
Class string provides member function substr (short for
“substring”) that returns a new string object created by
copying part of an existing string object.
 The first argument specifies the starting position in the original
string from which characters are copied.
 The second argument specifies the number of characters to copy.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


39
Validating Data with set Functions (cont.)
Figure 3.17 demonstrates the modified version of class
GradeBook (Figs. 3.15–3.16) featuring validation.
In previous versions of the class, the benefit of calling
setCourseName in the constructor was not evident.
Now, however, the constructor takes advantage of the
validation provided by setCourseName.
The constructor simply calls setCourseName, rather
than duplicating its validation code.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


40
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
41
RESERVED.
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
42
RESERVED.
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
43
RESERVED.
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
44
RESERVED.
©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS
45
RESERVED.
Validating Data with set Functions (cont.)
A public set function such as setCourseName should carefully
scrutinize any attempt to modify the value of a data member (e.g.,
courseName) to ensure that the new value is appropriate for that
data item.
A set function could return a value indicating that an attempt was
made to assign invalid data to an object of the class.
A client could then test the return value of the set function to
determine whether the attempt to modify the object was successful
and to take appropriate action if not.

©2016 BY PEARSON EDUCATION, INC., HOBOKEN, NJ. ALL RIGHTS RESERVED.


46

You might also like