Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Download
Standard view
Full view
of .
Save to My Library
Look up keyword
Like this
20Activity
0 of .
Results for:
No results containing your search query
P. 1
C++ Interactive Course

C++ Interactive Course

Ratings: (0)|Views: 2,508|Likes:
Published by ursvasu2k
C++ book
C++ book

More info:

Published by: ursvasu2k on Oct 24, 2009
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

11/16/2012

pdf

text

original

 
INTRODUCTIONABOUT THE AUTHORCHAPTER 1—A FIRST LOOL AT OOP AND C++
Session 1: Why Do We Need OOP?Procedural LanguagesDivision into FunctionsProblems with Structured ProgrammingData Is UndervaluedRelationship to the Real WorldNew Data TypesThe Object-Oriented ApproachThe Corporate AnalogyThe Dinner Table AnalogyOOP: An Approach to Organization, NotDetailsQuiz 1Session 2: Features of Object-Oriented LanguagesReal-World ObjectsStates and AbilitiesClassesInheritanceReusabilityCreating New Data TypesPolymorphism and OverloadingC++ and COOP in a NutshellQuizSession 3: Hot Dog Stands as ObjectsInteraction with the Hot Dog Stand ProgramInputting the DataRecording a SaleDisplaying the DataDesigning the Hot Dog Stand ProgramWhat Are the Objects?What’s in a Hot Dog Stand Object?Specifying the Class of Hot Dog Stand ObjectsSyntax of the Class SpecificationVariable DeclarationsFunctionsPublic and PrivateQuiz 3Session 4: Basic C++ Data TypesCharactersAssignment OperatorEscape SequencesIntegersUnsigned IntegersFloating PointWhitespaceCommentsQuiz 4Exercise 1Exercise 2Midchapter DiscussionSession 5: Introduction to Input/OutputOutput to the ScreenString ConstantsFormatting OutputNew Lines Not AutomaticEscape SequencesThe endl ManipulatorInput from the KeyboardStream I/OOld-Style C I/OQuiz 5Exercise 1Exercise 2Exercise 3Session 6: Member FunctionsInitializing the DataRecording a SaleDisplaying DataArithmetic OperatorsIncrement and Decrement OperatorsQuiz 6Exercise 1Exercise 2Session 7: Specifying a ClassQuiz 7Exercise 1Exercise 2Session 8: Creating and Interacting with ObjectsCreating Objects from a Class SpecificationSending Messages to ObjectsQuiz 8Exercise 1Exercise 2Summary: Chapter 1End-Of-Chapter Discussion
Session 1: The Complete Hot Dog Stand ProgramListing for the Hot Dog Stand ProgramThe IOSTREAM.H Header FilePreprocessor DirectivesOther Header FilesThe main() FunctionInteraction with the Hot Dog Stand ProgramProgram OrganizationQuiz 1Exercise 1Exercise 2Session 2: LoopsTrue and False ValuesRelational Operatorswhile Loopsdo Loopsfor LoopsNested LoopsLogical OperatorsPrecedenceQuiz 2Exercise 1Exercise 2Session 3: Simple DecisionsThe if StatementThe if…else StatementTest ExpressionNested if…else StatementsImproving the Hot Dog Program with if A Glimpse of ReusabilityQuiz 3Exercise 1Exercise 2Session 4: Advanced DecisionsThe else if ConstructionFine-Tuning LoopsThe break StatementThe continue StatementThe switch StatementImproving the Hot Dog Program with switchThe Conditional OperatorQuiz 4Exercise 1Exercise 2Midchapter DiscussionSession 5: A class to Represent Time ValuesNew Data TypesA Simple Version of the airtime ClassAssignment Statements with ObjectsWhat’s Really in an Object?More Manipulators: Formatting Leading ZerosQuiz 5Exercise 1Exercise 2Session 6: Function ArgumentsAdding Hours to an airtime ValueSending a Message with an ArgumentWriting the Member FunctionListing for houradd.cppThe set() Member Function with ArgumentsArguments of Any TypeOther Uses for FunctionsPassing by ValueQuiz 6Exercise 1Exercise 2Session 7: Arithmetic For User-defined TypesAdding airtime ValuesArithmetic Is Not for All ClassesAccess to Private DataConverting Minutes to airtimeNonautomatic ConversionsMultiplying an airtime ValueCalling Each OtherQuiz 7Exercise 1Exercise 2Session 8: Function Return ValuesConverting airtime to MinutesThe return StatementCreating Automatic VariablesThe StackNameless Automatic VariablesReturning a Value from add()Returning by ValueLibrary FunctionsQuiz 8Exercise 1Exercise 2Summary: Chapter 2End-Of-Chapter Discussion
Session 1: Array FundamentalsDefining an ArrayArray ElementsAccessing Array ElementsInitializing Array ElementsMultidimensional ArraysDanger: Index Out of RangeQuiz 1Session 2: Arrays as Instance DataThe employee ClassLibrary Function getche()The KeyPostfix Increment OperatorsThe Stack ClassPushing and PoppingAn Array Disguised as a StackNot a ConstructorQuiz 2Exercise 1Exercise 2Session 3: Arrays of ObjectsDefining an Array of ObjectsNew Syntax for AccessArray of airtime ObjectsArray of employee ObjectsQuiz 3Exercise 1Exercise 2Session 4: StringsString VariablesString ConstantsImproved String I/OUsing const VariablesEating Extra CharactersReal Strings for the employee ClassString I/OExternal VariablesQuiz 4Exercise 1Exercise 2Midchapter DiscussionSession 5: String Library FunctionsLibrary Functions for StringsFinding String LengthsCopying StringsAppending StringsComparing StringsA Homemade String ClassLibrary FunctionsClean FormatData ConversionsAppendingAssignmentOverflow ProtectionWrappingQuiz 5Exercise 1Exercise 2Session 6: Arrays of StringsSyntax of Arrays of StringsArrays of Empty StringsArrays of Initialized StringsThe weekday ClassThe stricmp() FunctionArithmetic Assignment OperatorsQuiz 6Exercise 1Exercuse 2Session 7: StructuresSpecifying a StructureDefining Structure VariablesAccessing Structure MembersInitializing Structure VariablesStructure UsageStructures versus ClassesQuiz 7Exercise 1Exercise 2Session 8: enum and boolEnumerated Data TypesSpecifying an Enumerated TypeCreating and Using Enumerated VariablesThey’re Really IntegersA Card Game ProgramThe bool KeywordQuiz 8Exercise 1Exercise 2Summary: Chapter 3End-of-Chapter Discussion
Session 1: Function Review and Function DeclarationReviewFunction CallsFunction DefinitionsArgumentsReturn ValuesFunction DeclarationsArgumentsFunctions Called from main()Functions Called from Member FunctionsLibrary FunctionsThe RuleQuiz 1Session 2: Standalone Member FunctionsInline FunctionsSpecifying an Inline FunctionWhen Should You Inline a Function?Member Functions Defined Within a ClassMember Functions Defined Outside a ClassThe Scope Resolution OperatorThe Compiler Has Its Own IdeasRevised weekdays ProgramMove ’em Out?MacrosQuiz 2Exercise 1Exercise 2Session 3: Overloaded FunctionsNeed for Function OverloadingHow Does It Know?A Member Function ExampleQuiz 3Exercise 1Exercise 2Session 4: Default ArgumentsA Power ExampleA Member Function ExampleThe cin.getline() FunctionLimitationsWhen to Do WhatQuiz 4Exercise 1Exercise 2Midchapter DiscussionSession 5: Storage ClassesDeclarations and DefinitionsTwo Kinds of DeclarationsLifetime and VisibilityAutomatic VariablesRegister VariablesBlocksExternal VariablesExternal Variables and Multiple FilesExternal Variables in the DoghouseLocal Static VariablesThe Storage Class TableObjectsVisiblity of Instance DataLifetime of Instance DataQuiz 5Session 6: Static MembersStatic Member DataCreating Static DataAccessing Static DataStatic FunctionsCount-the-Objects ExampleQuiz 6Exercise 1Exercise 2Session 7: Reference ArgumentsSwapping IntegersPassing by ValuePassing by ReferenceA Reference Is a Different NameSwapping ObjectsStandalone ReferencesBehind the ScenesAdvantages of Passing by ReferenceQuiz 7Exercise 1Exercise 2Session 8: Returning by ReferenceSetting an Object to a ValueCautionsWhat’s It For?Quiz 8Summary: Chapter 4End-of-Chapter Discussion
Session 1: Introducing ConstructorsInitializationCreationDestructorsConstructors and Destructors in ActionSame Name as the ClassNo Return ValueWhat They DoInitializing VariablesInitialization ListDefault ConstructorQuiz 1Exercise 1Exercise 2Session 2: Constructor ArgumentsA Two-Argument ConstructorThe Wrong WayThe Right Way“Calling” the ConstructorA No-Argument ConstructorQuiz 2Exercise 1Exercise 2Session 3: The One-Argument ConstructorConversionsConverting Strings to xStringsConverting Meters to English DistancesMeters to English ObjectsEscape CharactersNot Always AppropriateMore Conversions to ComeQuiz 3Exercise 1Exercise 2Session 4: Arrays as Instance DataArray Sized with ConstantArray Sized with External constInitializing Member VariablesInstance Data InitializationInitialization Is Not AssignmentArrays Sized at Compile TimeThe enum HackStatic Constant VariablesThe Improved STACK ProgramInitializing a Member ArrayQuiz 4Exercise 1Exercise 2Midchapter DiscussionSession 5: Copy ConstructorsCopying VariablesEquivalent SyntaxCopying ObjectsNot the Normal ConstructorThe Default Copy Constructorconst for Function ArgumentsPassing by ReferencePassing by ValueA Simple Example of a Copy ConstructorJust Another ConstructorArgument Must Be Passed by ReferenceArgument Should Be constQuiz 5Exercise 1Exercise 2Session 6: Copy Constructors at WorkNumbering the ObjectsAn Intelligent Copy ConstructorInitialization ListA Variation on strcpy()Other Reasons for Using Copy ConstructorsCopy Constructor Invoked in Pass by ValuePassing by Value Creates a CopyWhy the Copy Constructor Must Use aReference ArgumentCopy Constructor Invoked in Return by ValueQuiz 6Exercise 1Exercise 2Session 7: const ObjectsThe Wandering Noonconst FunctionsThe Fixed NoonQuiz 7Exercise 1Exercise 2Session 8: Visualizing Construction and DestructionTwo Kinds of TotalProgram FeaturesExternal VariablesVariables in main()Passing by ValueLocal VariablesQuiz 8Exercise 1Exercise 2Summary: Chapter 5End-of-Chapter Discussion
Session 1: Overloading Binary Arithmetic OperatorsWhy Overload Operators?You Could Do It with FunctionsNot for All ClassesYou Can’t Overload EverythingThe operatorX() FunctionAdding airtime ObjectsArgumentsReturn ValueAdding xString ObjectsOther Binary Arithmetic OperatorsQuiz 1Exercise 1Exercise 2Session 2: Overloading Other Binary OperatorsRelational OperatorsHow It WorksPassing the Argument by const ReferenceAssignment OperatorsAvoiding Temporary ObjectsQuiz 2Exercise 1Exercise 2Session 3: Overloading Unary OperatorsPrefix Version of Operator ++Postfix Version of Operator ++The Unary Minus OperatorQuiz 3Exercise 1Exercise 2Session 4: Conversion from Objects to Basic TypesType Casting: Conversion for Basic TypesConversion from English to floatConversion Function Invoked AutomaticallyCasting for ClarityA Static ConstantConversion from xString to StringThe static_cast ApproachQuiz 4Exercise 1Exercise 2Midchapter DiscussionSession 5: Conversions Between ClassesA Short ExampleThe FracFeet ClassThe FracFeet ProgramThe English() OperatorThe One-Argument ConstructorQuiz 5Exercise 1Exercise 2Session 6: Overloading the Assignment Operator (=)Syntax of the Overloaded Assignment OperatorA Simple Assignment Operator ExampleAn Assignment Operator That Allows ChainingFuture ImprovementQuiz 6Exercise 1Exercise 2Session 7: Overloading the [ ] OperatorAccess with access() FunctionOne Size Fits AllErrors Are ReportedAccess with Overloaded [ ] OperatorQuiz 7Exercise 1Exercise 2Fine-Tuning Overloaded OperatorsConstant ArgumentsConstant FunctionsConstant Overloaded OperatorsAdding Constant airtime ObjectsReturn ValuesReturns from Assignment OperatorsThe Amazing *this ObjectThe += Operator RevisitedThe Increment Operator RevisitedSummary of Fine-Tuning for Overloaded OperatorsQuiz 8Exercise 1Exercise 2Summary: Chapter 6End-of-Chapter Discussion
Session 1: Introduction to InheritanceReusabilityRewriting CodeFunction LibrariesClass LibrariesInheritance and Program DesignComposition: A “Has a” RelationshipInheritance: A “Kind of” RelationshipNot Exactly a Family TreeInheritance SyntaxInheriting AttributesAccessing Base Class DataCalling a Base Class FunctionFunction Overloading in Base and Derived ClassesQuiz 1Program Design: The employee ClassClass HierarchyThe EMPINH ProgramAbstract ClassesInteraction with EMPINHQuiz 2Exercise 1Exercise 2Session 3: Reusability: An Improved Stack ClassReusabilityThe STACKINH ProgramA Smarter ObjectThe Base Class ConstructorThe protected Access SpecifierFunctions That Aren’t InheritedQuiz 3Exercise 1Exercise 2Session 4: Constructors and InheritanceThe Great Chain of ConstructorsWhen Are Derived Class Constructors Necessary?No ArgumentsArgumentsThe Initializer ListAdding Functionality to the Derived ClassConstructorQuiz 4Exercise 1ExerciseMidchapter DiscussionSession 5: Access ControlAccess ReviewKeeping Data PrivateA Stack ExampleA Graphics ExampleA Hierarchy of ShapesThe ClassesPublic and Private InheritanceThe Compiler and Public InheritancePrivate InheritanceThe Compiler and Private InheritanceProtected InheritanceAccess SummaryQuiz 5Exercise 1Exercise 2Session 6: GrandparentsDeriving foreman from laborerConstructorsSummaryQuiz 6Exercise 1Exercise 2Session 7: CompositionA safearay Object in a Stack ClassShould a scientist “Have an” employee?SummaryQuiz 7Exercise 1Exercise 2Session 8: Multiple InheritanceTwo Base Classes: employee and studentRepeated Base ClassesIt’s Controversial
ference/archive/1571690638/ewtoc.html (1 of 2) [21-03-2000 18:47:00]
 
