- Page 1: Thinking in C++ 2 nd edition Volume
- Page 5 and 6: TICA7, August 14, 1998. Strings cha
- Page 7 and 8: http://www.microsoft.com/typography
- Page 9 and 10: In Bruce Eckel President, MindView
- Page 11 and 12: MindView Ad Space
- Page 13 and 14: Dedication To the scholar, the heal
- Page 15 and 16: 2: Making & Using Objects 87 The pr
- Page 17 and 18: Type-safe linkage............. 323
- Page 19 and 20: protected ............. 618 protect
- Page 21 and 22: Preface Like any human language, C+
- Page 23 and 24: So the short answer is: what isn’
- Page 25 and 26: end up losing some portion of the a
- Page 27 and 28: Chapters C++ is a language in which
- Page 29 and 30: Chapter 5: Hiding the Implementatio
- Page 31 and 32: existing type. In this chapter you
- Page 33 and 34: (and official mirror sites) where i
- Page 35 and 36: note that the CD ROM is browser-bas
- Page 37: Constantine, Lucy Lockwood, Tom Kef
- Page 40 and 41: But computers are not so much machi
- Page 42 and 43: the solution will run. There’s st
- Page 44 and 45: So, although what we really do in o
- Page 46 and 47: middle portion is not shown. If you
- Page 48 and 49: necessary to achieve the functional
- Page 50 and 51: more specific types of trash are de
- Page 52 and 53:
Shape +draw() +erase() +move() +get
- Page 54 and 55:
Thermostat Controls Cooling System
- Page 56 and 57:
BirdController What happens when fl
- Page 58 and 59:
doStuff(c); What’s happening here
- Page 60 and 61:
The second approach is to create ob
- Page 62 and 63:
Analysis and design The object-orie
- Page 64 and 65:
It’s often proposed that you “b
- Page 66 and 67:
Phase 1: What are we making In the
- Page 68 and 69:
eveal itself in the fullness of tim
- Page 70 and 71:
getting into too much detail too ea
- Page 72 and 73:
2. Object assembly. As you’re bui
- Page 74 and 75:
Phase 4: Iteration This is the poin
- Page 76 and 77:
will still function. You need not f
- Page 78 and 79:
You’re already on the learning cu
- Page 80 and 81:
large, complex program, there’s n
- Page 82 and 83:
first time, so it should not be mis
- Page 84 and 85:
Performance issues A common questio
- Page 86 and 87:
alternatives. Even if you eventuall
- Page 88 and 89:
By reading this chapter first, you
- Page 90 and 91:
takes several steps. The transition
- Page 92 and 93:
variable in another object module,
- Page 94 and 95:
point of definition the compiler al
- Page 96 and 97:
In a function declaration, you give
- Page 98 and 99:
cause the preprocessor to search fo
- Page 100 and 101:
until link time, one possibility is
- Page 102 and 103:
This book will use Standard C++ (an
- Page 104 and 105:
included the header file but all th
- Page 106 and 107:
"Hello, world!" And now, finally, t
- Page 108 and 109:
int main() { // Specifying formats
- Page 110 and 111:
Simple file manipulation Standard I
- Page 112 and 113:
This upward compatibility from C to
- Page 114 and 115:
iostream object. It’s that simple
- Page 116 and 117:
it’s much easier if you have each
- Page 118 and 119:
so if you have an array a and you w
- Page 120 and 121:
while(in >> word) is what gets the
- Page 122 and 123:
Exercises Solutions to selected exe
- Page 124 and 125:
If you’ve never seen C before, th
- Page 126 and 127:
} x = y = z; // ... It turns out th
- Page 128 and 129:
In cfunc( ), the first if that eval
- Page 130 and 131:
to a nonzero value). Other conditio
- Page 132 and 133:
while(guess != secret) { // Compoun
- Page 134 and 135:
curly brace ‘{’. This is in con
- Page 136 and 137:
switch(selector) { case integral-va
- Page 138 and 139:
using namespace std; void removeHat
- Page 140 and 141:
: C03:AutoIncrement.cpp // Shows us
- Page 142 and 143:
The first part of the program defin
- Page 144 and 145:
: C03:Specify.cpp // Demonstrates t
- Page 146 and 147:
All the variables, and even the fun
- Page 148 and 149:
from dog, bird is four bytes away f
- Page 150 and 151:
: C03:PassByValue.cpp #include usi
- Page 152 and 153:
pointers later, but this is arguabl
- Page 154 and 155:
All possible combinations of basic
- Page 156 and 157:
variable was defined. That is, a sc
- Page 158 and 159:
int main() { //.. { // Begin a new
- Page 160 and 161:
using namespace std; int globe; voi
- Page 162 and 163:
want a value to be extant throughou
- Page 164 and 165:
} int i; // The data definition voi
- Page 166 and 167:
The const was taken from C++ and in
- Page 168 and 169:
Operators and their use This sectio
- Page 170 and 171:
Introduction to preprocessor macros
- Page 172 and 173:
Bitwise not produces the opposite o
- Page 174 and 175:
An interesting bit pattern: unsigne
- Page 176 and 177:
x = a * -b; but the reader might ge
- Page 178 and 179:
Common pitfalls when using operator
- Page 180 and 181:
checking to catch errors. Once you
- Page 182 and 183:
(4) Implicit type conversions, norm
- Page 184 and 185:
Can't use xp as an X* at this point
- Page 186 and 187:
Keyword Meaning xor_eq ^= (bitwise
- Page 188 and 189:
The struct declaration must end wit
- Page 190 and 191:
int main() { Structure3 s1, s2; Str
- Page 192 and 193:
You can see how much more readable
- Page 194 and 195:
Once you perform an assignment, the
- Page 196 and 197:
for(int i = 0; i < 10; i++) cout
- Page 198 and 199:
Even though func1( ) and func2( ) d
- Page 200 and 201:
#include using namespace std; int
- Page 202 and 203:
++, which “adds one to the pointe
- Page 204 and 205:
int* ip = a; P(*ip); P(*++ip); P(*(
- Page 206 and 207:
in all upper case. A common flag na
- Page 208 and 209:
punctuation are concatenated into a
- Page 210 and 211:
Defining a function pointer To defi
- Page 212 and 213:
Using a function pointer Once you d
- Page 214 and 215:
Make: an essential tool for separat
- Page 216 and 217:
multiple rules. Many make programs
- Page 218 and 219:
target1.exe: target2.exe: If you ju
- Page 220 and 221:
Declare: Declare.o $(CPP) $(OFLAG)D
- Page 222 and 223:
lectures, exercises, and guided sol
- Page 224 and 225:
values in your instance and print t
- Page 226 and 227:
flag. You will need to consult your
- Page 228 and 229:
to switch from some language that y
- Page 230 and 231:
:~ A tag name like CStashTag is gen
- Page 232 and 233:
delete []s->storage; } } ///:~ init
- Page 234 and 235:
new unsigned char[newBytes]; The ge
- Page 236 and 237:
: C04:CLibTest.cpp //{L} CLib // Te
- Page 238 and 239:
Each separate C file is a translati
- Page 240 and 241:
of all their function names. So ini
- Page 242 and 243:
C library converted to C++ // Decla
- Page 244 and 245:
You can see that all the member fun
- Page 246 and 247:
: C04:CppLibTest.cpp //{L} CppLib /
- Page 248 and 249:
What's an object Now that you’ve
- Page 250 and 251:
Object details A question that come
- Page 252 and 253:
most of the time, except when struc
- Page 254 and 255:
included throughout the system, the
- Page 256 and 257:
This will yield a true result, and
- Page 258 and 259:
end up “turning off” namespaces
- Page 260 and 261:
} void Stack::initialize() { head =
- Page 262 and 263:
Read file and store lines in the St
- Page 264 and 265:
etween what the user of the structu
- Page 266 and 267:
16. Modify Stash to use a vector as
- Page 269 and 270:
5: Hiding the Implementation A typi
- Page 271 and 272:
The second reason for access contro
- Page 273 and 274:
Although func( ) can access any mem
- Page 275 and 276:
void Z::initialize() { j = 99; } vo
- Page 277 and 278:
private: Holder* h; int* p; public:
- Page 279 and 280:
second argument) for n bytes past t
- Page 281 and 282:
Any object belonging to this class
- Page 283 and 284:
The examples in this book, however,
- Page 285 and 286:
void initialize(); void push(void*
- Page 287 and 288:
Here’s a simple example demonstra
- Page 289 and 290:
u.cleanup(); } ///:~ The only thing
- Page 291:
9. Copy the implementation and test
- Page 294 and 295:
This not only provides a single uni
- Page 296 and 297:
Now, when an object is defined, voi
- Page 298 and 299:
The destructor is called automatica
- Page 300 and 301:
eginning of a scope. If a construct
- Page 302 and 303:
However, some confusion may result
- Page 304 and 305:
pointer “down” (a relative term
- Page 306 and 307:
} storage = b; // Point to new memo
- Page 308 and 309:
Stack with constructors & destructo
- Page 310 and 311:
ut is not responsible for cleaning
- Page 312 and 313:
Now if you decide to add another el
- Page 314 and 315:
zz[i].print(); } ///:~ Notice that
- Page 316 and 317:
Safety during coding is a big issue
- Page 319 and 320:
7: Function Overloading & Default A
- Page 321 and 322:
Although function overloading is a
- Page 323 and 324:
int f(); This works fine when the c
- Page 325 and 326:
~Stash(); int add(void* element); v
- Page 327 and 328:
Both constructors are exercised in
- Page 329 and 330:
Although the member functions civil
- Page 331 and 332:
(outside all functions and classes)
- Page 333 and 334:
Placeholder arguments Arguments in
- Page 335 and 336:
Mem::Mem(int sz) { mem = 0; size =
- Page 337 and 338:
int main() { MyString s("My test st
- Page 339 and 340:
Notice that a call to ensureMinSize
- Page 341:
7. Create a new version of the Stac
- Page 344 and 345:
This provides safety and control in
- Page 346 and 347:
const). Storage must be allocated b
- Page 348 and 349:
situations, const means “a piece
- Page 350 and 351:
has the option of doing constant fo
- Page 352 and 353:
const int* const x = &d; // (1) int
- Page 354 and 355:
Function arguments & return values
- Page 356 and 357:
Returning by value as a const becom
- Page 358 and 359:
temporary X. However, f7( ) takes i
- Page 360 and 361:
that attempting to modify the desti
- Page 362 and 363:
Error: const temporary created by f
- Page 364 and 365:
void print(); }; Fred::Fred(int sz)
- Page 366 and 367:
until Chapter 10: static. The stati
- Page 368 and 369:
The “enum hack” in old code In
- Page 370 and 371:
non-const member function. Thus, an
- Page 372 and 373:
cq.lastQuote(); // OK //! cq.quote(
- Page 374 and 375:
} int main() { const Z zz; zz.f();
- Page 376 and 377:
char Comm::read(int index) const {
- Page 378 and 379:
9. Write a const pointer to a doubl
- Page 380 and 381:
assign via a void* (without a cast)
- Page 382 and 383:
In C, one of the ways to preserve e
- Page 384 and 385:
granted. In the un-parenthesized ve
- Page 386 and 387:
mixed together, so a problem like t
- Page 388 and 389:
space than the code generated to do
- Page 390 and 391:
Here, the class user never has dire
- Page 392 and 393:
void setWidth(int w) { width = w; }
- Page 394 and 395:
updateLocal(); return local.tm_sec;
- Page 396 and 397:
if(storage != 0) delete []storage;
- Page 398 and 399:
The Stack class makes even better u
- Page 400 and 401:
Inlines & the compiler To understan
- Page 402 and 403:
class Forward { int i; public: Forw
- Page 404 and 405:
interface and thereby making the cl
- Page 406 and 407:
Because there are actually two stat
- Page 408 and 409:
} } exit(1); inline void assure(std
- Page 410 and 411:
C++ is complicated enough without a
- Page 412 and 413:
second function, without the need f
- Page 415 and 416:
10: Name Control Creating names is
- Page 417 and 418:
function. C and C++ allow you to cr
- Page 419 and 420:
int i; public: X(int ii = 0) : i(ii
- Page 421 and 422:
static Obj b inside f( ) and the st
- Page 423 and 424:
all you’ve done is change the vis
- Page 425 and 426:
Creating a namespace The creation o
- Page 427 and 428:
names in an unnamed namespace, you
- Page 429 and 430:
Integer a, b, c; Integer divide(Int
- Page 431 and 432:
} #endif // USINGDECLARATION_H ///:
- Page 433 and 434:
is not very safe. Global data can b
- Page 435 and 436:
ws.print(); } ///:~ Here, the quali
- Page 437 and 438:
static const X x3; static const X x
- Page 439 and 440:
A static member function cannot acc
- Page 441 and 442:
int main() { //! Egg x(1); // Error
- Page 443 and 444:
zeroing of the storage occupied by
- Page 445 and 446:
definition for the Initializer init
- Page 447 and 448:
constructor, so you can tell if the
- Page 449 and 450:
} static Dependency1 dep1; return d
- Page 451 and 452:
across the various translation unit
- Page 453 and 454:
that when you give the argument wit
- Page 455 and 456:
your namespace into that function s
- Page 457:
a Mirror object, which it assigns t
- Page 460 and 461:
Although references also exist in P
- Page 462 and 463:
2. Once a reference is initialized
- Page 464 and 465:
} ///:~ The call to f(1) produces a
- Page 466 and 467:
how does the compiler know how to p
- Page 468 and 469:
farther to provide storage for the
- Page 470 and 471:
output for bigfun( ), you can see i
- Page 472 and 473:
When the local object goes out of s
- Page 474 and 475:
} }; int HowMany2::objectCount = 0;
- Page 476 and 477:
cout.width(width); cout
- Page 478 and 479:
Temporary objects Line 15 begins th
- Page 480 and 481:
cout
- Page 482 and 483:
Here’s an example: //: C11:NoCopy
- Page 484 and 485:
combined with the object dereferenc
- Page 486 and 487:
fp = &Simple2::f; } ///:~ In the de
- Page 488 and 489:
underlying implementation without a
- Page 490 and 491:
the member functions const and prov
- Page 492 and 493:
21. Create a simple class without a
- Page 494 and 495:
The difference is that the argument
- Page 496 and 497:
} }; i += rv.i; return *this; int m
- Page 498 and 499:
operator++(Integer& a); // Postfix:
- Page 500 and 501:
} Byte operator!() const { cout
- Page 502 and 503:
an example of all the operators you
- Page 504 and 505:
friend int operator=(const Integer&
- Page 506 and 507:
if(&left == &right) {/* self-assign
- Page 508 and 509:
} #define TRYC(OP) \ out
- Page 510 and 511:
%= right.b; return *this; } Byte& o
- Page 512 and 513:
} Byte b3 = 92; b1 = b2 = b3; int m
- Page 514 and 515:
ack the object that was changed. Th
- Page 516 and 517:
left-hand side of an equal sign. Th
- Page 518 and 519:
class ObjContainer { vector a; publ
- Page 520 and 521:
#include #include "../require.h" u
- Page 522 and 523:
pointer,” although the example sh
- Page 524 and 525:
around and calls operator( ) for th
- Page 526 and 527:
eturn i[x]; } friend ostream& opera
- Page 528 and 529:
Operator &= |= %= >>=
- Page 530 and 531:
When you create an operator=, you m
- Page 532 and 533:
} ~Dog() { cout
- Page 534 and 535:
it. However, if your object require
- Page 536 and 537:
: p(dog), houseName(house) { cout
- Page 538 and 539:
Before you make any modifications (
- Page 540 and 541:
Automatic operator= creation Becaus
- Page 542 and 543:
In this case, automatic type conver
- Page 544 and 545:
Reflexivity One of the most conveni
- Page 546 and 547:
using namespace std; class Stringc
- Page 548 and 549:
: C12:TypeConversionFanout.cpp clas
- Page 550 and 551:
(the creator of the class) or the u
- Page 552 and 553:
16. Add an int data member to both
- Page 555 and 556:
13: Dynamic Object Creation Sometim
- Page 557 and 558:
Object creation When a C++ object i
- Page 559 and 560:
... sometime later: obj->destroy();
- Page 561 and 562:
with a call to free( )). Just as a
- Page 563 and 564:
Before a pointer to that block is r
- Page 565 and 566:
If you have a memory leak in your p
- Page 567 and 568:
The other change is the replacement
- Page 569 and 570:
can prevent a memory leak (more ele
- Page 571 and 572:
However, for the string pointers, i
- Page 573 and 574:
Now the array elements in q can be
- Page 575 and 576:
Another issue is heap fragmentation
- Page 577 and 578:
} free(m); class S { int i[100]; pu
- Page 579 and 580:
} for(int i = 0; i < psize; i++) if
- Page 581 and 582:
empty bracket syntax to indicate ar
- Page 583 and 584:
In both cases you’re handed the s
- Page 585 and 586:
When the program runs, it does not
- Page 587 and 588:
Notice that operator new only retur
- Page 589 and 590:
5. Repeat the above exercise, but a
- Page 591 and 592:
14: Inheritance & Composition One o
- Page 593 and 594:
int i; public: X() { i = 0; } void
- Page 595 and 596:
public: Y() { i = 0; } int change()
- Page 597 and 598:
The solution is simple: Call the co
- Page 599 and 600:
This makes built-in types act a lit
- Page 601 and 602:
#define CLASS(ID) class ID { \ publ
- Page 603 and 604:
properly reverse the order of the c
- Page 605 and 606:
in the new class. In the next chapt
- Page 607 and 608:
Name hiding comes into play here be
- Page 609 and 610:
~GameBoard() { cout
- Page 611 and 612:
ecause that function was not explic
- Page 613 and 614:
implementation hiding themselves, s
- Page 615 and 616:
} operator ifstream&() { return fil
- Page 617 and 618:
inherit privately, you’re “impl
- Page 619 and 620:
int read() const { return i; } void
- Page 621 and 622:
organic, evolutionary creature, rat
- Page 623 and 624:
your diagrams any way you find help
- Page 625 and 626:
Child object to a Parent& (if you c
- Page 627 and 628:
#include #include using namespace
- Page 629 and 630:
types inside the new type. Typicall
- Page 631 and 632:
class BusinessTraveler from Travele
- Page 633 and 634:
15: Polymorphism & Virtual Function
- Page 635 and 636:
quickly see the usefulness of this
- Page 637 and 638:
“narrow” that interface, but ne
- Page 639 and 640:
virtual void play(note) const { cou
- Page 641 and 642:
class Brass : public Wind { public:
- Page 643 and 644:
The keyword virtual tells the compi
- Page 645 and 646:
pointer (the VPTR) into the structu
- Page 647 and 648:
instrument pointer brass object VPT
- Page 649 and 650:
call word ptr [bx+4] Finally, the s
- Page 651 and 652:
from the previous assembly-language
- Page 653 and 654:
instrument virtual void play() virt
- Page 655 and 656:
cout
- Page 657 and 658:
may be a common piece of code that
- Page 659 and 660:
virtual string sit() const { return
- Page 661 and 662:
the examples you’ve seen here, an
- Page 663 and 664:
exists) and Dog, which no longer ex
- Page 665 and 666:
x = d2.f(); //! d2.f(s); // string
- Page 667 and 668:
int main() { Bird b; Cat c; Pet* p[
- Page 669 and 670:
Order of constructor calls The seco
- Page 671 and 672:
that is called last. This is anothe
- Page 673 and 674:
int main() { Base1* bp = new Derive
- Page 675 and 676:
The only distinction occurs when yo
- Page 677 and 678:
ely on portions of an object that h
- Page 679 and 680:
} Object* peek() const { return hea
- Page 681 and 682:
Creating containers that hold Objec
- Page 683 and 684:
using namespace std; class Shape {
- Page 685 and 686:
picture” of class relationships.
- Page 687 and 688:
12. Create a model of a greenhouse
- Page 689 and 690:
has no default constructor, so why
- Page 691 and 692:
16: Introduction to Templates Inher
- Page 693 and 694:
} int pop() { return stack[top > 0
- Page 695 and 696:
need an object, create it with new,
- Page 697 and 698:
object-based hierarchy with its con
- Page 699 and 700:
code. The container no longer holds
- Page 701 and 702:
In main( ), you can see how easy it
- Page 703 and 704:
people see software as a service, a
- Page 705 and 706:
} }; class Number { float f; public
- Page 707 and 708:
}* head; public: Stack() : head(0)
- Page 709 and 710:
changeable throughout the lifetime
- Page 711 and 712:
#ifndef AUTOCOUNTER_H #define AUTOC
- Page 713 and 714:
The destructor for CleanupCheck doe
- Page 715 and 716:
in the program, and you don’t nec
- Page 717 and 718:
int main() { Stack ac; // Ownership
- Page 720 and 721:
array, copying the old array to the
- Page 722 and 723:
of the underlying container) for an
- Page 724 and 725:
} friend ostream& operator
- Page 726 and 727:
} // Jump an iterator forward itera
- Page 728 and 729:
void push(T* dat) { head = new Link
- Page 730 and 731:
dereference operator performs the e
- Page 732 and 733:
To create the end sentinel: iterato
- Page 734 and 735:
} inflate(); storage[next++] = elem
- Page 736 and 737:
int main() { { // To force destruct
- Page 738 and 739:
class Square : public Shape { publi
- Page 740 and 741:
drawAll(p); cout
- Page 742 and 743:
that, to acquire a library from a t
- Page 744 and 745:
16. (Advanced) Modify PointerToMemb
- Page 746 and 747:
Although many of these issues have
- Page 748 and 749:
Begin and end comment tags A very i
- Page 750 and 751:
void func(int a) { you immediately
- Page 752 and 753:
The issue of where to put the openi
- Page 754 and 755:
Use of require( ) and assure( ) The
- Page 756 and 757:
also from the insights of friends i
- Page 758 and 759:
elationship where it doesn’t exis
- Page 760 and 761:
22. Don’t use private inheritance
- Page 762 and 763:
than global variables, although you
- Page 764 and 765:
the heap, the catcher must know to
- Page 766 and 767:
has enough information to deal with
- Page 768 and 769:
768 Thinking in C++ www.BruceEckel.
- Page 770 and 771:
C Thinking in C: Foundations for Ja
- Page 772 and 773:
Analysis & Design Extreme Programmi
- Page 774 and 775:
mathematical determinism and the il
- Page 776 and 777:
# compiler under dos: { all } # Obj
- Page 778 and 779:
C07:MemTest.cpp C09:Cpptime.cpp C12
- Page 780 and 781:
Index -, 177 --, 178 !, 177 !=, 172
- Page 782 and 783:
linking compiled C code with C++, 4
- Page 784 and 785:
declaration, 93, 245, 256 analyzing
- Page 786 and 787:
static member, 378, 440, 477 using
- Page 788 and 789:
Love, Tom, 777 lvalue, 170, 358 mac
- Page 790 and 791:
organization code, 260 code in head
- Page 792 and 793:
short, 145 side effect, 170, 178 si
- Page 794 and 795:
assembly-language code generated by
- Page 796 and 797:
MindView Ad Space 796