PDF Archive

Easily share your PDF documents with your contacts, on the Web and Social Networks.

Share a file Manage my documents Convert Recover PDF Search Help Contact



Thinking in C++ .pdf



Original filename: Thinking in C++.pdf
Title: Thinking in C++

This PDF 1.3 document has been generated by Microsoft Word - Thinking in C++ / Acrobat PDFWriter 4.0 for Windows, and has been sent on pdf-archive.com on 02/11/2011 at 17:49, from IP address 175.157.x.x. The current document download page has been viewed 2148 times.
File size: 2.2 MB (1104 pages).
Privacy: public file




Download original PDF file









Document preview


Thinking
In

C++
Bruce Eckel, Noman Laghari & Syed Kashif Haider

Presidents, Cool Soft Inc.
Home Departments
Gulshan e Iqbal & Federal B Area
http://www.coolsoft.com

What’s inside...
Thinking in C++ 2nd edition VERSION
TICA17Error! Bookmark not defined.

Why C++ succeeds ........................37

PrefaceError! Bookmark not
defined.
PrerequisitesError! Bookmark not defined.
Thinking in CError! Bookmark not defined.

Learning C++Error! Bookmark not defined.
Goals Error! Bookmark not defined.
ChaptersError! Bookmark not defined.
ExercisesError! Bookmark not defined.
Source codeError! Bookmark not defined.

A better C......................................38
You’re already on the learning curve 38
Efficiency......................................38
Systems are easier to express and
understand.....................................39
Maximal leverage with libraries.......39
Source-code reuse with templates ....39
Error handling................................39
Programming in the large ................40

Strategies for transition .................40
Guidelines .....................................40
Management obstacles....................42

Summary ..........................................43

Coding standardsError! Bookmark not defined.

2: Making & using objects 45

Language standardsError! Bookmark not defined.
Language support Error! Bookmark not defined.
The process of language translation45
Seminars & CD Roms Error! Bookmark not defined.Interpreters....................................46
ErrorsError! Bookmark not defined.
Compilers......................................46
AcknowledgementsError! Bookmark not defined. The compilation process .................47
Tools for separate compilation.....48

1: Introduction to objects

11

The progress of abstraction..........11
An object has an interface ............13
The hidden implementation..........15
Reusing the implementation .......16
Inheritance: reusing the interface17
Is-a vs. is-like-a relationships.......... 21

Interchangeable objects with
polymorphism.................................22
Creating and destroying objects ..25
Exception handling: dealing with
errors ................................................26
Analysis and design.......................27
Phase 0: Make a plan...................... 29
Phase 1: What are we making? ........ 30
Phase 2: How will we build it?........ 32
Phase 3: Build it ............................ 35
Phase 4: Iteration........................... 35
Plans pay off ................................. 37

Declarations vs. definitions.............49
Linking.........................................53
Using libraries ...............................54

Your first C++ program.................55
Using the iostreams class ................55
Namespaces...................................56
Fundamentals of program structure ..57
"Hello, world!" ..............................58
Running the compiler .....................59

More about iostreams ....................59
Character array concatenation..........60
Reading input ................................60
Simple file manipulation .................61

Introducing strings ........................62
Reading and writing files ..............64
Introducing vector..........................66
Summary ..........................................69
Exercises..........................................70

3: The C in C++

73

Creating functions .........................73
Using the C function library ............ 76
Creating your own libraries with the
librarian ........................................ 76

Controlling execution....................77
True and false................................ 77
if-else ........................................... 77
while............................................ 78
do-while....................................... 79
for ............................................... 80
The break and continue Keywords . 81
switch .......................................... 82
Recursion...................................... 84

Introduction to operators ..............84
Precedence.................................... 85
Auto increment and decrement ........ 85

Introduction to data types .............86
Basic built-in types ........................ 86
bool, true, & false ......................... 87
Specifiers...................................... 88
Introduction to Pointers.................. 90
Modifying the outside object ........... 94
Introduction to C++ references........ 96
Pointers and references as modifiers 97

Scoping............................................99
Defining variables on the fly ......... 100

Specifying storage allocation.....102
Global variables........................... 102
Local variables ............................ 103
static.......................................... 103
extern ........................................ 105
Constants.................................... 106
volatile....................................... 107