Session 1: Addresses and PointersAddresses (Pointer Constants)The Address of Operator &Pointer VariablesPointers to Basic TypesSyntax QuibblesPointers Must Have a ValuePointers to ObjectsAccessing the Variable Pointed ToPointer to voidQuiz 1Session 2: Pointers, Arrays, and FunctionsPointers and ArraysArray Elements and Pointer NotationPointer Constants and Pointer VariablesPointers and FunctionsPassing Simple VariablesPassing Arrays as ArgumentsQuiz 2Exercise 1Exercise 2Session 3: Pointers and StringsPointers to String ConstantsStrings as Function ArgumentsCopying a String Using PointersLibrary String FunctionsArrays of Pointers to StringsMembership Access Operator (->)Quiz 3Exercise 1Exercise 2Session 4: Memory Management with new and deleteThe new OperatorThe delete OperatorA String Class That Uses newConstructor in NEWSTRDestructor in NEWSTRGlitch in xString ClassCreating Objects with newAn Array of Pointers to ObjectsProgram OperationAccessing Member FunctionsQuiz 4Exercise 1Exercise 2Midchapter DiscussionSession 5: this and constThe this PointerAccessing Member Data with thisUsing this for Returning ValuesPointers and the const Modifierconst VariablesTwo Places for constFunction Arguments and constReturning const ValuesQuiz 5Session 6: A Memory-Efficient String ClassTo Copy or Not to Copy?A String Counter ClassThe strCount ClassThe xString ClassReturning *this by ReferenceQuiz 6Exercise 1Exercise 2Session 7: A Linked List ClassA Chain of PointersAdding an Item to the ListDisplaying the List ContentsSelf-Containing ClassesAugmenting the linklist ProgramContainersQuiz 7Exercise 1Exercise 2Session 8: A Sorted Array ClassInserting Objects in Sorted OrderThe employee ClassThe SortedArray ClassIn main()Searching for a Specific ElementThe Binary SearchConstructors Used to Initialize ArrayQuiz 8Exercise 1Exercise 2Summary: Chapter 8End-Of-Chapter Discussion
Session 1: Introduction to Virtual FunctionsPolymorphismNormal Member Functions Accessed withPointersVirtual Member Functions Accessed withPointersLate BindingHow It WorksArrays of Pointers to ObjectsDon’t Try This with ObjectsQuiz 1Session 2: Examples of Virtual FunctionsA Personnel ExampleThe main() ProgramThe ClassesVirtual FunctionsThe isOutstanding() FunctionVirtual Functions in Other ClassesA Graphics ExampleNo shape Objects, PleaseInitializing the ArrayVirtual Functions and ConstructorsQuiz 2Exercise 1Exercise 2Session 3: Decoupling with PolymorphismPassing ReferencesPassing PointersA person Class ExampleQuiz 3Exercise 1Exercise 2Session 4: Abstract Classes and Virtual DestructorsAbstract ClassesPure Virtual FunctionsA Short ExampleThe shape ExampleThe Compiler on WatchAbstract Classes and Pure Virtual FunctionsPure Virtual Functions with BodiesVirtual DestructorsIs the Derived Class Destructor Executed?Not Unless It’s VirtualA More Realistic ExampleWhen Do You Use Virtual Functions?Quiz 4Exercise 1Exercise 2Midchapter DiscussionSession 5: Runtime Type IdentificationA Simple ExampleA More Realistic ExampleQuiz 5Exercise 1Session 6: Friend FunctionsThe “Left-Side” ProblemNo Problem on the RightNot So Easy on the LeftFriends to the RescueBreaching the WallsFriends for Functional NotationFriends as BridgesQuiz 6Exercise 1Exercise 2Session 7: Friend ClassesInterclass CommunicationAccessing Private Members in a PreviouslyDefined ClassAccessing Private Members in a Not YetDefined ClassPointers in Interclass CommunicationA Horse Race ExampleOperation of FRIHORSEDesigning the Horse RaceCreating the HorsesKeeping TimeQuiz 7Exercise 1Exercise 2Session 8: Nested Classes and Static Member DataNested ClassesCommunication Between Nested ClassesHorse Racing and Nested ClassesHorse Racing and Static DataQuiz 8Exercise 1Exercise 2Summary: Chapter 9End-of-Chapter Discussion
SESSION 1: Stream ClassesAdvantages of StreamsThe Stream Class HierarchyThe ios ClassFormatting FlagsManipulatorsFunctionsThe istream ClassThe ostream ClassThe iostream and the _withassign ClassesPredefined Stream ObjectsStream ErrorsError-Status BitsInputting NumbersToo Many CharactersNo-Input InputInputting Strings and CharactersError-Free DistancesAll-Character InputQuiz 2Exercise 1Exercise 2Session 3: Disk File I/O with StreamsFormatted File I/OWriting DataReading DataStrings with Embedded BlanksDetecting End-of-FileCharacter I/ODirect Access to the streambuf ObjectBinary I/OObject I/OWriting an Object to DiskReading an Object from DiskCompatible Data StructuresI/O with Multiple ObjectsThe fstream ClassThe open() FunctionThe Mode BitsQuiz 3Exercise 1Exercise 2Session 4: File Errors and File PointersError Handling in File I/OReacting to ErrorsAnalyzing ErrorsFile PointersSpecifying the PositionSpecifying the OffsetThe tellg() FunctionQuiz 4Exercise 1Exercise 2MidChapter DiscussionSession 5: File I/O Using Member FunctionsObjects That Read and Write ThemselvesClasses That Read and Write ThemselvesStatic FunctionsSize of Derived ObjectsUsing the typeid() FunctionCode Number for Object TypeNo Homemade Objects, PleaseInteraction with empl_ioQuiz 5Exercise 1Exercise 2Session 6: Overloading the << and >> OperatorsOverloading for cout and cinOverloading for FilesOverloading for Binary I/OQuiz 6Exercise 1Exercise 2Session 7: Memory as a Stream ObjectFixed Buffer SizeThe ostrstream ObjectInput Memory StreamsUniversalityFile PointersDynamic Buffer SizeQuiz 7Exercise 1Exercise 2Session 8: Printer Output and Other RefinementsCommand-Line ArgumentsPrinter OutputRedirectionUsing the redir ProgramRedirecting OutputRedirecting InputRedirecting Input and OutputRedirection and the _withassign ClassesQuiz 8Exercise 1Exercise 2Summary: Chapter 10End-of-Chapter Discussion
Session 1: Function TemplatesA Simple Function TemplateFunction Template SyntaxWhat the Compiler DoesFunction Templates with Multiple ArgumentsTemplate Arguments Must MatchMore Than One Template ArgumentWhy Not Macros?What Works?Start with a Normal FunctionQuiz 1Exercise 1Exercise 2Session 2: Class TemplatesClass Name Depends on ContextA Linked List Class Using TemplatesStoring User-Defined Data TypesEmployees in a Linked ListWhat Can You Store?Quiz 2Exercise 1Exercise 2Session 3: ExceptionsWhy Do We Need Exceptions?Exception SyntaxA Simple Exception ExampleSpecifying the Exception ClassThrowing an ExceptionThe try BlockThe Exception Handler (catch Block)The Sequence of EventsQuiz 3Exercise 1Exercise 2Session 4: Exceptions ContinuedMultiple ExceptionsExceptions with the Distance ClassExceptions with ArgumentsSpecifying Data in an Exception ClassInitializing an Exception ObjectExtracting Data from the Exception ObjectThe xalloc ClassException NotesDestructors Called AutomaticallyTermination OrientedFunction NestingCan’t Return to Throw PointQuiz 4Exercise 1Exercise 2Midchapter DiscussionSession 5: Explicit Casts, typedef, and the OperatorExplicit CastsStatic CastsDynamic CastsConst CastsReinterpret CastsThe typedef SpecifierPointers and typedef Classes and typedef More Portable CodeTemplates and typedef Overloading the Function OperatorQuiz 5Exercise 1Exercise 2Session 6: The Standard string ClassHeader FilesConstructors and OperatorsMember FunctionsThe insert(), remove(), and replace() MemberFunctionsThe find() Member FunctionThe find_first_of() Member FunctionThe substr() Member FunctionPassing string Objects as ArgumentsThe copy() Member FunctionThe c_str() Member FunctionArrays of string ObjectsThe compare() Member FunctionGet Ready for the STLQuiz 6Exercise 1Exercise 2Session 7: Multifile ProgramsReasons for Multifile ProgramsClass LibrariesPublic ComponentsPrivate ComponentsOrganization and ConceptualizationHow to Create a Multifile ProgramHeader FilesDirectoryMultiple FilesNamespacesDeclaring NamespacesAccessing Elements from Another NamespaceQuiz 7Exercise 1Exercise 2Session 8: A Very-Long-Numbers ExampleNumbers as StringsThe Class SpecifierThe Member FunctionsThe Application ProgramSubtraction and DivisionExercise 1Summary: Chapter 11End-of-Chapter Discussion
Session 1: Introduction to the STLContainersSequence ContainersAssociative ContainersMember FunctionsAbstract Data TypesAlgorithmsIteratorsPotential Problems with the STLQuiz 1Session 2: AlgorithmsThe find() AlgorithmHeader FilesRangesThe count() AlgorithmThe sort() AlgorithmThe search() AlgorithmThe merge() AlgorithmFunction ObjectsUser-Written Functions in Place of FunctionObjectsBoolean TypeAdding _if to AlgorithmsThe for_each() AlgorithmThe transform() AlgorithmQuiz 2Exercise 1Session 3: Sequential ContainersVectorsMember Functions push_back(), size(), andOperator [ ]Member Functions swap(), empty() back(), andpop_back()Member Functions insert() and erase()ListsMember Functions push_front(), front(), andpop_frontMember Functions reverse(), merge(), andunique()DequesQuiz 3Exercise 1Exercise 2Session 4: IteratorsIterators as Smart PointersOrdinary Pointers UnderpoweredWhose Responsibility?Iterators as an InterfaceMatching Algorithms with ContainersPlugging the Cable into a ContainerPlugging the Cables into the AlgorithmThe Tables Tell the StoryOverlapping Member Functions andAlgorithmsIterators at WorkData AccessData InsertionAlgorithms and IteratorsQuiz 4Exercise 1Exercise 2Midchapter DiscussionSession 5: Specialized IteratorsIterator AdaptersReverse IteratorsInsert IteratorsStream IteratorsThe ostream_iterator ClassThe istream_iterator ClassQuiz 5Exercise 1Exercise 2Session 6: Associative ContainersSets and MultisetsMaps and MultimapsIterating Through MapsPairsThe [ ] OperatorHash Table VersionsQuiz 6Exercise 1Exercise 2Session 7: Storing User-Defined ObjectsA Set of person ObjectsNecessary Member FunctionsOrderingJust Like Basic TypesA List of person ObjectsFinding All persons with a Specified NameFinding All persons with a Specified PhoneNumberA List of airtime ObjectsQuiz 7Exercise 1Exercise 2Session 8: Function ObjectsPredefined Function ObjectsWriting Your Own Function ObjectsDifferent Criteria for SortingBinding: Providing Values to Function ObjectsQuiz 8Exercise 1Exercise 2Summary: Chapter 12End-of-Chapter Discussion
 
