9781423902225_IM_ch14

advertisement
C++ Programming: Program Design Including Data Structures, Fourth Edition
Chapter 14
Overloading and Templates
At a Glance
Instructor’s Manual Table of Contents

Overview

Objectives

Teaching Tips

Quick Quizzes

Class Discussion Topics

Additional Projects

Additional Resources

Key Terms
14-1
C++ Programming: Program Design Including Data Structures, Fourth Edition
14-2
Lecture Notes
Overview
Chapter 14 covers two important concepts in object-oriented programming: operator
overloading and templates. Students will explore how to overload the standard operators
in user-defined classes. They will also learn about the use of the this pointer and
friend functions in user-defined classes. Finally, students will examine how to create
class and function templates in order to provide generic code in a program.
Objectives
In this chapter, the student will:
 Learn about overloading
 Become aware of the restrictions on operator overloading
 Examine the pointer this
 Learn about friend functions
 Explore the members and nonmembers of a class
 Discover how to overload various operators
 Learn about templates
 Explore how to construct function templates and class templates
Teaching Tips
Why Operator Overloading is Needed
1. Use the clockType class to illustrate why operator overloading is beneficial for userdefined classes.
2. Review the definition of operator overloading.
Teaching
Tip
Emphasize that clients of a class find it much more convenient and intuitive to
use standard operators to perform operations on objects of the class. Use the
<string> header file as an example of how operator overloading can ease the
task of programming. Point out that this is another form of encapsulation: the
client is aware that the operators work as expected, but is unaware of the
implementation details.
C++ Programming: Program Design Including Data Structures, Fourth Edition
14-3
Operator Overloading
1. List the standard operators that C++ overloads, including the arithmetic operators and
the stream extraction and insertion operators.
2. Explain that C++ allows programmers to overload most operators to work with a
specific application.
Teaching
Tip
Note that C++ does not allow you to create new operators.
3. Define the term operator function and note the syntax for an operator function name.
Mention that operator is a reserved word in C++.
Syntax for Operation Functions
1. Examine the syntax of the heading of an operator function.
2. Remind students that the assignment and member selection operators are the only builtin operators in C++ for classes.
Teaching
Tip
Reiterate that all other standard operators for classes must be explicitly
overloaded. Students are probably more accustomed to using applications as
clients (with operator overloading already in place), so this might be somewhat
counterintuitive.
3. Describe the basic steps for overloading an operator.
Overloading an Operator: Some Restrictions
1. Step through the restrictions on operator overloading that are discussed in this section.
Teaching
Tip
Ask students what they think the basis is for some of the restrictions described in
this section. Which of them are they more likely to forget when overloading a
function (e.g., that the associativity of an overloaded function must stay the same
as the original) and why?
Pointer this
1. Describe the purpose of the pointer this in object-oriented programming.
2. Use Examples 14-1 and 14-2 to explain how the this operator is used in a program
and why it is so useful.
C++ Programming: Program Design Including Data Structures, Fourth Edition
14-4
Teaching
Tip
Emphasize that the this pointer cannot have its value changed; in other words,
it always points to the object that is calling the function in which it is used.
Teaching
Tip
Note that this is particularly useful in operator overloading. Ask students to
think of reasons why this might be the case.
Quick Quiz 1
1. What is operator overloading?
Answer: Operator overloading allows programmers to extend the definition of most of
the built-in operators so that they may be applied to classes.
2. The function heading for an operator function uses the reserved word
____________________.
Answer: operator
3. True or False: The associativity of an operator can be modified in an overloaded
operator function.
Answer: False
4. Every object maintains a hidden pointer to itself called the ____________________
pointer.
Answer: this
Friend Functions of Classes
1. Define a friend function and describe the purpose of friend functions in a class.
Teaching
Tip
Discuss the additional overhead involved with accessing private member
functions with accessor and mutator functions instead of friend functions. Ask
students to examine the example in this section and think about how it would be
implemented without the use of friend functions.
2. Examine the syntax of a friend function prototype and discuss its placement in the
header file of a class.
3. Discuss the implementation of a friend function. Use Example 14-3 to illustrate how a
friend function is typically used in a class.
C++ Programming: Program Design Including Data Structures, Fourth Edition
14-5
Operator Functions as Member Functions and Nonmember Functions
1. Step through the rules for declaring operator functions as member functions and
nonmember functions.
Teaching
Tip
Mention that nonmember functions are primarily used for operator overloading.
Note that the C++ ternary operator cannot be overloaded.
2. Review the rectangleType class in this section to prepare for the following
examples of operator overloading.
Overloading Binary Operators
1. Describe how to overload a binary operator as a member function. Use Example 14-4 to
illustrate.
2. Describe how to overload a binary operator as a nonmember function. Use Example 145 to illustrate.
Teaching
Tip
Emphasize that in the function heading of a friend function definition, the name
of the class and scope resolution operator are not included, because a friend
function is not a member of the class.
Overloading the Stream Insertion (<<) and Stream Extraction (>>) Operators
1. Explain why an operator function that overloads the insertion or extraction operator
must be a nonmember function of a class.
2. Describe how to overload the stream insertion operator.
Teaching
Tip
Verify that students understand why both parameters in the overloaded stream
insertion function are reference parameters, as well as why the second parameter
is declared const.
3. Explain the mechanics of the return type of stream operators and why it must be a
reference type.
4. Briefly describe how to overload the stream extraction operator.
5. Use Example 14-6 to illustrate how stream insertion and extraction operators are
overloaded as nonmember functions in a class.
C++ Programming: Program Design Including Data Structures, Fourth Edition
14-6
Overloading the Assignment (=) Operator
1. Review how the built-in assignment operator produces a shallow copy for classes with
pointer member variables.
2. Examine the syntax for an overloaded assignment operator function prototype and
definition. In particular, note the constant reference return type and use of the this
pointer.
Teaching
Tip
Students may be intimated by the code in this section. Spend some additional
time on the explanation in this section of why self-assignments should be
prevented for the assignment operator.
3. Use Example 14-7 to illustrate how to overload the assignment operator.
Overloading Unary Operators
1. Describe the parameters for member and nonmember functions of overloaded unary
operators.
2. Examine the general syntax for the function prototype and definition of an overloaded
pre-increment operator as a member function.
3. Examine the general syntax for the function prototype and definition of an overloaded
pre-increment operator as a nonmember function.
4. Examine the general syntax for the function prototype and definition of an overloaded
post-increment operator as a member function.
5. Examine the general syntax for the function prototype and definition of an overloaded
post-increment operator as a nonmember function.
Teaching
Tip
Verify that students understand why the post-increment version of an overloaded
increment operator needs two parameters. What does the compiler do when the
second dummy parameter is not included?
6. Review the two definitions of the rectangleType class to consolidate the
understanding of overloaded member and nonmember operator functions.
Operator Overloading: Member versus Nonmember
1. Discuss when to use a member function or nonmember function for operation functions
that can be implemented in either way. Mention that the text advocates the use of
member operator functions whenever possible.
C++ Programming: Program Design Including Data Structures, Fourth Edition
14-7
Classes and Pointer Member Variables (Revisited)
1. Review the three functions a class with pointer member variables should include: an
overloaded assignment operator, a copy constructor, and a destructor.
Operator Overloading: One Final Word
1. Review overloaded functions with the modified clockType class and the “Complex
Numbers” Programming Example in this section.
Teaching
Tip
Ask your students to work in small groups and code the overloaded subtraction
and division functions for the “Complex Numbers” Programming Example. This
will give them firsthand experience with coding overloaded operators and
increase their comfort level when programming on their own.
Quick Quiz 2
1. A(n) ____________________ function is a nonmember function that has access to all
the public and private variables of a class.
Answer: friend
2. Which operator functions cannot be overloaded as friend functions?
Answer: (), [], ->, or =
3. True or False: The stream extraction and stream insertion operators must be overloaded
as member functions.
Answer: True
4. True or False: The body of an overloaded assignment operator should include selfassignments.
Answer: False
Overloading the Array Index (Subscript) Operator ([])
1. Remind the students that an overloaded subscript operator must be a member of the
class.
2. Explain that the subscript operator must handle two cases: one for constant arrays and
the other for nonconstant arrays.
3. Examine the syntax for the function prototypes and definitions of the overloaded array
subscript operator.
C++ Programming: Program Design Including Data Structures, Fourth Edition
14-8
4. Step through the “newString” Programming Example in this section to illustrate the
use of the overloaded array subscript operator.
Teaching
Tip
Look at the <string> header file again and ask your students to comment on
the similarities and differences of the string class definition with the
newString class definition, particularly in terms of functions and operating
overloading. Do they think the function implementations are similar?
Function Overloading
1. Introduce the concept of function overloading.
2. Relate operator overloading to function overloading.
3. Discuss the use of multiple constructors as an example of function overloading.
Teaching
Tip
Note that this section is simply a quick review of the function overloading
concepts discussed in previous chapters. Students need to have an understanding
of function overloading to grasp the importance of templates, which will be
discussed next.
Templates
1. Define the terms function template and class template.
Teaching
Tip
Emphasize the importance of templates in any object-oriented programming
language. Note that some programming languages use the term generics to
describe the use of templates.
2. Examine the syntax for declaring a template. Emphasize that the type is a parameter to
the template, much like a variable is a parameter to a function.
Function Templates
1. Explain that templates can simplify the process of overloading functions by providing
one function that can take multiple parameter types. Illustrate this concept with the
function larger in this section (Example 14-8).
C++ Programming: Program Design Including Data Structures, Fourth Edition
14-9
Class Templates
1. Explain how class templates can be used to write a single code segment for a set of
related classes.
2. Examine the syntax for declaring a class template.
3. Define the term parameterized type.
Teaching
Tip
Mention that the classes in the C++ Standard Library are templates.
4. Explain what an instantiation of a class template is.
Teaching
Tip
Emphasize that user-defined templates can be instantiated with built-in types or
user-defined types.
5. Compare the listType class with the listType template to demonstrate the
usefulness of class templates.
6. Explain why separating a class template into a header and implementation file (as
described thus far in the text) is a problem for the compiler. Describe solutions to this
problem.
Teaching
Tip
Verify that students understand how to compile class templates. Although this
text provides a solution of placing both the class definition and implementation
in the same file, it might be useful to show students an example of a class
template with separate files. In this scenario, you would place a directive to
include the implementation file at the end of the header file.
Quick Quiz 3
1. C++ simplifies the process of overloading functions by providing
____________________.
Answer: function templates
2. Class templates are also called ____________________ types.
Answer: parameterized
3. True or False: Including multiple constructors of a class is an example of function
overloading.
Answer: True
C++ Programming: Program Design Including Data Structures, Fourth Edition
14-10
4. True or False: A template instantiation can only be created with a built-in type.
Answer: False
Class Discussion Topics
1. Moderate a discussion on whether friend functions violate the principles of objectoriented programming by providing access to private members of a class. Ask your
students to explain their reasoning on either side of the argument. Discuss advantages of
friend functions that are object-oriented in nature, such as the ability to use an operator
function as a friend of more than one class.
2. Remind students that some overloaded operators, such as assignment operators and
array subscript operators, must be members of that class. Ask students to speculate
about the reasoning behind this requirement.
3. Review the different approaches to compiling class templates. Which do your students
think is the best approach and why?
Additional Projects
1. Enhance the birthday program from Chapter 13 to include an overloaded assignment
operator for the birthday class, as well as overloaded assignment and relational
operators for the date class. Then, modify the sort capability of the program to sort the
array either on the name or date. The sort will use the overloaded operators. Write a
main program that tests these new functionalities.
2.
Chapter 7 included a project that simulates a questionnaire to find a roommate. In this
program, the user is prompted with various questions that might determine a suitable
match. An overloaded function, called match, evaluates whether their preferences
match your own. Modify this function to be a function template so that it can take any
parameter and return the appropriate Boolean value based on a match. Make the
necessary changes to the rest of the program to test the function template.
Additional Resources
1. Operator Overloading Guidelines:
www.informit.com/guides/content.asp?g=cplusplus&seqNum=23&rl=1
2. Overloading Operators; The keyword this:
www.cplusplus.com/doc/tutorial/classes2.html
3. C++ Function Templates:
www.codebeach.com/tutorials/cplusplus-function-templates.asp
C++ Programming: Program Design Including Data Structures, Fourth Edition
14-11
4. Class Templates:
www.codersource.net/cpp_class_templates.html
Key Terms
 Class template: allows you to write a single code segment for a set of related classes
 Complex number: a number of the form, a + ib, where i2 = -1, and a and b are real
numbers
 Conversion constructor: single-parameter function that converts its argument to an
object of the constructor’s class
 Friend function: nonmember function of a class that has access to all the members of
the class
 Function template: simplifies the process of overloading functions by allowing you to
write a single code segment for a set of related functions
 Operator function: function that overloads an operator
 Operator overloading: allows the programmer to extend the definitions of most of the
standard operators so that operators—such as relational operators, arithmetic operators,
the insertion operator for data output, and the extraction operator for data input— can
be used to manipulate class objects
 Parameterized types: class templates are called parameterized types because, based on
the parameter type, a specific class is generated
 Templates: enable the programmer to write generic code for functions and classes
Download