Operators and their use...............108
Assignment ................................. 108
Mathematical operators................ 108
Relational operators..................... 110
Logical operators......................... 110
Bitwise operators......................... 111
Shift operators............................. 111
Unary operators........................... 114
The ternary operator..................... 115
The comma operator .................... 115
Common pitfalls when using operators116
Casting operators......................... 116
sizeof – an operator by itself ......... 117
The asm keyword........................ 117
Explicit operators......................... 117

Composite type creation.............118
Aliasing names with typedef......... 118
Combining variables with struct ... 119
Clarifying programs with enum .... 122
Saving memory with union........... 123
Arrays ........................................ 124

Debugging hints .......................... 132
Debugging flags........................... 133
Turning variables and expressions into
strings......................................... 134
The C assert( ) macro................... 135

Make: an essential tool for separate
compilation................................... 136
Make activities............................. 137
Makefiles in this book.................. 139
An example makefile ................... 140

Summary ....................................... 142
Exercises....................................... 142

4: Data abstraction

145

A tiny C-like library.................... 146
Dynamic storage allocation ........... 149
Bad guesses ................................. 152

What's wrong? ............................. 153
The basic object........................... 154
What's an object? ........................ 160
Abstract data typing.................... 161
Object details ............................... 161
Header file etiquette.................... 163
Importance of header files............. 163
The multiple-declaration problem .. 165
The preprocessor directives #define,
#ifdef and #endif ......................... 165
A standard for header files ............ 166
Namespaces in headers................. 167
Using headers in projects.............. 167

Nested structures ......................... 168
Global scope resolution................. 171

Summary ....................................... 172
Exercises....................................... 172

5: Hiding the implementation
177
Setting limits ................................ 177
C++ access control...................... 178
protected.................................... 180

Friends .......................................... 180
Nested friends.............................. 182
Is it pure?.................................... 185

Object layout................................ 185
The class ....................................... 186
Modifying Stash to use access control188
Modifying Stack to use access control189

Handle classes ............................. 190
Hiding the implementation ............ 190
Reducing recompilation ................ 190

Summary ....................................... 193

Exercises .......................................193

6: Initialization & cleanup 195
Guaranteed initialization with the
constructor ....................................196
Guaranteed cleanup with the
destructor.......................................197
Elimination of the definition block199
for loops..................................... 201
Storage allocation ........................ 202

Stash with constructors and
destructors.....................................203
Stack with constructors &
destructors.....................................206
Aggregate initialization...............209
Default constructors ....................211
Summary........................................212
Exercises .......................................213

7: Function overloading &
default arguments
215
More name decoration.................216
Overloading on return values ........ 217
Type-safe linkage ........................ 217

Overloading example...................218
unions ............................................221
Default arguments........................225
Placeholder arguments.................. 226

Choosing overloading vs. default
arguments ......................................226
Summary........................................231
Exercises .......................................231

8: Constants

233

Value substitution ........................233

Classes .......................................... 247
const and enum in classes............. 247
Compile-time constants in classes.. 250
const objects & member functions. 253
ROMability................................. 257

volatile .......................................... 257
Summary ....................................... 259
Exercises....................................... 259

9: Inline functions

263

Preprocessor pitfalls .................... 263
Macros and access........................ 266

Inline functions............................ 267
Inlines inside classes..................... 267
Access functions.......................... 268

Stash & Stack with inlines......... 274
Inlines & the compiler................ 274
Limitations.................................. 274
Order of evaluation ...................... 275
Hidden activities in constructors &
destructors................................... 276

Forward referencing.................... 277
Reducing clutter........................... 277
More preprocessor features ....... 278
Token pasting.............................. 279

Improved error checking............ 279
Summary ....................................... 282
Exercises....................................... 282

10: Name control

285

Static elements from C............... 285
static variables inside functions..... 285
Controlling linkage....................... 289
Other storage class specifiers......... 291

Namespaces ................................. 291
Creating a namespace................... 291
Using a namespace ....................... 293

Static members in C++............... 297

const in header files..................... 234
Safety consts............................... 235
Aggregates.................................. 236
Differences with C....................... 236

Defining storage for static data
members..................................... 297
Nested and local classes................ 299
static member functions................ 300

Pointers ..........................................237

Static initialization dependency 303

Pointer to const ........................... 238
const pointer............................... 238
Assignment and type checking...... 239

Function arguments & return
values .............................................240
Passing by const value ................. 240
Returning by const value .............. 241
Passing and returning addresses..... 244

What to do ................................... 304

Alternate linkage specifications 306
Summary ....................................... 307
Exercises....................................... 307