Introduction
If you want to know whether you should buy this book, read thisintroduction!First question: Why learn C++ at all? That's easy: It’s today’s dominantcomputer language. When the going gets tough, the professionals turn toC++. There are many other languages, of course, but they lack theuniversality and power of C++. For example, Visual Basic is useful forquickly putting together applications that aren’t too large or demanding,assembly language is good if you’re writing a device driver, and Java isgreat for the World Wide Web. (Java is derived from C++ anyway.) But fora major standalone application, C++ is the most popular language that hasthe power and flexibility to produce the fastest, best-performing code. Forthese reasons, C++ is a major part of the Computer Science curriculum atalmost every school and university. If you’re a programmer, chances arethat sooner or later you’ll need to know it.
What’s Different About This Book?
This book is a C++ tutorial. But there are a lot of C++ tutorials on themarket. How is this one different? Three ways: It’s easy to understand, it’sorganized in a better and unique way, and it comes with a free backupsystem if there’s anything that’s giving you trouble. Let’s look at thesefeatures in detail.
 Easy to Understand 
This book starts off with very easy examples; we don’t assume you’re arocket scientist. We try to explain everything with no assumptions aboutwhat you may already know. We use plenty of figures and analogies toclarify the text. The program examples are heavily commented to makeeverything as clear as possible.As you progress further into the book, the examples become morechallenging, but we try to keep the increase in difficulty gradual, so you’realways ready for what comes next. Ultimately we cover all the mainfeatures of C++.
Unique Organization
Unlike most other C++ books, this one uses, from the very first example,real object-oriented programs. Most books, in an attempt to stick with thefamiliar, start with old-fashioned procedural examples and work up to fullobject-based examples half-way through. This may seem easier, but in thelong run it’s counter-productive, because it encourages bad thinking habits.The whole point of C++ is to write object-oriented programs. If they don’tdo that from the beginning, they’re missing the point. And, as it turns out,object-oriented programs aren’t that hard anyway.
The Waite Group Interactive Series
The third way this book differs from other C++ books is that it’s a WaiteGroup Interactive book. This isn't just publisher’s hype: By connecting youto the Waite Group via the World Wide Web, this new approach canactually play a significant role in helping you to learn C++. There are manyaspects to the Interactive Series. We won’t dwell on them here, since thedetails are presented elsewhere. We should note, however, that this book was written from the ground up to work as part of the Interactive Series.First, each chapter is divided into short, easily digestible lessons. Eachlesson is devoted to a specific topic and requires only an hour(approximately) to read and understand. This makes it easy to sit down withthe book and learn something, even if your time is limited.Each lesson is followed by a quiz to ensure that you’ve understood thematerial. You can answer the quizzes by yourself, or you can do them onthe Web, which will grade them automatically. There are almost 500 quizquestions in the book, so you'll really find out how well you understand thesubject.The Waite Group Web site offers many other advantages. A principle one ismentoring, which is the ability to ask questions and get answers back, justas you would if you were taking a class at a university and could talk to theprofessor.As a final plus, this book includes a full chapter on the Standard TemplateLibrary (STL), which is fast becoming an essential part of every C++programmer’s bag of tricks, but which has not yet made its way into manyC++ books.
What Do You Need to Know?
This book is intended for anyone who wants to learn C++ from the groundup. That is, it does not assume any previous knowledge of C (or any otherspecific programming language). It’s nice if you’ve had some exposure toanother language, but even that is not essential. In fact, it may be better notto have bad old (procedural) habits to unlearn.If you already know the C language, you’ll find that perhaps a third of thematerial in this book is familiar to you. You’ll know the basic syntax of 
for
loops,
switch
statements, and pointers, for example. However,you’ll be surprised by how much of the material is new. Almost all theexamples, including those that explain basic syntax, use the object-orientedapproach, so you’ll find you’re learning OOP even when you’re readingabout syntax you already know.
What Hardware and Software Do You Need?
You should have some kind of C++ compiler at your disposal. The exampleprograms in this book are—for the most part—generic: That is, they willwork with most compilers. Thus, you aren’t constrained to use anyparticular system.In a few instances we wrote compiler-specific code so we could use moresophisticated screen displays. This applies to only a half-dozen examplesout of more than 200 programs in the book. For these, the code in the book is specific to Borland C++ (and Turbo C++, which is similar). These areprobably the most popular compilers and among the easiest to use.However, if you're using Microsoft Visual C++, Appendix C shows youhow, by inserting a special header file (provided on the CD-ROM) into theexample’s source code, you can easily convert these few programs to work with your compiler.
Go For It!
Learning C++ has never been easier. With its short lessons,easy-to-understand writing style, and the support of Waite Group Press viatheir Web site, you should be on your way to C++ mastery in less time thanyou thought possible.
Installation
The companion CD-ROM contains all of the source code and theexecutables from the lessons in the book, as well as the NetManageChameleon installer. Since all of the code for the lessons in this book are onthe companion CD-ROM, there is no need to type the code if you want touse it for your own projects. We will illustrate how to copy the files fromthe companion CD-ROM to your hard drive.This section will walk you through the steps necessary to install the sourcecode from the CD-ROM to your hard drive for DOS/Windows 3.x andWindows 95. To install the NetManage Chameleon, please see the section
The Chameleon Sampler 
.
Note:
For the following examples, we are going to assume that theCD-ROM drive you want to copy files from is the D: drive and the harddrive you want to copy files to is the C: drive. If your system is set updifferently, please substitute the appropriate drive letters for your system.
DOS
These instructions for DOS assume you have no familiarity with DOScommands. If you feel uncomfortable with DOS and are using theseinstructions from the Windows DOS Prompt, please exit and follow theinstructions for your version of Windows.
1.
Move to the drive that you want to copy the files to. If you want tocopy the files onto the C: drive, type
C:
and press ENTER. Ensure you are at the root directory by typing
CD \
and pressing ENTER.
2.
Create the directory you would like to store your files into. If youwant to store the files into the CPPIC directory, type
MD CPPIC
and press ENTER.
3.
Move to that directory. If you created a directory called CPPIC,move to that directory by typing
CD CPPIC
and press ENTER.
4.
To copy all of the files to your hard drive, simply type
XCOPY D:\*.* /V /S
and press ENTER. To copy individual subdirectories from theCD-ROM to the CPPIC directory on your hard drive, you must createthe chapter directories before you copy the contents. For example, if you wanted to copy the code for Chapters 2, 5, and 7, you would type
MD CHAP_02MD CHAP_05MD CHAP_07
and press ENTER after each line. Then you would type
CD \CPPIC\CHAP_02XCOPY D:\CHAP_02 /V /SCD \CPPIC\CHAP_05XCOPY D:\CHAP_05 /V /SCD \CPPIC\CHAP_07XCOPY D:\CHAP_07 /V /S
and press ENTER after each line. The /V is a DOS switch to verifyfiles while copying and /S is a DOS switch to copy thesubdirectories. Depending on the configuration and performance of your system, these steps may take from a few moments to a fewminutes.
Windows 3.x
The following steps are for the use of Windows 3.x with short file names.
1.
Open the File Manager.
2.
In File Manager, locate the drive you want to copy to and click onit.
3.
If you have a directory to copy the files to, skip to Step 4.Otherwise, create a new directory by selecting File, Create Directory.Type
CPPIC
or a directory name of your choice and press ENTER or click on theOK button.
4.
Click on CPPIC or the directory you created.
5.
Select the drive letter of your CD-ROM drive.
6.
Double-click on the D: drive icon. You should see the followingdirectory structure:
APP_CCHAP_02CHAP_03CHAP_04CHAP_05CHAP_06CHAP_07CHAP_08CHAP_09CHAP_10CHAP_11CHAP_12NTMANAGE
Control-click on the directories that you want to copy and drag theselection to the destination drive. Depending on how fast yourcomputer is and also depending on the options set for your computer,the copying process may take a few moments to a few minutes.
Note:
When Windows copies a CD-ROM, it does not change theRead-only attribute for the files it copies. You can view the files, but youcannot edit them until you remove this attribute. To change it on all of thefiles, select the top-most directory with the files in it. In File Manager,select File, Properties and click on the Read-only checkbox to deselect itand click on OK.
Windows 95
The easiest way to copy files using Windows 95 is by using the Desktop.
1.
Double-click on the My Computer icon. Your drives will appearin a window on the desktop.
2.
Double-click on your hard drive and create a new folder, such as
C++ Interactive Course
, by selecting File, New, Folder from thewindow menu. A folder called
 New Folder 
