- •Contents
- •Introduction
- •Who This Book Is For
- •What This Book Covers
- •How This Book Is Structured
- •What You Need to Use This Book
- •Conventions
- •Source Code
- •Errata
- •p2p.wrox.com
- •The Basics of C++
- •The Obligatory Hello, World
- •Namespaces
- •Variables
- •Operators
- •Types
- •Conditionals
- •Loops
- •Arrays
- •Functions
- •Those Are the Basics
- •Diving Deeper into C++
- •Pointers and Dynamic Memory
- •Strings in C++
- •References
- •Exceptions
- •The Many Uses of const
- •C++ as an Object-Oriented Language
- •Declaring a Class
- •Your First Useful C++ Program
- •An Employee Records System
- •The Employee Class
- •The Database Class
- •The User Interface
- •Evaluating the Program
- •What Is Programming Design?
- •The Importance of Programming Design
- •Two Rules for C++ Design
- •Abstraction
- •Reuse
- •Designing a Chess Program
- •Requirements
- •Design Steps
- •An Object-Oriented View of the World
- •Am I Thinking Procedurally?
- •The Object-Oriented Philosophy
- •Living in a World of Objects
- •Object Relationships
- •Abstraction
- •Reusing Code
- •A Note on Terminology
- •Deciding Whether or Not to Reuse Code
- •Strategies for Reusing Code
- •Bundling Third-Party Applications
- •Open-Source Libraries
- •The C++ Standard Library
- •Designing with Patterns and Techniques
- •Design Techniques
- •Design Patterns
- •The Reuse Philosophy
- •How to Design Reusable Code
- •Use Abstraction
- •Structure Your Code for Optimal Reuse
- •Design Usable Interfaces
- •Reconciling Generality and Ease of Use
- •The Need for Process
- •Software Life-Cycle Models
- •The Stagewise and Waterfall Models
- •The Spiral Method
- •The Rational Unified Process
- •Software-Engineering Methodologies
- •Extreme Programming (XP)
- •Software Triage
- •Be Open to New Ideas
- •Bring New Ideas to the Table
- •Thinking Ahead
- •Keeping It Clear
- •Elements of Good Style
- •Documenting Your Code
- •Reasons to Write Comments
- •Commenting Styles
- •Comments in This Book
- •Decomposition
- •Decomposition through Refactoring
- •Decomposition by Design
- •Decomposition in This Book
- •Naming
- •Choosing a Good Name
- •Naming Conventions
- •Using Language Features with Style
- •Use Constants
- •Take Advantage of const Variables
- •Use References Instead of Pointers
- •Use Custom Exceptions
- •Formatting
- •The Curly Brace Alignment Debate
- •Coming to Blows over Spaces and Parentheses
- •Spaces and Tabs
- •Stylistic Challenges
- •Introducing the Spreadsheet Example
- •Writing Classes
- •Class Definitions
- •Defining Methods
- •Using Objects
- •Object Life Cycles
- •Object Creation
- •Object Destruction
- •Assigning to Objects
- •Distinguishing Copying from Assignment
- •The Spreadsheet Class
- •Freeing Memory with Destructors
- •Handling Copying and Assignment
- •Different Kinds of Data Members
- •Static Data Members
- •Const Data Members
- •Reference Data Members
- •Const Reference Data Members
- •More about Methods
- •Static Methods
- •Const Methods
- •Method Overloading
- •Default Parameters
- •Inline Methods
- •Nested Classes
- •Friends
- •Operator Overloading
- •Implementing Addition
- •Overloading Arithmetic Operators
- •Overloading Comparison Operators
- •Building Types with Operator Overloading
- •Pointers to Methods and Members
- •Building Abstract Classes
- •Using Interface and Implementation Classes
- •Building Classes with Inheritance
- •Extending Classes
- •Overriding Methods
- •Inheritance for Reuse
- •The WeatherPrediction Class
- •Adding Functionality in a Subclass
- •Replacing Functionality in a Subclass
- •Respect Your Parents
- •Parent Constructors
- •Parent Destructors
- •Referring to Parent Data
- •Casting Up and Down
- •Inheritance for Polymorphism
- •Return of the Spreadsheet
- •Designing the Polymorphic Spreadsheet Cell
- •The Spreadsheet Cell Base Class
- •The Individual Subclasses
- •Leveraging Polymorphism
- •Future Considerations
- •Multiple Inheritance
- •Inheriting from Multiple Classes
- •Naming Collisions and Ambiguous Base Classes
- •Interesting and Obscure Inheritance Issues
- •Special Cases in Overriding Methods
- •Copy Constructors and the Equals Operator
- •The Truth about Virtual
- •Runtime Type Facilities
- •Non-Public Inheritance
- •Virtual Base Classes
- •Class Templates
- •Writing a Class Template
- •How the Compiler Processes Templates
- •Distributing Template Code between Files
- •Template Parameters
- •Method Templates
- •Template Class Specialization
- •Subclassing Template Classes
- •Inheritance versus Specialization
- •Function Templates
- •Function Template Specialization
- •Function Template Overloading
- •Friend Function Templates of Class Templates
- •Advanced Templates
- •More about Template Parameters
- •Template Class Partial Specialization
- •Emulating Function Partial Specialization with Overloading
- •Template Recursion
- •References
- •Reference Variables
- •Reference Data Members
- •Reference Parameters
- •Reference Return Values
- •Deciding between References and Pointers
- •Keyword Confusion
- •The const Keyword
- •The static Keyword
- •Order of Initialization of Nonlocal Variables
- •Types and Casts
- •typedefs
- •Casts
- •Scope Resolution
- •Header Files
- •C Utilities
- •Variable-Length Argument Lists
- •Preprocessor Macros
- •How to Picture Memory
- •Allocation and Deallocation
- •Arrays
- •Working with Pointers
- •Array-Pointer Duality
- •Arrays Are Pointers!
- •Not All Pointers Are Arrays!
- •Dynamic Strings
- •C-Style Strings
- •String Literals
- •The C++ string Class
- •Pointer Arithmetic
- •Custom Memory Management
- •Garbage Collection
- •Object Pools
- •Function Pointers
- •Underallocating Strings
- •Memory Leaks
- •Double-Deleting and Invalid Pointers
- •Accessing Out-of-Bounds Memory
- •Using Streams
- •What Is a Stream, Anyway?
- •Stream Sources and Destinations
- •Output with Streams
- •Input with Streams
- •Input and Output with Objects
- •String Streams
- •File Streams
- •Jumping around with seek() and tell()
- •Linking Streams Together
- •Bidirectional I/O
- •Internationalization
- •Wide Characters
- •Non-Western Character Sets
- •Locales and Facets
- •Errors and Exceptions
- •What Are Exceptions, Anyway?
- •Why Exceptions in C++ Are a Good Thing
- •Why Exceptions in C++ Are a Bad Thing
- •Our Recommendation
- •Exception Mechanics
- •Throwing and Catching Exceptions
- •Exception Types
- •Throwing and Catching Multiple Exceptions
- •Uncaught Exceptions
- •Throw Lists
- •Exceptions and Polymorphism
- •The Standard Exception Hierarchy
- •Catching Exceptions in a Class Hierarchy
- •Writing Your Own Exception Classes
- •Stack Unwinding and Cleanup
- •Catch, Cleanup, and Rethrow
- •Use Smart Pointers
- •Common Error-Handling Issues
- •Memory Allocation Errors
- •Errors in Constructors
- •Errors in Destructors
- •Putting It All Together
- •Why Overload Operators?
- •Limitations to Operator Overloading
- •Choices in Operator Overloading
- •Summary of Overloadable Operators
- •Overloading the Arithmetic Operators
- •Overloading Unary Minus and Unary Plus
- •Overloading Increment and Decrement
- •Overloading the Subscripting Operator
- •Providing Read-Only Access with operator[]
- •Non-Integral Array Indices
- •Overloading the Function Call Operator
- •Overloading the Dereferencing Operators
- •Implementing operator*
- •Implementing operator->
- •What in the World Is operator->* ?
- •Writing Conversion Operators
- •Ambiguity Problems with Conversion Operators
- •Conversions for Boolean Expressions
- •How new and delete Really Work
- •Overloading operator new and operator delete
- •Overloading operator new and operator delete with Extra Parameters
- •Two Approaches to Efficiency
- •Two Kinds of Programs
- •Is C++ an Inefficient Language?
- •Language-Level Efficiency
- •Handle Objects Efficiently
- •Use Inline Methods and Functions
- •Design-Level Efficiency
- •Cache as Much as Possible
- •Use Object Pools
- •Use Thread Pools
- •Profiling
- •Profiling Example with gprof
- •Cross-Platform Development
- •Architecture Issues
- •Implementation Issues
- •Platform-Specific Features
- •Cross-Language Development
- •Mixing C and C++
- •Shifting Paradigms
- •Linking with C Code
- •Mixing Java and C++ with JNI
- •Mixing C++ with Perl and Shell Scripts
- •Mixing C++ with Assembly Code
- •Quality Control
- •Whose Responsibility Is Testing?
- •The Life Cycle of a Bug
- •Bug-Tracking Tools
- •Unit Testing
- •Approaches to Unit Testing
- •The Unit Testing Process
- •Unit Testing in Action
- •Higher-Level Testing
- •Integration Tests
- •System Tests
- •Regression Tests
- •Tips for Successful Testing
- •The Fundamental Law of Debugging
- •Bug Taxonomies
- •Avoiding Bugs
- •Planning for Bugs
- •Error Logging
- •Debug Traces
- •Asserts
- •Debugging Techniques
- •Reproducing Bugs
- •Debugging Reproducible Bugs
- •Debugging Nonreproducible Bugs
- •Debugging Memory Problems
- •Debugging Multithreaded Programs
- •Debugging Example: Article Citations
- •Lessons from the ArticleCitations Example
- •Requirements on Elements
- •Exceptions and Error Checking
- •Iterators
- •Sequential Containers
- •Vector
- •The vector<bool> Specialization
- •deque
- •list
- •Container Adapters
- •queue
- •priority_queue
- •stack
- •Associative Containers
- •The pair Utility Class
- •multimap
- •multiset
- •Other Containers
- •Arrays as STL Containers
- •Strings as STL Containers
- •Streams as STL Containers
- •bitset
- •The find() and find_if() Algorithms
- •The accumulate() Algorithms
- •Function Objects
- •Arithmetic Function Objects
- •Comparison Function Objects
- •Logical Function Objects
- •Function Object Adapters
- •Writing Your Own Function Objects
- •Algorithm Details
- •Utility Algorithms
- •Nonmodifying Algorithms
- •Modifying Algorithms
- •Sorting Algorithms
- •Set Algorithms
- •The Voter Registration Audit Problem Statement
- •The auditVoterRolls() Function
- •The getDuplicates() Function
- •The RemoveNames Functor
- •The NameInList Functor
- •Testing the auditVoterRolls() Function
- •Allocators
- •Iterator Adapters
- •Reverse Iterators
- •Stream Iterators
- •Insert Iterators
- •Extending the STL
- •Why Extend the STL?
- •Writing an STL Algorithm
- •Writing an STL Container
- •The Appeal of Distributed Computing
- •Distribution for Scalability
- •Distribution for Reliability
- •Distribution for Centrality
- •Distributed Content
- •Distributed versus Networked
- •Distributed Objects
- •Serialization and Marshalling
- •Remote Procedure Calls
- •CORBA
- •Interface Definition Language
- •Implementing the Class
- •Using the Objects
- •A Crash Course in XML
- •XML as a Distributed Object Technology
- •Generating and Parsing XML in C++
- •XML Validation
- •Building a Distributed Object with XML
- •SOAP (Simple Object Access Protocol)
- •. . . Write a Class
- •. . . Subclass an Existing Class
- •. . . Throw and Catch Exceptions
- •. . . Read from a File
- •. . . Write to a File
- •. . . Write a Template Class
- •There Must Be a Better Way
- •Smart Pointers with Reference Counting
- •Double Dispatch
- •Mix-In Classes
- •Object-Oriented Frameworks
- •Working with Frameworks
- •The Model-View-Controller Paradigm
- •The Singleton Pattern
- •Example: A Logging Mechanism
- •Implementation of a Singleton
- •Using a Singleton
- •Example: A Car Factory Simulation
- •Implementation of a Factory
- •Using a Factory
- •Other Uses of Factories
- •The Proxy Pattern
- •Example: Hiding Network Connectivity Issues
- •Implementation of a Proxy
- •Using a Proxy
- •The Adapter Pattern
- •Example: Adapting an XML Library
- •Implementation of an Adapter
- •Using an Adapter
- •The Decorator Pattern
- •Example: Defining Styles in Web Pages
- •Implementation of a Decorator
- •Using a Decorator
- •The Chain of Responsibility Pattern
- •Example: Event Handling
- •Implementation of a Chain of Responsibility
- •Using a Chain of Responsibility
- •Example: Event Handling
- •Implementation of an Observer
- •Using an Observer
- •Chapter 1: A Crash Course in C++
- •Chapter 3: Designing with Objects
- •Chapter 4: Designing with Libraries and Patterns
- •Chapter 5: Designing for Reuse
- •Chapter 7: Coding with Style
- •Chapters 8 and 9: Classes and Objects
- •Chapter 11: Writing Generic Code with Templates
- •Chapter 14: Demystifying C++ I/O
- •Chapter 15: Handling Errors
- •Chapter 16: Overloading C++ Operators
- •Chapter 17: Writing Efficient C++
- •Chapter 19: Becoming Adept at Testing
- •Chapter 20: Conquering Debugging
- •Chapter 24: Exploring Distributed Objects
- •Chapter 26: Applying Design Patterns
- •Beginning C++
- •General C++
- •I/O Streams
- •The C++ Standard Library
- •C++ Templates
- •Integrating C++ and Other Languages
- •Algorithms and Data Structures
- •Open-Source Software
- •Software-Engineering Methodology
- •Programming Style
- •Computer Architecture
- •Efficiency
- •Testing
- •Debugging
- •Distributed Objects
- •CORBA
- •XML and SOAP
- •Design Patterns
- •Index
Chapter 16
|
|
Method or |
|
|
|
Name or |
Global Friend |
When to |
|
Operator |
Category |
Function |
Overload |
Sample Prototype |
|
|
|
|
|
operator delete |
Memory |
Method |
Whenever you |
void operator |
operator delete[] |
deallocation |
recommended |
overload the |
delete(void* ptr) |
|
routines |
|
memory |
throw(); |
|
|
|
allocation |
|
|
|
|
routines |
void operator |
|
|
|
|
delete[](void* ptr) |
|
|
|
|
throw(); |
operator* |
Dereferencing |
Method |
Useful for |
E& operator*() |
operator-> |
operators |
required for |
smart pointers |
const; |
|
|
operator-> |
|
|
|
|
|
|
E* operator->() |
|
|
Method |
|
const; |
|
|
recommended |
|
|
|
|
for operator* |
|
|
operator& |
Address-of |
N/A |
Never |
N/A |
|
operator |
|
|
|
operator->* |
Dereference |
N/A |
Never |
N/A |
|
pointer-to- |
|
|
|
|
member |
|
|
|
operator, |
Comma |
N/A |
Never |
N/A |
|
operator |
|
|
|
operator type() |
Conversion, |
Method |
When you |
operator type() |
|
or cast, |
required |
want to |
const; |
|
operators |
|
provide |
|
|
(separate |
|
conversions |
|
|
operator for |
|
from your |
|
|
each type) |
|
class to other |
|
|
|
|
types |
|
|
|
|
|
|
Overloading the Arithmetic Operators
In Chapter 9, you learned how to write the binary arithmetic operators and the shorthand arithmetic assignment operators. However, you did not yet learn how to overload all of the arithmetic operators.
Overloading Unary Minus and Unary Plus
C++ has several unary arithmetic operators. Two of these are unary minus and unary plus. You’ve probably used unary minus, but you might be surprised to learn about unary plus. Here is an example of these operators using ints:
438
Overloading C++ Operators
int i, j = 4;
i = -j; // Unary minus i = +i; // Unary plus
j = +(-i); // Apply unary plus to the result of applying unary minus to i. j = -(-i); // Apply unary minus to the result of applying unary minus to i.
Unary minus negates the operand, while unary plus returns the operand directly. The result of unary plus or minus is not an lvalue: you can’t assign to it. This means you should return a const object when you overload them. However, note that you can apply unary plus or unary minus to the result of unary plus or unary minus. Because you’re applying these operations to a const temporary object, you must make operator- and operator+ themselves const; otherwise, the compiler won’t let you call them on the const temporary.
Here is an example of a SpreadsheetCell class definition with an overloaded operator-. Unary plus is usually a no-op, so this class doesn’t bother to overload it.
class SpreadsheetCell
{
public:
// Omitted for brevity. Consult Chapter 9 for details.
friend const SpreadsheetCell operator+(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);
friend const SpreadsheetCell operator-(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);
friend const SpreadsheetCell operator*(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);
friend const SpreadsheetCell operator/(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);
SpreadsheetCell& operator+=(const SpreadsheetCell& rhs); SpreadsheetCell& operator-=(const SpreadsheetCell& rhs); SpreadsheetCell& operator*=(const SpreadsheetCell& rhs); SpreadsheetCell& operator/=(const SpreadsheetCell& rhs); const SpreadsheetCell operator-() const;
protected:
// Omitted for brevity. Consult Chapter 9 for details.
};
Here is the definition of the unary operator-.
const SpreadsheetCell SpreadsheetCell::operator-() const
{
SpreadsheetCell newCell(*this);
newCell.set(-mValue); // call set to update mValue and mStr
return (newCell);
}
operator- doesn’t change the operand, so this method must construct a new SpreadsheetCell with the negated value, and return a copy of it. Thus, it can’t return a reference.
Overloading Increment and Decrement
Recall that there are four ways to add one to a variable:
439
Chapter 16
i = i + 1; i += 1;
++i;
i++;
The last two are called the increment operators. The first form is prefix increment, which adds one to the variable, then returns the newly incremented value for use in the rest of the expression. The second form is postfix increment, which returns the old (nonincremented) value for use in the rest of the expression. The decrement operators function similarly.
The two possible meanings for operator++ and operator-- (prefix and postfix) present a problem when you want to overload them. When you write an overloaded operator++, for example, how do you specify whether you are overloading the prefix or the postfix version? C++ introduced a hack to allow you to make this distinction: the prefix versions of operator++ and operator-- take no arguments, while the postfix versions take one unused argument of type int.
If you want to overload these operators for your SpreadsheetCell class, the prototypes would look like this:
class SpreadsheetCell |
|
{ |
|
public: |
|
// Omitted for brevity. Consult Chapter 9 |
for details. |
SpreadsheetCell& operator++(); // Prefix |
|
const SpreadsheetCell operator++(int); // |
Postfix |
SpreadsheetCell& operator--(); // Prefix |
|
const SpreadsheetCell operator--(int); // |
Postfix |
protected: |
|
// Omitted for brevity. Consult Chapter 9 |
for details. |
}; |
|
The C++ standard specifies that the prefix versions of increment and decrement return an lvalue, so they can’t return a const value. The return value in the prefix forms is the same as the end value of the operand, so prefix increment and decrement can return a reference to the object on which they are called. The postfix versions of increment and decrement, however, return values that are different from the end values of the operands, so they cannot return references.
Here are the implementations of these operators:
SpreadsheetCell& SpreadsheetCell::operator++()
{
set(mValue + 1); return (*this);
}
const SpreadsheetCell SpreadsheetCell::operator++(int)
{
SpreadsheetCell oldCell(*this); // Save the current value before incrementing set(mValue + 1); // Increment
return (oldCell); // Return the old value.
}
SpreadsheetCell& SpreadsheetCell::operator--()
440
Overloading C++ Operators
{
set(mValue - 1); return (*this);
}
const SpreadsheetCell SpreadsheetCell::operator--(int)
{
SpreadsheetCell oldCell(*this); // Save the current value before incrementing set(mValue - 1); // Increment
return (oldCell); // Return the old value.
}
Now you can increment and decrement your SpreadsheetCell objects to your heart’s content!
SpreadsheetCell c1, c2; c1.set(4);
c2.set(4);
c1++;
++c1;
Recall that increment and decrement also work on pointers. When you write classes that are smart pointers or iterators, you can overload operator++ and operator-- to provide pointer incrementing and decrementing. You can see this topic in action in Chapter 23, in which you learn how to write your own STL iterators.
Overloading the Bitwise and
Binar y Logical Operators
The bitwise operators are similar to the arithmetic operators, and the bitwise shorthand assignment operators are similar to the arithmetic shorthand assignment operators. However, they are significantly less common, so we do not show examples here. The table in the “Summary of Overloadable Operators” section shows sample prototypes, so you should be able to implement them easily if the need ever arises.
The logical operators are trickier. We don’t recommend overloading && and ||. These operators don’t really apply to individual types: they aggregate results of Boolean expressions. Additionally, you lose the short-circuit evaluation. Thus, it rarely makes sense to overload them for specific types.
Overloading the Inser tion and
Extraction Operators
In C++, you use operators not only for arithmetic operations, but also for reading from and writing to streams. For example, when you write ints and strings to cout you use the insertion operator, <<:
int number = 10;
cout << “The number is “ << number << endl;
When you read from streams you use the extraction operator, >>:
441
Chapter 16
int number; string str;
cin >> number >> str;
You can write insertion and extraction operators that work on your classes as well, so that you can read and write them like this:
SpreadsheetCell myCell, anotherCell, aThirdCell;
cin >> myCell >> anotherCell >> aThirdCell;
cout << myCell << “ “ << anotherCell << “ “ << aThirdCell << endl;
Before you write the insertion and extraction operators, you need to decide how you want to stream your class out and how you want to read it in. For SpreadsheetCells it makes sense to read and write strings because all doubles can be read as strings (and converted back to doubles), but not vice versa.
The object on the left of an insertion or extraction operator is the istream or ostream (such as cin or cout), not a SpreadsheetCell object. Because you can’t add a method to the istream or ostream class, you should write the insertion and extraction operators as global friend functions of the SpreadsheetCell class. The declaration of these functions in your SpreadsheetCell class looks like this:
class SpreadsheetCell
{
public:
// Omitted for brevity
friend ostream& operator<<(ostream& ostr, const SpreadsheetCell& cell);
friend istream& operator>>(istream& istr, SpreadsheetCell& cell); // Omitted for brevity
};
By making the insertion operator take a reference to an ostream as its first parameter, you allow it to be used for file output streams, string output streams, cout, and cerr. See Chapter 14 for details. Similarly, by making the extraction operator take a reference to an istream, you can make it work on file input streams, string input streams, and cin.
The second parameter to operator<< and operator>> is a reference to the SpreadsheetCell object that you want to read or write. The insertion operator doesn’t change the SpreadsheetCell it writes, so that reference can be const. The extraction operator, however, modifies the SpreadsheetCell object, requiring the argument to be a non-const reference.
Both operators return a reference to the stream they were given as their first argument so that calls to the operator can be nested. Remember that the operator syntax is shorthand for calling the global operator>> or operator<< functions explicitly. Consider this line:
cin >> myCell >> anotherCell >> aThirdCell;
It’s actually shorthand for this line:
operator>>(operator>>(operator>>(cin, myCell), anotherCell), aThirdCell);
As you can see, the return value of the first call to operator>> is used as input to the next. Thus, you must return the stream reference so that it can be used in the next nested call. Otherwise, the nesting won’t compile.
442