11: References & the copyconstructor
309
Pointers in C++.............................309
References in C++........................310
References in functions................ 310
Argument-passing guidelines ........ 313

The copy-constructor..................313
Passing & returning by value......... 313
Copy-construction........................ 318
Default copy-constructor .............. 323
Alternatives to copy-construction .. 326

Pointers to members ....................327
Functions.................................... 328

Summary........................................331
Exercises .......................................331

12: Operator overloading 333
Warning & reassurance...............333
Syntax.............................................334
Overloadable operators ...............335
Unary operators........................... 335
Binary operators.......................... 340
Arguments & return values ........... 351
Unusual operators........................ 353
Operators you can’t overload......... 357

Running out of storage............... 394
Overloading new & delete......... 395
Overloading global new & delete... 396
Overloading new & delete for a class398
Overloading new & delete for arrays400
Constructor calls .......................... 402
Object placement ......................... 403

Summary ....................................... 405
Exercises....................................... 405

14: Inheritance & composition
407
Composition syntax..................... 407
Inheritance syntax........................ 409
The constructor initializer list... 411
Member object initialization.......... 411
Built-in types in the initializer list .. 411

Combining composition &
inheritance .................................... 412
Order of constructor & destructor calls414
Name hiding................................ 416
Functions that don’t automatically
inherit ......................................... 417

Choosing composition vs.
inheritance .................................... 418

Basic guidelines........................... 359

Subtyping.................................... 420
Specialization .............................. 422
private inheritance....................... 424

Overloading assignment .............360

protected....................................... 425

Nonmember operators.................357
Behavior of operator=................. 361

protected inheritance ................... 426

Automatic type conversion ........371

Multiple inheritance.................... 427
Incremental development........... 427
Upcasting...................................... 428

Constructor conversion................. 371
Operator conversion ..................... 373
A perfect example: strings............. 375
Pitfalls in automatic type conversion377

Summary........................................379
Exercises .......................................379

13: Dynamic object creation
381
Object creation .............................382
C’s approach to the heap............... 383
operator new.............................. 384
operator delete ........................... 385
A simple example........................ 385
Memory manager overhead........... 386

Early examples redesigned.........387
Stash for pointers........................ 387
The stack .................................... 391

new & delete for arrays..............393
Making a pointer more like an array394

Why “upcasting”?........................ 429
Upcasting and the copy-constructor
(not indexed) ............................... 429
Composition vs. inheritance (revisited)432
Pointer & reference upcasting........ 433
A crisis ....................................... 434

Summary ....................................... 434
Exercises....................................... 434

15: Polymorphism & virtual
functions
437
Evolution of C++ programmers..... 438

Upcasting...................................... 438
The problem................................. 440
Function call binding.................... 440

virtual functions ......................... 440
Extensibility................................ 441

How C++ implements late binding444
Storing type information............... 445
Picturing virtual functions............. 446
Under the hood............................ 448
Installing the vpointer................... 449
Objects are different..................... 449

Why virtual functions?..............450
Abstract base classes and pure
virtual functions..........................451
Pure virtual definitions................ 456

Inheritance and the VTABLE....457
virtual functions & constructors461
Order of constructor calls.............. 462
Behavior of virtual functions inside
constructors................................. 463

Destructors and virtual destructors464

Replacing string characters............ 507
Concatenation using non-member
overloaded operators.................... 511

Searching in strings..................... 512
Finding in reverse ........................ 517
Finding first/last of a set ................ 518
Removing characters from strings .. 519
Comparing strings........................ 523
Using iterators............................. 527
Strings and character traits............ 529

A string application..................... 532
Summary ....................................... 535
Exercises....................................... 536

18: Iostreams

537

Virtuals in destructors.................. 465

Why iostreams?........................... 537

Summary........................................466
Exercises .......................................466

Iostreams to the rescue............... 541

16: Introduction to templates
469
Containers & iterators .................469
The need for containers................ 471

Overview of templates ................472
The C approach ........................... 472
The Smalltalk approach ................ 472
The template approach ................. 474

Template syntax............................475
Non-inline function definitions...... 477
The stack as a template................. 478
Constants in templates.................. 480

Stash and stack as templates....482
The ownership problem ................ 482
Stash as a template ...................... 482
stack as a template....................... 488

Polymorphism & containers ......491
Summary........................................495
Exercises .......................................495

Part 2: The Standard C++
Library
497
Library overview..........................498

17: Strings

501