will be created on yourhard drive with the name highlighted. Type in the name you want andpress the ENTER key.
3.
Go back to your drive window and double-click on the icon thatrepresents your CD-ROM. You will see a window that has 11 chapterfolders, one appendix folder, and one Program folder.
4.
Select the directories you want to copy (control-click on thefolders if you’re not copying all of them) and drag your selection tothe directory you created on your hard drive. You might need toreposition your windows to make the window for your hard drivevisible. Depending on your system’s performance, this may take afew moments to a few minutes
Note:
When Windows (any version) copies a CD-ROM, it does notchange the Read-only attribute for the files it copies. You can view thefiles, but you cannot edit them until you remove this attribute. To changeit on all of the files, select the top-most directory with the files in it. InExplorer, select File, Properties and click on the Read-only checkbox todeselect it and click on OK.
The Chameleon Sampler
The NetManage Internet Chameleon is one of the most versatile andeasy-to-use set of Internet tools in the world. Chameleon helps you sign upwith an Internet provider, connect cleanly to the Internet, and access avariety of resources—including a pretty cool Web browser. The Chameleonpackage includes

Custom,
for connecting to the Internet

WebSurfer,
a full-featured World Wide Web browser

Gopher,
which lets you access any gopher menu worldwide

 NEWTNews,
