Bruce Eckel's Thinking in C++, 2nd Ed
Contents
|
Prev
|
Next
Thinking in C++ 2nd ed (Beta) Version TICA14 - Contents
Thinking in C++ 2nd ed (Beta) Version TICA14 - Title Page
Thinking in C++ 2nd edition VERSION TICA14
Preface
Prerequisites
Thinking in C
Learning C++
Goals
Chapters
Exercises
Source code
Coding standards
Language standards
Language support
Seminars & CD Roms
Errors
Acknowledgements
1: Introduction to objects
The progress of abstraction
An object has an interface
The hidden implementation
Reusing the implementation
Inheritance: reusing the interface
Is-a vs. is-like-a relationships
Interchangeable objects with polymorphism
Creating and destroying objects
Exception handling: dealing with errors
Analysis and design
Phase 0: Make a plan
The mission statement
Phase 1: What are we making?
Phase 2: How will we build it?
Five stages of object design
Guidelines for object development
Phase 3: Build it
Phase 4: Iteration
Plans pay off
Why C++ succeeds
A better C
You’re already on the learning curve
Efficiency
Systems are easier to express and understand
Maximal leverage with libraries
Source-code reuse with templates
Error handling
Programming in the large
Strategies for transition
Guidelines
1. Training
2. Low-risk project
3. Model from success
4. Use existing class libraries
5. Don’t rewrite existing code in C++
Management obstacles
Startup costs
Performance issues
Common design errors
Summary
2: Making & using objects
The process of language translation
Interpreters
Compilers
The compilation process
Static type checking
Tools for separate compilation
Declarations vs. definitions
Function declaration syntax
A gotcha
Function definitions
Variable declaration syntax
Including headers
Standard C++ include format
Linking
Using libraries
How the linker searches a library
Secret additions
Using plain C libraries
Your first C++ program
Using the iostreams class
Namespaces
Fundamentals of program structure
"Hello, world!"
Running the compiler
More about iostreams
Character array concatenation
Reading input
Simple file manipulation
Introducing strings
Reading and writing files
Introducing vector
Summary
Exercises
3: The C in C++
Creating functions
Function return values
Using the C function library
Creating your own libraries with the librarian
Controlling execution
True and false
if-else
while
do-while
for
The break and continue Keywords
switch
Introduction to operators
Precedence
Auto increment and decrement
Introduction to data types
Basic built-in types
bool, true, & false
Specifiers
Introduction to Pointers
Modifying the outside object
Introduction to C++ references
Pointers and references as modifiers
Scoping
Defining variables on the fly
Specifying storage allocation
Global variables
Local variables
Register variables
static
extern
Linkage
Constants
Constant values
volatile
Operators and their use
Assignment
Mathematical operators
Introduction to preprocessor macros
Relational operators
Logical operators
Bitwise operators
Shift operators
Unary operators
The ternary operator
The comma operator
Common pitfalls when using operators
Casting operators
sizeof – an operator by itself
The asm keyword
Explicit operators
Composite type creation
Aliasing names with typedef
Combining variables with struct
Pointers and structs
Clarifying programs with enum
Saving memory with union
Arrays
Pointers and arrays
Pointer arithmetic
Debugging hints
Debugging flags
Preprocessor debugging flags
Run-time debugging flags
Turning variables and expressions into strings
The C assert( ) macro
Make: an essential tool for separate compilation
Make activities
Macros
Suffix Rules
Default targets
Makefiles in this book
An example makefile
Summary
Exercises
4: Data abstraction
A tiny C-like library
Dynamic storage allocation
What's wrong?
The basic object
What's an object?
Abstract data typing
Object details
Header file etiquette
Importance of using a common header file
The preprocessor directives #define, #ifdef and #endif
Preventing re-declaration of classes
A standard for class header files
Namespaces in headers (??)
Using headers in projects
Nested structures
Global scope resolution
Summary
Exercises
answers:
5: Hiding the implementation
Setting limits
C++ access control
protected
Friends
Nested friends
Is it pure?
Object layout
The class
Modifying Stash to use access control
Modifying Stack to use access control
Handle classes
Visible implementation
Reducing recompilation
Summary
Exercises
answers:
6: Initialization & cleanup
Guaranteed initialization with the constructor
Guaranteed cleanup with the destructor
Elimination of the definition block
for loops
Storage allocation
Stash with constructors and destructors
Stack with constructors & destructors
Aggregate initialization
Default constructors
Summary
Exercises
answers:
7: Function overloading & default arguments
More mangling
Overloading on return values
Type-safe linkage
Overloading example
Default arguments
unions
Summary
Exercises
answers:
8: Constants
Value substitution
const in header files
Safety consts
Aggregates
Differences with C
Pointers
Pointer to const
const pointer
Formatting
Assignment and type checking
Character array literals
Function arguments & return values
Passing by const value
Returning by const value
Temporaries
Passing and returning addresses
Standard argument passing
Classes
const and enum in classes
The constructor initializer list
“Constructors” for built-in types
Compile-time constants in classes
Type checking for enumerations
const objects & member functions
mutable: bitwise vs. memberwise const
ROMability
volatile
Summary
Exercises
9: Inline functions
Preprocessor pitfalls
Macros and access
Inline functions
Inlines inside classes
Access functions
Accessors and mutators
Inlines & the compiler
Limitations
Order of evaluation
Hidden activities in constructors & destructors
Forward referencing
Reducing clutter
More preprocessor features
Token pasting
Improved error checking
Summary
Exercises
10: Name control
Static elements from C
static variables inside functions
static class objects inside functions
Static object destructors
Controlling linkage
Confusion
Other storage class specifiers
Namespaces
Creating a namespace
Unnamed namespaces
Friends
Using a namespace
Scope resolution
The using directive
The using declaration
Static members in C++
Defining storage for static data members
static array initialization
Compile-time constants inside classes
Nested and local classes
static member functions
Static initialization dependency
What to do
Alternate linkage specifications
Summary
Exercises
11: ReferencesBE & the copy-constructor
Pointers in C++
References in C++
References in functions
const references
Pointer references
Argument-passing guidelines
The copy-constructor
Passing & returning by value
Passing & returning large objects
Function-call stack frame
Re-entrancy
Bitcopy versus initialization
Copy-construction
Temporary objects
Default copy-constructor
Alternatives to copy-construction
Preventing pass-by-value
Functions that modify outside objects
Pointers to members
Functions
An example
Summary
Exercises
12: BEOperator overloading
Warning & reassurance
Syntax
Overloadable operators
Unary operators
Increment & decrement
Binary operators
Arguments & return values
Return by value as const
return efficiency
Unusual operators
Operators you can’t overload
Nonmember operators
Basic guidelines
Overloading assignment
Behavior of operator=
Pointers in classes
Tracing the output
Automatic operator= creation
Automatic type conversion
Constructor conversion
Preventing constructor conversion
Operator conversion
Reflexivity
A perfect example: strings
Pitfalls in automatic type conversion
Hidden activities
Summary
Exercises
13: Dynamic object creation
Object creation
C’s approach to the heap
operator new
operator delete
A simple example
Memory manager overhead
Early examples redesigned
Heap-only string class
Stash for pointers
A test
The stack
new & delete for arrays
Making a pointer more like an array
Running out of storage
Overloading new & delete
Overloading global new & delete
Overloading new & delete for a class
Overloading new & delete for arrays
Constructor calls
Object placement
Summary
Exercises
14: Inheritance & composition
Composition syntax
Inheritance syntax
The constructor initializer list
Member object initialization
Built-in types in the initializer list
Combining composition & inheritance
Automatic destructor calls
Order of constructor & destructor calls
Name hiding
Functions that don’t automatically inherit
Choosing composition vs. inheritance
Subtyping
Specialization
private inheritance
Publicizing privately inherited members
protected
protected inheritance
Multiple inheritance
Incremental development
Upcasting
Why “upcasting”?
Downcasting
Upcasting and the copy-constructor (not indexed)
Composition vs. inheritance (revisited)
Pointer & reference upcasting
A crisis
Summary
Exercises
15: Polymorphism & virtual functions
Evolution of C++ programmers
Upcasting
The problem
Function call binding
virtual functions
Extensibility
How C++ implements late binding
Storing type information
Picturing virtual functions
Under the hood
Installing the vpointer
Objects are different
Why virtual functions?
Abstract base classes and pure virtual functions
Pure virtual definitions
Inheritance and the VTABLE
Object slicing
virtual functions & constructors
Order of constructor calls
Behavior of virtual functions inside constructors
Destructors and virtual destructors
Virtuals in destructors
Summary
Exercises
16: Introduction to templates
Containers & iterators
The need for containers
Overview of templates
The C approach
The Smalltalk approach
The template approach
Template syntax
Non-inline function definitions
Header files
The stack as a template
Constants in templates
Stash and stack as templates
The ownership problem
Stash as a template
stack as a template
Polymorphism & containers
BE a long journey
Summary
Exercises
Part 2: The Standard C++ Library
Library overview
17: Strings
What’s in a string
Creating and initializing C++ strings
Initialization limitations
Operating on strings
Appending, inserting and concatenating strings
Replacing string characters
Simple character replacement using the STL replace( ) algorithm
Concatenation using non-member overloaded operators
Searching in strings
Finding in reverse
Finding first/last of a set
Removing characters from strings
Stripping HTML tags
Comparing strings
Indexing with [ ] vs. at( )
Using iterators
Iterating in reverse
Strings and character traits
A string application
Summary
Exercises
18: Iostreams
Why iostreams?
True wrapping
Iostreams to the rescue
Sneak preview of operator overloading
Inserters and extractors
Manipulators
Common usage
Line-oriented input
Overloaded versions of get( )
Reading raw bytes
Error handling
File iostreams
Open modes
Iostream buffering
Using get( ) with a streambuf
Seeking in iostreams
Creating read/write files
stringstreams
strstreams
User-allocated storage
Output strstreams
Automatic storage allocation
Proving movement
A better way
Output stream formatting
Internal formatting data
Format fields
Width, fill and precision
An exhaustive example
Formatting manipulators
Manipulators with arguments
Creating manipulators
Effectors
Iostream examples
Code generation
Maintaining class library source
Detecting compiler errors
A simple datalogger
Generating test data
Verifying & viewing the data
Counting editor
Breaking up big files
Summary
Exercises
19: Templates in depth
The typename keyword
Typedefing a typename
Nontype template arguments
Default template arguments
Function templates
A memory allocation system
Applying a function to a TStack
Member function templates
Sstring & integer
A string on the stack
integer
Templates & inheritance
Design & efficiency
Preventing template bloat
Controlling instantiation
Template specialization
Explicit specification of template functions
Taking the address of a generated template function
Type induction in template functions
Template specializations
Partial specialization
Pointer specialization
Partial ordering of function templates
Member templates
Why virtual member template functions are disallowed
Nested template classes
Template-templates
Controlling template instantiation
The inclusion vs. separation models
The export keyword
Template programming idioms
The “curiously-recurring template”
Summary
20: STL Containers & Iterators
Containers and iterators
STL reference documentation
The Standard Template Library
The basic concepts
Containers of strings
Inheriting from STL containers
A plethora of iterators
Iterators in reversible containers
Iterator categories
Input: read-only, one pass
Output: write-only, one pass
Forward: multiple read/write
Bidirectional: operator--
Random-access: like a pointer
Is this really important?
Predefined iterators
IO stream iterators
Manipulating raw storage
Basic sequences: vector, list & deque
Basic sequence operations
vector
Cost of overflowing allocated storage
Inserting and erasing elements
deque
Converting between sequences
Cost of overflowing allocated storage
Checked random-access
list
Special list operations
list vs. set
Swapping all basic sequences
Robustness of lists
Performance comparison
set
Eliminating strtok( )
StreamTokenizer: a more flexible solution
A completely reusable tokenizer
stack
queue
Priority queues
Holding bits
bitset<n>
vector<bool>
Associative containers
Generators and fillers for associative containers
The magic of maps
A command-line argument tool
Multimaps and duplicate keys
Multisets
Combining STL containers
Cleaning up containers of pointers
Creating your own containers
Freely-available STL extensions
Summary
Exercises
21: STL Algorithms
Function objects
Classification of function objects
Automatic creation of function objects
Binders
Function pointer adapters
SGI extensions
A catalog of STL algorithms
Support tools for example creation
Filling & generating
Example
Counting
Example
Manipulating sequences
Example
Searching & replacing
Example
Comparing ranges
Example
Removing elements
Example
Sorting and operations on sorted ranges
Sorting
Example
Locating elements in sorted ranges
Example
Merging sorted ranges
Example
Set operations on sorted ranges
Example
Heap operations
Applying an operation to each element in a range
Examples
Numeric algorithms
Example
General utilities
Creating your own STL-style algorithms
Summary
Exercises
Part 3: Advanced Topics
22: Multiple inheritance
Perspective
Duplicate subobjects
Ambiguous upcasting
virtual base classes
The "most derived" class and virtual base initialization
"Tying off" virtual bases with a default constructor
Overhead
Upcasting
Persistence
MI-based persistence
Improved persistence
Avoiding MI
Repairing an interface
Summary
Exercises
23: Exception handling
Error handling in C
Throwing an exception
Catching an exception
The try block
Exception handlers
Termination vs. resumption
The exception specification
unexpected( )
set_unexpected( )
Better exception specifications?
Catching any exception
Rethrowing an exception
Uncaught exceptions
terminate( )
set_terminate( )
Function-level try blocks
Cleaning up
Constructors
Making everything an object
Exception matching
Standard exceptions
Programming with exceptions
When to avoid exceptions
Not for asynchronous events
Not for ordinary error conditions
Not for flow-of-control
You’re not forced to use exceptions
New exceptions, old code
Typical uses of exceptions
Always use exception specifications
Start with standard exceptions
Nest your own exceptions
Use exception hierarchies
Multiple inheritance
Catch by reference, not by value
Throw exceptions in constructors
Don’t cause exceptions in destructors
Avoid naked pointers
Overhead
Summary
Exercises
24: Run-time type identification
The “Shape” example
What is RTTI?
Two syntaxes for RTTI
Syntax specifics
typeid( ) with built-in types
Producing the proper type name
Nonpolymorphic types
Casting to intermediate levels
void pointers
Using RTTI with templates
References
Exceptions
Multiple inheritance
Sensible uses for RTTI
Revisiting the trash recycler
Mechanism & overhead of RTTI
Creating your own RTTI
Explicit cast syntax
static_cast
const_cast
reinterpret_cast
Summary
Exercises
XX: Maintaining system integrity
The canonical object form
An extended canonical form
Dynamic aggregation
Reference counting
Reference-counted class hierarchies
25: Design patterns
The pattern concept
The singleton
Variations on singleton
Classifying patterns
Features, idioms, patterns
Basic complexity hiding
Encapsulating object creation
Callbacks
Functor
Command
Strategy
Observer
The “interface” idiom
The “inner class” idiom
The observer example
Multiple dispatching
Visitor, a type of multiple dispatching
Efficiency
Flyweight
The composite
Evolving a design: the trash recycler
Improving the design
“Make more objects”
A pattern for prototyping creation
Trash subclasses
Parsing Trash from an external file
Recycling with prototyping
Abstracting usage
Applying double dispatching
Implementing the double dispatch
Applying the visitor pattern
More coupling?
RTTI considered harmful?
Summary
Exercises
26: Tools & topics
The code extractor
Debugging
assert( )
Trace macros
Trace file
Abstract base class for debugging
Tracking new/delete & malloc/free
CGI programming in C++
Encoding data for CGI
The CGI parser
Testing the CGI parser
Using POST
Handling mailing lists
Maintaining your list
Mailing to your list
A general information-extraction CGI program
Parsing the data files
Summary
Exercises
A: Coding style
File names
Begin and end comment tags
Parens, braces and indentation
Order of header inclusion
Include guards on header files
Use of namespaces
Use of require( ) and assure( )
B: Programming guidelines
C: Simulating virtual constructors
All-purpose virtual constructorsBE
A remaining conundrum
Destructor operation
A simpler alternative
D: Recommended reading
C
General C++
My own list of books
Depth & dark corners
Analysis & Design
The STL
Design Patterns
E:Compiler specifics
Index
Contents
|
Prev
|
Next
Go to CodeGuru.com
Contact:
webmaster@codeguru.com
© Copyright 1997-1999 CodeGuru