What’s in a string.........................501
Creating and initializing C++ strings503

Operating on strings....................505
Appending, inserting and concatenating
strings......................................... 506

True wrapping............................. 539
Sneak preview of operator overloading542
Inserters and extractors................. 543
Common usage ............................ 544
Line-oriented input....................... 546

File iostreams ............................... 548
Open modes................................. 550

Iostream buffering....................... 550
Using get( ) with a streambuf ........ 552

Seeking in iostreams ................... 552
Creating read/write files................ 554

stringstreams ................................ 555
strstreams ...................................... 555
User-allocated storage .................. 555
Automatic storage allocation ......... 558

Output stream formatting........... 561
Internal formatting data................. 562
An exhaustive example................. 566

Formatting manipulators ............ 569
Manipulators with arguments........ 571

Creating manipulators ................ 574
Effectors..................................... 575

Iostream examples....................... 577
Code generation ........................... 577
A simple datalogger ..................... 585
Counting editor ............................ 592
Breaking up big files .................... 593

Summary ....................................... 595
Exercises....................................... 595

19: Templates in depth

597

Nontype template arguments..... 597
Default template arguments....... 598
The typename keyword .............. 598
Typedefing a typename................. 600

Using typename instead of class ... 600

Function templates.......................600

Cost of overflowing allocated storage658
Checked random-access................ 660

A memory allocation system ......... 601

list................................................... 661

Type induction in function
templates........................................605
Taking the address of a generated
function template..........................606
Applying a function to an STL
sequence........................................607
Template-templates......................610
Member function templates .......611

Special list operations................... 663
Swapping all basic sequences ........ 667
Robustness of lists........................ 668

Why virtual member template
functions are disallowed............... 613
Nested template classes ................ 613

Template specializations.............613
Full specialization........................ 613
Partial Specialization.................... 613
A practical example ..................... 613
Design & efficiency..................... 617
Preventing template bloat ............. 617

Explicit instantiation ...................618
Explicit specification of template
functions..................................... 619

Controlling template instantiation619
The inclusion vs. separation models621
The export keyword..................... 621

Template programming idioms ..621
The “curiously-recurring template” 621
Traits.......................................... 621

Summary........................................621

20: STL Containers & Iterators
623
Containers and iterators ..............623
STL reference documentation........ 625

The Standard Template Library .625
The basic concepts .......................627
Containers of strings ...................631
Inheriting from STL containers .633
A plethora of iterators .................635
Iterators in reversible containers.... 637
Iterator categories ........................ 638
Predefined iterators...................... 639

Basic sequences: vector, list &
deque..............................................645
Basic sequence operations............. 645

vector .............................................648
Cost of overflowing allocated storage649
Inserting and erasing elements....... 653

deque..............................................655
Converting between sequences...... 657

Performance comparison ........... 669
set................................................... 674
Eliminating strtok( ) .................... 675
StreamTokenizer: a more flexible
solution ....................................... 677
A completely reusable tokenizer .... 679

stack............................................... 684
queue ............................................. 687
Priority queues............................. 692
Holding bits .................................. 702
bitset<n>.................................... 702
vector<bool>.............................. 706

Associative containers................ 708
Generators and fillers for associative
containers.................................... 712
The magic of maps....................... 715
Multimaps and duplicate keys........ 720
Multisets..................................... 723

Combining STL containers........ 726
Cleaning up containers of pointers729
Creating your own containers ... 731
Freely-available STL extensions733
Summary ....................................... 735
Exercises....................................... 736

21: STL Algorithms

739

Function objects .......................... 739
Classification of function objects... 741
Automatic creation of function objects741
SGI extensions............................. 755

A catalog of STL algorithms ..... 761
Support tools for example creation . 763
Filling & generating..................... 767
Counting..................................... 769
Manipulating sequences................ 770
Searching & replacing.................. 775
Comparing ranges ........................ 781
Removing elements...................... 784
Sorting and operations on sorted ranges787
Heap operations........................... 798
Applying an operation to each element
in a range .................................... 799
Numeric algorithms...................... 807
General utilities............................ 810

Creating your own STL-style
algorithms ..................................... 812
Summary ....................................... 813

Exercises .......................................813

Part 3: Advanced Topics
22: Multiple inheritance

817
818

Perspective....................................818
Duplicate subobjects ...................820
Ambiguous upcasting .................821
virtual base classes .....................822
The "most derived" class and virtual
base initialization......................... 824
"Tying off" virtual bases with a default
constructor.................................. 825