a Usenet newsreader

 Mail,
a convenient way to send and receive e-mail

 Archie,
which lets you search for a file over the Internet

Telnet,
for connecting to a remote computer

FTP,
for transferring files over the Internet

FTP Server,
which lets you allow others to download or uploadfiles to your PC

 Mail Utilities,
programs that help you compact or organize yourmailbox files to save space

Ping,
to test if you’re connected to a remote computer

Finger,
to check if a friend is connected to the Internet

Whois,
to get information about people registered in the NIC(Network Information Center) databaseYou can sample the Chameleon tools for 30 days at no charge. If you likewhat you see, you can register everything for 50 bucks.
Installing the Chameleon
Note:
In the installation directions here, we assume that your hard disk isthe C: drive and your CD-ROM is the D: drive. If this doesn’t match yourcomputer, substitute C: or D: with the correct drive designation.
To copy the sampler software onto your hard disk, run the Setup program.While under Windows, select File, Run in the Program Manager. In theRun dialog box, type
d:\windows\browsers\ntmanage\disk_1\setup.exe
and then press the OK button.The Setup program will ask you where to install the NetManage program.The default suggested is fine for most people. If you want it installedelsewhere, type in the drive and directory of your choosing and selectContinue.After a few moments, the Setup program will ask you to type in the path of the second batch of files. Select the 1 in
 DISK_1
and change it to 2, andselect Continue.After another few moments, the Setup program will ask you to type in thepath of the third batch of files. Select the 2 in
 DISK_2
and change it to 3,and select Continue.Click OK when Setup tells you that installation is complete. You are nowready to setup your Internet account!
Signing Up for an Internet Provider Account
If you don’t already have one, the Chameleon package makes it easy to signup with one of several popular Internet providers. Read Chapter 1 for moreinformation about what services are offered by Internet providers.If you’d like to sign up using the Chameleon software, run the AutomaticInternet-Click to Start icon.To learn about a particular Internet provider, click one of the tabs (otherthan NetManage) in the Select Internet Provider window. Most providersgive you several hours (or even a month) of free trial time. To read aboutthe locations an Internet provider can cover, the monthly price, and otherimportant information, click the More Info button at the bottom of thescreen. If you have specific questions, contact the provider directly.When you’re ready to begin the sign-up procedure, click the Signup button.You’ll see a registration screen similar to the one in Figure I-1. Fill in yourname (as it appears on your credit card), address, phone number, and creditcard information.
The easiest way to sign up for an Internet provider
Note:
You will not actually be charged any provider fees until youofficially register with the service. You can cancel the registrationtransaction at any time during the sign-on process. If you do decide toregister, your credit card number will be sent over a secure phone line.
As you work through the sign-up process, there may be other tabs askingfor additional information. If so, click these tabs and fill in the forms.Select the Phone List button at the bottom of the screen. The Phone Listdialog appears, listing possible phone numbers you can use to register. If one of the numbers is in your area code, select it. Otherwise, select thetoll-free 800 number.
Note:
If necessary, you can edit the registration phone number. Somesystems, for example, require you to dial a 9 to reach an outside line. Justtype in this 9.
When you’ve typed in all your vital stats, return to the first registration tab.Click Send to dial the toll-free number and begin the registration process.The icons to the right will light up as each stage of the dialing process iscompleted. The set of traffic lights tell you if each stage—initializing themodem, dialing, connecting, and communicating—has worked.
Note:
You may need to click the Advanced button to specify specialmodem ports or commands.
Follow the instructions that appear as the registration proceeds. You will begiven the option to select from various service and pricing plans. Youraccount information (username, e-mail address, password, dial-up number,and IP address) will automatically be configured into the Chameleonpackage. An interface will be created for the Custom program, whichquickly and flawlessly connects you to the Internet.That’s it! You can now reboot your system to kick-start everything.
Registering the Chameleon Software
If you already have an Internet account, you can set up the InternetChameleon software (shown in Figure I-2) and start using it within minutes.Run the Automatic Internet-Click to Start program.
The full Chameleon package in the Internet Chameleonprogram groupMake sure the NetManage tab is selected, and then click the Signup button.You can now activate the software for a free 30-day demonstration period.After this period, the Chameleon software will no longer work. If youdecide to register the Chameleon package (for $50), your credit card will becharged and your software will be activated permanently.Fill in all the information on both forms, as shown in Figure I-1, includingyour credit card number (it won’t be charged unless you complete theregistration). You may need to contact your Internet provider for theInternet information on the second form.Select the Phone button, and choose a local or toll-free phone number. Thenclick the Send button to dial in to NetManage and get your softwareactivated.Once you connect, you are given the following choices:
Activate your software for a free 30-day demonstration.
Purchase your software to activate it permanently.
Configure your connection (if your Chameleon software hasalready been activated).
Connecting to the Internet
Now that you have selected a provider and registered your software, youcan actually get hooked in to the Internet. To do this, you need to run theCustom program (Figure I-3) from Windows File Manager.
Your customized on-ramp onto the Information SuperhighwayIf you used the Chameleon package to sign up with your Internet provider,an automatic configuration file should have already been written for you.Otherwise, Chameleon comes with the configurations for most popularInternet providers. Select File, Open and look for the configuration file foryour provider. If your provider is not listed, you’ll need to contact them andask what the proper settings are. They may even be able to send you aprewritten Chameleon configuration file.If you do need to enter the connection settings yourself, use the appropriatevalues you have obtained from your Internet provider. You can verify oredit the following information under the Setup menu:
IP Address
Subnet Mask 
Host Name
Domain Name
Port
Modem
Dial
Login
Interface Name
BOOTPYou may also need to fill in the following under the Services menu:
Default Gateway
Domain ServersRead Chapter 1 for more information about these terms.
 Logging In