Overhead .......................................827
Upcasting ......................................828
Persistence.................................. 831

Avoiding MI..................................838
Repairing an interface .................838
Summary........................................843
Exercises .......................................843

23: Exception handling

845

Error handling in C......................845
Throwing an exception................848
Catching an exception.................849
The try block .............................. 849
Exception handlers....................... 849
The exception specification........... 850
Better exception specifications?..... 853
Catching any exception ................ 853
Rethrowing an exception .............. 854
Uncaught exceptions.................... 854
Function-level try blocks.............. 856

Cleaning up...................................856
Constructors ..................................860

What is RTTI? .............................. 876
Two syntaxes for RTTI................. 876

Syntax specifics ........................... 880
typeid( ) with built-in types........... 880
Producing the proper type name..... 881
Nonpolymorphic types.................. 881
Casting to intermediate levels........ 882
void pointers................................ 884
Using RTTI with templates ........... 884

References .................................... 885
Exceptions................................... 886

Multiple inheritance.................... 887
Sensible uses for RTTI............... 888
Revisiting the trash recycler .......... 889

Mechanism & overhead of RTTI892
Creating your own RTTI ............ 892
Explicit cast syntax..................... 896
static_cast................................... 897
const_cast................................... 899
reinterpret_cast .......................... 900

Summary ....................................... 902
Exercises....................................... 903

XX: Maintaining system
integrity

905

The canonical object form.......... 905
An extended canonical form .......... 905

Dynamic aggregation.................. 905
Reference counting..................... 909
Reference-counted class
hierarchies..................................... 909
Exercises....................................... 909

25: Design patterns

911

The pattern concept .................... 911

Making everything an object ......... 862

The singleton ............................... 912

Exception matching.....................864
Standard exceptions.....................866
Programming with exceptions...867

Classifying patterns .................... 916
Features, idioms, patterns.............. 917
Basic complexity hiding................ 917

When to avoid exceptions............. 867
Typical uses of exceptions............ 868

Factories: encapsulating object
creation.......................................... 917

Overhead .......................................872
Summary........................................873
Exercises .......................................873

Polymorphic factories................... 920
Abstract factories ......................... 923
Virtual constructors...................... 925

24: Run-time type
identification

875

The “Shape” example ..................875

Callbacks....................................... 931
Functor/Command........................ 931
Strategy ...................................... 931
Observer ..................................... 931

Multiple dispatching................... 941
Visitor, a type of multiple dispatching944

Efficiency ......................................948
Flyweight.................................... 948

A: Coding style

The composite ..............................948
Evolving a design: the trash
recycler...........................................948
Improving the design ..................953

File names...................................1057
Begin and end comment tags..1057
Parens, braces and indentation1058
Order of header inclusion ........1061
Include guards on header files 1061
Use of namespaces....................1062
Use of require( ) and assure( )1062

“Make more objects”.................... 953
A pattern for prototyping creation.. 958

Abstracting usage ........................969
Applying double dispatching.....974
Implementing the double dispatch . 974

Applying the visitor pattern .......979
RTTI considered harmful?..........985
Summary........................................988
Exercises .......................................989

26: Tools & topics

991

The code extractor........................991
Debugging.................................. 1013

B: Programming guidelines
1063
C: Recommended reading
Error! Bookmark not
defined.
C ...Error! Bookmark not defined.
General C++Error! Bookmark not defined.

assert( ).....................................1013
Trace macros..............................1013
Trace file ...................................1014
Abstract base class for debugging.1015
Tracking new/delete & malloc/free1015

My own list of booksError! Bookmark not defined.

Depth & dark cornersError! Bookmark not defined.
Analysis & DesignError! Bookmark not defined.
The STLError! Bookmark not defined.
Design PatternsError! Bookmark not defined.

CGI programming in C++....... 1021
Encoding data for CGI.................1022
The CGI parser ...........................1023
Using POST ...............................1030
Handling mailing lists.................1031
A general information-extraction CGI
program .....................................1042
Parsing the data files ...................1048

Summary..................................... 1055
Exercises .................................... 1055

1057

D:Compiler specificsError!
Bookmark not defined.
Index

1073


Related documents


objectorientedprogrammingunit6
objectorientedprogrammingunit7
objectorientedprogrammingunit1
objectorientedprogrammingunit2
devry comp 220 ilab 4 composition lab report and source code
datastructureunit1


Related keywords