Once your configuration settings are in place, simply click the Connectmenu to dial up your Internet provider and get connected. If all goes well,you should hear a small beep, and a program known as Newt will run. Thisprogram lets Windows communicate with the Internet. You can thenminimize the Custom program and run the Internet application of yourchoice.
 Logging Out
When you’re done using the Internet, call up the Custom program and click the Disconnect menu.
Web Browsing with Websurfer
WebSurfer is a full-featured World Wide Web browser similar to Mosaic.You can read all about browsers in Chapter 2 and about Mosaic in Chapter5. To start exploring the Web, first use the Chameleon Custom program toconnect to the Internet. Then run the WebSurfer program.Like Mosaic, WebSurfer has a toolbar (see the top of Figure I-4) that acts asa shortcut for most commands. The toolbar contains
The WebSurfer browser in all its glory
Show Connection Status: Shows you which links are currentlybeing loaded.
Go to URL: Opens a specific Web URL (defined in Chapter 1).
Get URL: Reloads the current document.
Hotlist: Shows the list of your favorite Web pages for you tochoose from. To go to a page, just double-click on it. You can alsodelete pages from the list by selecting the page and clicking Remove.
Make Hot: Adds the current Web page to your hotlist.
Back: Revisits the Web page you just came from.
Forward: Goes to the next Web page in the series, if applicable.
Home: Returns to the Web page you started from.
Cancel All: Stops the loading of the current Web page.
 Loading a Web Page from the Internet
Like Mosaic, WebSurfer combines text and graphics on the same page. Anytext in blue or graphics with a blue border are hypertext
 
links to other Webpages, multimedia files, or Internet areas. To load a link, just click on it.You can also load up a document directly. Just select Retrieve, Go To URLand type in the document’s exact URL. Alternatively, you can type adocument’s URL in the Dialog bar’s URL box and press to loadit.If the document is a Web page, it will be displayed. If the document is agraphic, sound, or movie, the WebSurfer program will attempt to call up aviewer program to display/play it. If the document is any other type of multimedia file, WebSurfer allows you to save the document directly toyour hard disk.To find out more about the current Web document, select Retrieve,Properties.
 Loading a Web Page from Your Hard Disk
If you have any Web pages on your hard disk (perhaps ones that you’vecreated yourself), you can easily use WebSurfer to view them. SelectRetrieve, Open Local File. Choose the file you want to view and click OK.You can even edit the current Web document—a very handy capability forWeb developers. Select Retrieve, Edit HTML. Then access the Retrieve,Refresh From Disk menu item to reload the page in a flash and see whatyour edits look like.
Other Internet Tools
The Chameleon package contains software for every Internet resource youcould possibly want. To use FTP, e-mail, telnet, gopher, or any otherInternet program, first connect to the Internet using the Custom application.Then you can communicate with friends across the world using Mail, reador post messages to thousands of newsgroups using NEWTNews, browsemenus of data using gopher, download tons of cool software using FTP, andmuch moreTable of Contents
Products|Contact Us|About Us|Privacy|Ad Info|Home
Use of this site is subject to certainTerms & Conditions,Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express writtenpermissionof EarthWeb isprohibited. Read EarthWeb'sprivacystatement.
ference/archive/1571690638/index.html [21-03-2000 18:54:05]

Activity (20)

You've already reviewed this. Edit your review.
1 hundred reads
1 thousand reads
akbisoi1 liked this
Makarius Yuwono liked this
bhalesh liked this
Nahid Ali liked this
readerman247 liked this
Quay San liked this

You're Reading a Free Preview

Download
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->