283 77 4MB
English Pages 502 Year 2000
C++ Weekend Crash Course
C++ Weekend Crash Course St ephen R. Davis
IDG Bo o ks Wo rldwide, Inc. An Inte rnatio nal Data Gro up Co mpany Fo ste r City, CA
◆
Chicago , IL
◆
Indianapo lis, IN
◆
Ne w Yo rk, NY
C++ We e ke nd Crash Course Published by
IDG Books Worldwide, Inc. An Internatio nal Data Gro up Co mpany 919 E. Hillsdale Blvd., Suite 400 Fo ster City, CA 94404 www.idgbooks.com ( IDG Bo o ks Wo rldwide Web site) Co pyright © 2000 IDG Bo o ks Wo rldwide, Inc. All rights reserved. No part of this bo o k, including interio r design, cover design, and ico ns, may be repro duced o r transmitted in any fo rm, by any means ( electro nic, pho to co pying, reco rding, o r o therwise) witho ut the prio r written permissio n of the publisher. Library of Co ngress Card Number: 00- 101537 ISBN: 0- 7645- 4689- 9 Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 1B/ RS/ QU/ QQ/ FC Distributed in the United States by IDG Bo o ks Wo rldwide, Inc. Distributed by CDG Bo o ks Canada Inc. fo r Canada; by Transwo rld Publishers Limited in the United Kingdo m; by IDG No rge Bo o ks fo r No rway; by IDG Sweden Bo o ks fo r Sweden; by IDG Bo o ks Australia Publishing Co rpo ratio n Pty. Ltd. fo r Australia and New Zealand; by TransQuest Publishers Pte Ltd. fo r Singapo re, Malaysia, Thailand, Indo nesia, and Ho ng Ko ng; by Go to p Info rmatio n Inc. fo r Taiwan; by ICG Muse, Inc. fo r Japan; by Intersoft fo r So uth Africa; by Eyro lles fo r France; by Internatio nal Tho mso n Publishing fo r Germany, Austria, and Switzerland; by Distribuido ra Cuspide fo r Argentina; by LR Internatio nal fo r Brazil; by Galileo Libro s fo r Chile; by Edicio nes ZETA S.C.R. Ltda. fo r Peru; by WS Co mputer Publishing Co rpo ratio n, Inc., fo r the Philippines; by Co ntempo ranea de Edicio nes fo r
Venezuela; by Express Co mputer Distributo rs fo r the Caribbean and West Indies; by Micro nesia Media Distributo r, Inc. fo r Micro nesia; by Chips Co mputado ras S.A. de C.V. fo r Mexico ; by Edito rial No rma de Panama S.A. fo r Panama; by American Bo o ksho ps fo r Finland. Fo r general info rmatio n o n IDG Bo o ks Wo rldwide’s bo o ks in the U.S., please call o ur Co nsumer Custo mer Service department at 800- 762- 2974. Fo r reseller info rmatio n, including disco unts and premium sales, please call o ur Reseller Custo mer Service department at 800- 434- 3422. Fo r info rmatio n o n where to purchase IDG Bo o ks Wo rldwide’s bo o ks o utside the U.S., please co ntact o ur Internatio nal Sales department at 317- 596- 5530 o r fax 317- 572- 4002. Fo r co nsumer info rmatio n o n fo reign language translatio ns, please co ntact o ur Custo mer Service department at 800- 434- 3422, fax 317- 572- 4002, o r e- mail rights@ idgbo o ks.co m. Fo r info rmatio n o n licensing fo reign o r do mestic rights, please pho ne +1- 650- 653- 7098. Fo r sales inquiries and special prices fo r bulk quantities, please co ntact o ur Order Services department at 800- 434- 3422 o r write to the address above. Fo r info rmatio n o n using IDG Bo o ks Wo rldwide’s bo o ks in the classro o m o r fo r o rdering examinatio n co pies, please co ntact o ur Educatio nal Sales department at 800- 434- 2086 o r fax 317- 572- 4005. Fo r press review co pies, autho r interviews, o r o ther publicity info rmatio n, please co ntact o ur Public Relatio ns department at 650- 653- 7000 o r fax 650- 653- 7500. Fo r autho rizatio n to pho to co py items fo r co rpo rate, perso nal, o r educatio nal use, please co ntact Co pyright Clearance Center, 222 Ro sewo o d Drive, Danvers, MA 01923, o r fax 978- 750- 4470.
LIMIT OF LIABILITY/ DISCLAIMER OF WARRANTY: THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK. THE PUBLISHER AND AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. THERE ARE NO WARRANTIES WHICH EXTEND BEYOND THE DESCRIPTIONS CONTAINED IN THIS PARAGRAPH. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ACCURACY AND COMPLETENESS OF THE INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT GUARANTEED OR WARRANTED TO PRODUCE ANY PARTICULAR RESULTS, AND THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY INDIVIDUAL. NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES. Trade marks: All brand names and pro duct names used in this bo o k are trade names, service marks, trademarks, o r registered trademarks of their respective owners. IDG Bo o ks Wo rldwide is no t asso ciated with any pro duct o r vendo r mentio ned in this bo o k. is a registered trademark o r trademark under exclusive license to IDG Bo o ks Wo rldwide, Inc. fro m Internatio nal Data Gro up, Inc. in the United States and/ o r o ther co untries.
Welcome to the world of IDG Books Worldwide. IDG Books Worldwide, Inc., is a subsidiary of International Data Group, the world’s largest publisher of computer-related information and the leading global provider of information services on information technology. IDG was founded more than 30 years ago by Patrick J. McGovern and now employs more than 9,000 people worldwide. IDG publishes more than 290 computer publications in over 75 countries. More than 90 million people read one or more IDG publications each month. Launched in 1990, IDG Books Worldwide is today the #1 publisher of best-selling computer books in the United States. We are proud to have received eight awards from the Computer Press Association in recognition of editorial excellence and three from Computer Currents’ First Annual Readers’ Choice Awards. Our bestselling ...For Dummies® series has more than 50 million copies in print with translations in 31 languages. IDG Books Worldwide, through a joint venture with IDG’s Hi-Tech Beijing, became the first U.S. publisher to publish a computer book in the People’s Republic of China. In record time, IDG Books Worldwide has become the first choice for millions of readers around the world who want to learn how to better manage their businesses. Our mission is simple: Every one of our books is designed to bring extra value and skill-building instructions to the reader. Our books are written by experts who understand and care about our readers. The knowledge base of our editorial staff comes from years of experience in publishing, education, and journalism — experience we use to produce books to carry us into the new millennium. In short, we care about books, so we attract the best people. We devote special attention to details such as audience, interior design, use of icons, and illustrations. And because we use an efficient process of authoring, editing, and desktop publishing our books electronically, we can spend more time ensuring superior content and less time on the technicalities of making books. You can count on our commitment to deliver high-quality books at competitive prices on topics you want to read about. At IDG Books Worldwide, we continue in the IDG tradition of delivering quality for more than 30 years. You’ll find no better book on a subject than one from IDG Books Worldwide.
John Kilcullen Chairman and CEO IDG Books Worldwide, Inc.
Eighth Annual Computer Press Awards 1992
Ninth Annual Computer Press Awards 1993
Tenth Annual Computer Press Awards 1994
Eleventh Annual Computer Press Awards 1995
IDG is the world’s leading IT media, research and exposition company. Founded in 1964, IDG had 1997 revenues of $2.05 billion and has more than 9,000 employees worldwide. IDG offers the widest range of media options that reach IT buyers in 75 countries representing 95% of worldwide IT spending. IDG’s diverse product and services portfolio spans six key areas including print publishing, online publishing, expositions and conferences, market research, education and training, and global marketing services. More than 90 million people read one or more of IDG’s 290 magazines and newspapers, including IDG’s leading global brands — Computerworld, PC World, Network World, Macworld and the Channel World family of publications. IDG Books Worldwide is one of the fastest-growing computer book publishers in the world, with more than 700 titles in 36 languages. The “...For Dummies® ” series alone has more than 50 million copies in print. IDG offers online users the largest network of technology-specific Web sites around the world through IDG.net (http://www.idg.net), which comprises more than 225 targeted Web sites in 55 countries worldwide. International Data Corporation (IDC) is the world’s largest provider of information technology data, analysis and consulting, with research centers in over 41 countries and more than 400 research analysts worldwide. IDG World Expo is a leading producer of more than 168 globally branded conferences and expositions in 35 countries including E3 (Electronic Entertainment Expo), Macworld Expo, ComNet, Windows World Expo, ICE (Internet Commerce Expo), Agenda, DEMO, and Spotlight. IDG’s training subsidiary, ExecuTrain, is the world’s largest computer training company, with more than 230 locations worldwide and 785 training courses. IDG Marketing Services helps industry-leading IT companies build international brand recognition by developing global integrated marketing programs via IDG’s print, online and exposition products worldwide. Further information about the company can be found at www.idg.com. 1/26/00
Credit s Acquisit ions Edit or Greg Croy Project Edit or Matthew E. Lusher Technical Edit or Greg L. Guntle Copy Edit ors S.B. Kleinman Rich Adin Media Development Specialist Jaso n Lusher
Graphics and Product ion Specialist s Ro bert Bihlmayer Jude Levinso n Michael Lewis Ramses Ramirez Victo r Pérez- Varela Dina F Quan Qualit y Cont rol Specialist Laura Taflinger Proof reading and I ndexing Yo rk Pro ductio n Services
Permissions Edit or Leno ra Chin Sell
I llust rat ors Mary Jo Richards Brent Savage
Media Development Manager Stephen No etzel
Cover Design Clark Creative Gro up
Project Coordinat ors Linda Maro usek Lo uigene A. Santo s Marco s Vergara
About t he Aut hor A 43- year- o ld father and husband, lives and wo rks in Greenville, Texas as a pro grammer bo th at wo rk and at play when he’s no t riding his bicycle o r hauling his so n to Tae Kwo n Do events.
to my wo nde rful ne w nie ce s, Christa and Sarah
Preface
++ We e ke nd Crash Co urse teaches the reader C++ in o ne admittedly busy
C
weekend: 30 sessio ns of a half- ho ur each, fo r 15 ho urs stretching fro m Friday evening to Sunday afterno o n. At the end of each part of the bo o k,
yo u’ll get a chance to pause, reflect, and review what yo u’ve just learned befo re pushing o n thro ugh the rest. Go o d luck!
What is C++? C++ is the mo st po pular pro gramming language in use to day. C++ is used in applicatio ns fro m the micro - pro grams that drive yo ur microwave oven, yo ur clo thes washer and yo ur TV up thro ugh the huge, hardco re pro grams that co ntro l nuclear missiles and Mars ro ckets — heh, yo u can’t blame the Mars ro ckets o n C++. In the late 1980s C began to show signs of age. Fo r o ne, C do es no t suppo rt the o bject- o riented pro gramming style. At the time, the o bject- o riented wave was taking the wo rld by sto rm. Employers were throwing mo ney at o bject- o riented pro grammers. All yo u had to do was wo rk the phrase “ new paradigm” into the co nversatio n in o rder to gather a crowd of admirers. The pro blem was that every pro gram wo rth its salt was written in C ( there were a few pro grams written in Pascal like early versio ns of Windows, but they do n’t co unt — if yo u are familiar with the earliest versio ns of Windows, yo u know why) . There was no way that co mpanies were go ing to rewrite all that co de just to ride the o bject- o riented wave. Object- o riented co ncepts had to be grafted o nto the existing C language. The result was called C++.
x
Preface
C++ is a superset of C. Any well written C pro gram can be rebuilt with a C++ to o l to generate a wo rking pro gram. That meant the co mpanies co uld upgrade their software in pieces. Existing co de co uld remain in C while new co de ado pted the extra features of C++. Fo rtunately fo r us, C++ is a standardized language. The American Natio nal Standards Institute ( ANSI) and Internatio nal Standards Organizatio n ( ISO) agree o n what C++ is. They issued a detailed descriptio n of the C++ language. This standardized language is often known as ANSI o r ISO standard C++ o r simply Standard C++. Standard C++ is no t co ntro lled by a single co mpany such as Micro soft ( o r Sun, fo r that matter) . The Standard C++ co mmunity is no t held ho stage to the whims of any o ne co rpo rate giant. In additio n, co mpanies do no t stray. Even Micro soft’s Visual C++ ho lds tightly to the C++ standard. The pro grams in C++ We e ke nd Crash Co urse in can be built using any Standard C++ implementatio n.
The Object -Orient ed Paradigm Object-o riented pro gramming is no t all hype. Object-o riented pro gramming really is a different appro ach to pro gramming than its predecesso r. Object-o riented pro grams are easier to write and maintain. Object-o riented mo dules can be reused with greater ease than tho se written in o lder styles. C++ We e ke nd Crash Co urse presents mo re than just the C++ language. Yo u need to
learn the o bject-o riented paradigm in o rder to make co mplete use of the power of C++. C++ We e ke nd Crash Co urse uses C++ examples to teach yo u the o bject-o riented view of the wo rld. Anyo ne who claims to pro gram in C++ witho ut understanding OO co ncepts is just using C++ as a “ better C”.
Who C++ We e ke nd Crash Co urse is intended fo r the beginner thro ugh the intermediate
reader. This bo o k serves the beginner by no t assuming any knowledge of pro gramming o r pro gramming co ncepts. The first few lesso ns go over real- wo rld, no n- techie explanatio ns of what pro gramming is. This bo o k is also great fo r the ho me pro grammer. The multiple examples demo nstrate pro gramming techniques used in mo dern, high speed pro grams.
Preface
xi
The serio us pro grammer o r student needs C++ in his quiver of pro gramming skills. The ability to speak knowledgeably of C++ can make the difference between getting that jo b and no t.
What C++ We e ke nd Crash Co urse is mo re than just a bo o k: it’s a co mplete develo pment
package. A CD- ROM co ntaining the famo us GNU C++ enviro nment is included with the bo o k. You need a word processor, such as Microsoft Word, in order to do word processing. Similarly, you need a C++ development environment in order to build and execute programs in C++. Many readers will already own a pro gramming enviro nment such as Micro soft’s ubiquito us Visual C++. Fo r tho se who do no t own a C++ enviro nment already, C++ We e ke nd Crash Co urse includes the standard GNU C++.
GNU C++ is no t so me stripped down, limited time pro gram. The GNU C++ package included with the bo o k is a co mplete, no - ho lds- barred develo pment enviro nment. C++ We e ke nd Crash Co urse provides co mplete instructio ns o n how to install and use bo th GNU C++ and Visual C++.
How C++ We e ke nd Crash Co urse fo llows a o ne- weekend fo rmat. Start with Friday
evening; co nclude Sunday afterno o n. This “ One weekend” fo rmat is:
쐌 ideal fo r the student who wants to catch up with the rest of the class, 쐌 ideal fo r the o ne-time pro grammer who wants to brush up o n his skills, and 쐌 ideal fo r anyo ne who wants to learn C++ while the kids are off at Grandma’s ho use. Of co urse, yo u can pro ceed thro ugh the bo o k at a mo re leisurely pace, if yo u prefer. Each sectio n of 4 to 6 lesso ns can be read independently. The reader sho uld be able to co mplete each of 30 sessio ns in 30 minutes. Time markers in the lesso n margin help keep the reader o n pace. Each session is followed by a set of review questions to allow the reader to judge her comprehension of the material. A set of more involved problems is provided at the end of each part to help drive home knowledge gained during the weekend session.
xii
Preface
Overview C++ We e ke nd Crash Co urse presents its sessio ns in gro ups of 4 to 6 chapters,
o rganized into 6 parts:
Friday evening — I nt roduct ion t o programming. This part intro duces pro gramming co ncepts and pro gresses yo u thro ugh yo ur first pro gram.
Sat urday morning — Basic C++ This part covers beginning to pics such as statement syntax, o perato rs and basic functio n.
Sat urday aft ernoon — St ruct ures and point ers. Here the reader delves the slightly mo re co mplicated to pic of po inter variables including their applicatio n in linked lists, arrays and o bjects.
Sat urday evening — I nt roduct ion t o object based programming. This is the jumping- off po int — to pics such as C++ structures, which fo rm the basis fo r o bject- o riented pro gramming are discussed.
Sunday morning — Object -orient ed programming. Here it is — the mo ther lo de. This part delves into bo th the syntax and the meaning of o bject- o riented pro gramming.
Sunday aft ernoon — Wrap up This part wraps up so me of the mo re invo lved to pics such as erro r handling using exceptio ns and overlo ading o perato rs.
xiii
Preface
Each part ends with a discussio n of debugging techniques fo r finding and removing the inevitable erro rs fro m yo ur pro grams. The level of co mplexity of these techniques is cho sen to match the reader’s ability glean fro m that sessio n. The appendix includes mo re invo lved pro gramming pro blems fo r each lesso n.
Layout and Feat ures No o ne sho uld try to simply power thro ugh this material witho ut a break. After each sessio n, and at the end of each part, yo u’ll find so me questio ns to check yo ur knowledge and give yo u a little practice at exercising yo ur new- fo und skills. Take a break, grab a snack, refill that coffee mug, and plunge into the next o ne! Along the way, you’ll find some features of the book to help you keep track of how far along you are, and point out interesting bits of info you shouldn’t miss. First, as you’re going through each session, check for something like this in the margin: This ico n and o thers like it let yo u know how much pro gress yo u’ve made thro ugh each sessio n as yo u go . There are also several ico ns to po int o ut special tidbits of info fo r yo u:
This is a f lag t o clue you in t o an import ant piece of info you should f ile away in your head for lat er. Not e
This gives you helpf ul advice on t he best ways t o do t hings, or a neat lit t le t echnique t hat can make your programming go easier. Tip
Don’t do t his! ‘Nuf f said.
Never
This highlight s informat ion you’ll f ind on t he CD- ROM t hat accompanies t his book. CD-ROM
xiv
Preface
We also o ccasio nally highlight text passages that explain key co ncepts of C++ syntax, like so :
SYNTAX
쑺
A function is a lo gically separate blo ck of C++ co de. The functio n co nstruct has the fo rm:
name() { // ... return ; }
Convent ions Used in t his Book Aside fro m the ico ns yo u’ve just seen, such as Tip , there are o nly three co nventio ns in this bo o k:
쐌 To indicate a menu cho ice, we use the ➪ symbo l, as in: Cho o se File ➪ Save Pro ject to save yo ur wo rk.
쐌 To indicate pro gramming co de within the bo dy text, we use a special fo nt, like this: Likewise, when writing main(), I co uld co ncentrate o n handling the summatio n returned by sumSequence(), while thinking o nly of what the functio n did, and no t abo ut how it wo rked.
쐌 To indicate a pro gramming example that’s no t in the bo dy text, we use this typeface: float fVariable1 = 10.0; float fVariable2 = (10 / 3) * 3; fVariable1 == fVariable2; // are these two equal?
What ’s left ? No thing. Open yo ur wo rk bo o k to the first page and start the clo ck. It’s Friday evening: yo u have two days.
Acknowledgment s
W
riting a bo o k like C++ Weekend Crash Co urse is a challenge, especially since it’s o ne of the first titles in a new series. I’m pleased to have had the o ppo rtunity to help launch a new way to teach readers the basics
of pro gramming. I’d first like to thank Greg Croy, acquisitio ns edito r, fo r spearheading this new series and selecting me as an autho r. I’d also like to thank my agent, Claudette Mo o re, fo r her wo rk with Greg and me to get this pro ject moving. The edito rial staff at IDG Bo o ks has been very helpful, and their co ntributio ns have made this a better bo o k: Matt Lusher, pro ject edito r; S.B. Kleinman and Rich Adin, co py edito rs; and the pro ductio n staff directly respo nsible fo r the lo o k of what yo u now ho ld in yo ur hands. Greg Guntle, technical edito r, provided a sharp eye fo r accuracy and detail. Finally, and mo st of all, I’d like to thank my family, who se suppo rt of my writing makes it all wo rthwhile.
xvii
Cont ent s at a Glance Preface .......................................................................................................ix Acknowledgment s .......................................................................................xv
FRI DAY ....................................................................................2 Part I — Friday Evening ..............................................................4 Sessio n 1–What Is Pro gramming Anyway? ........................................................5 Sessio n 2–Creating Yo ur First C++ Pro gram in Visual C++ ..................................11 Sessio n 3–Creating Yo ur First C++ Pro gram in GNU C++ .....................................23 Sessio n 4–C++ Instructio ns ...........................................................................37 Part I— Friday Evening Review .......................................................................45
SATURDAY ...............................................................................4 8 Part I I — Sat urday Morning .......................................................5 0 Sessio n 5–Variable Types ..............................................................................51 Sessio n 6–Mathematical Operatio ns ...............................................................65 Sessio n 7–Lo gical Operatio ns ........................................................................73 Sessio n 8–Flow Co ntro l Co mmands .................................................................85 Sessio n 9–Functio ns ...................................................................................101 Sessio n 10–Debugging I ..............................................................................115 Part II— Saturday Mo rning Review ................................................................127
Part I I I — Sat urday Af t ernoon ................................................1 3 0 Sessio n 11–The Array .................................................................................131 Sessio n 12–Intro to Classes .........................................................................149 Sessio n 13–A Few C++ Po inters ....................................................................159 Sessio n 14–A Few Mo re Po inters ..................................................................175 Sessio n 15–Po inters to Objects .....................................................................195 Sessio n 16–Debugging II .............................................................................213 Part III— Saturday Afterno o n Review ............................................................229
Part I V— Sat urday Evening .....................................................2 3 2 Sessio n 17–Object Pro gramming ..................................................................233 Sessio n 18–Active Classes ...........................................................................239 Sessio n 19–Maintaining Class Integrity .........................................................257 Sessio n 20–Class Co nstructo rs II ..................................................................273 Part IV— Saturday Evening Review ................................................................296
xviii
Cont ent s at a Glance
SUNDAY ................................................................................2 9 8 Part V— Sunday Morning ........................................................3 0 0 Sessio n 21–Inheritance ..............................................................................301 Sessio n 22–Po lymo rphism ...........................................................................315 Sessio n 23–Abstract Classes and Facto ring ....................................................329 Sessio n 24–Multiple Inheritance ..................................................................345 Sessio n 25–Large Pro grams .........................................................................361 Sessio n 26–C++ Prepro cesso r .......................................................................373 Part V— Sunday Mo rning Review ...................................................................384
Part VI — Sunday Af t ernoon ....................................................3 8 8 Sessio n 27–Overlo ading Operato rs ................................................................389 Sessio n 28–The Assignment Operato r ...........................................................409 Sessio n 29–Stream I/ O ...............................................................................419 Sessio n 30–Exceptio ns ................................................................................441 Part VI— Sunday Afterno o n Review ...............................................................456
Appendix A ...............................................................................................4 6 1 Appendix B ...............................................................................................4 8 3 Appendix C ...............................................................................................4 9 7 I ndex .......................................................................................................5 0 1 End- User License Agreement ......................................................................5 1 4 GNU General Public License ........................................................................5 1 7 CD- ROM I nst allat ion I nst ruct ions................................................................5 2 6
Cont ent s Preface .......................................................................................................ix Acknowledgment s .......................................................................................xv
FRI DAY .....................................................................................2 Part I – Friday Evening ................................................................4 Friday Evening ..........................................................................4 Session 1 – What I s Programming Anyway? ......................................................5 A Human Program ...........................................................................................6 The algo rithm ..............................................................................................6 The pro cesso r ...............................................................................................7 The pro gram ................................................................................................7 Co mputer pro cesso rs .....................................................................................9
Session 2 – Creat ing Your First C++ Program in Visual C++ ...............................1 1 Installing Visual C++ .....................................................................................1 2 Cre ating Your First Program ...........................................................................1 2 Building Your Program ..................................................................................1 4 Exe cuting Your Program ................................................................................1 8 Closing Points ...............................................................................................2 0 Pro gram o utput ..........................................................................................20 Visual C++ help ...........................................................................................20
Session 3 – Creat ing Your First C++ Program in GNU C++ .................................2 3 Installing GNU C++ ........................................................................................2 4 Cre ating Your First Program ...........................................................................2 6 Entering the C++ co de .................................................................................26
Building Your Program ..................................................................................2 9 Exe cuting Your Program ................................................................................3 3 Closing Points ...............................................................................................3 4 Pro gram o utput ..........................................................................................35 GNU C++ help .............................................................................................35
Session 4 – C++ I nst ruct ions .........................................................................3 7 The Program .................................................................................................3 7 The C++ Program Explaine d ...........................................................................3 9 The basic pro gram framewo rk .......................................................................39 Co mments ..................................................................................................40 There’s that framewo rk again ........................................................................40 Statements .................................................................................................41 Declaratio ns ...............................................................................................41 Input/ o utput .............................................................................................42
xx
Cont ent
Expre ssions ...................................................................................................4 2 Assignment ................................................................................................43 Expressio ns ( co ntinued) ...............................................................................43
Part I–Friday Evening Review .........................................................................45
SATURDAY ...............................................................................4 8 Part I I – Sat urday Morning .........................................................5 0 Session 5 – Variable Types ............................................................................5 1 De cimal Numbe rs ..........................................................................................5 2 The limitatio ns of int’s in C++ .......................................................................52 So lving the truncatio n pro blem ....................................................................55 Limitatio ns of flo ating po int ........................................................................56
Othe r Variable Type s .....................................................................................5 7 Types of co nstants ......................................................................................59 Special characters .......................................................................................59
Mixe d Mode Expre ssions ................................................................................6 1 Session 6 – Mat hemat ical Operat ions .............................................................6 5 Arithme tic Ope rators .....................................................................................6 6 Expre ssions ...................................................................................................6 7 Ope rator Pre ce de nce ......................................................................................6 8 Unary Ope rators ............................................................................................6 9 Assignme nt Ope rators ...................................................................................7 1 Session 7 – Logical Operat ions ......................................................................7 3 Simple Logical Ope rators ...............................................................................7 4 Sho rt circuits and C++ .................................................................................76 Lo gical variable types ..................................................................................76
Binary Numbe rs ............................................................................................7 7 Bitwise Logical Ope rations .............................................................................7 8 The single- bit o perato rs ...............................................................................78 The bitwise o perato rs ..................................................................................80 A simple test ..............................................................................................81 Why? .........................................................................................................82
Session 8 – Flow Cont rol Commands ...............................................................8 5 The Branch Command ....................................................................................8 6 Looping Commands .......................................................................................8 7 The while lo o p ............................................................................................88 The fo r lo o p ...............................................................................................91 Special lo o p co ntro ls ...................................................................................93
Ne ste d Control Commands .............................................................................9 6 Can We switch to a Diffe re nt Subje ct? ............................................................9 7
Cont ent s
xxi
Session 9 – Funct ions .................................................................................1 0 1 Sample Function Code .................................................................................1 0 2 Sample co de .............................................................................................102
Function .....................................................................................................1 0 5 Why use functio ns? ...................................................................................105 Simple functio ns .......................................................................................106 Functio ns with arguments ..........................................................................107 Multiple functio ns with the same nickname .................................................110
Function Prototype s ....................................................................................1 1 2 Variable Storage Type s .................................................................................1 1 3 Session 1 0 – Debugging I ............................................................................1 1 5 Type s of Errors ............................................................................................1 1 5 The Output-State me nt Te chnique .................................................................1 1 6 Catching Bug # 1 ..........................................................................................1 1 8 Visual C++ ................................................................................................118 GNU C++ ...................................................................................................120
Catching Bug # 2 ..........................................................................................1 2 2 Part II–Saturday Mo rning Review ..................................................................127
Part I I I – Sat urday Af t ernoon ...................................................1 3 0 Session 1 1 – The Array ...............................................................................1 3 1 What Is an Array? ........................................................................................1 3 2 An array in practice ...................................................................................134 Initializing an array ..................................................................................137 Why use arrays? ........................................................................................138 Arrays of arrays .........................................................................................138
Arrays of Characte rs ....................................................................................1 3 9 Manipulating Strings ...................................................................................1 4 2 Our own co ncatenate functio n ....................................................................142 C++ string- handling functio ns .....................................................................145 Wide characters .........................................................................................146
Obsole sce nt Output Functions ......................................................................1 4 6 Session 1 2 – I nt ro t o Classes ......................................................................1 4 9 Grouping Data .............................................................................................1 4 9 An example ..............................................................................................150 The pro blem .............................................................................................153
The Class .....................................................................................................1 5 3 The fo rmat of a class .................................................................................153 Example pro gram ......................................................................................155 Advantages ...............................................................................................157
xxii
Cont ent
Session 1 3 – A Few C++ Point ers .................................................................1 5 9 What’s Your Addre ss? ...................................................................................1 6 0 Introduction to Pointe r Variable s .................................................................1 6 2 Type s of Pointe rs .........................................................................................1 6 5 Passing Pointe rs to Functions ......................................................................1 6 7 Pass by value ............................................................................................167 Passing po inter values ...............................................................................168 Passing by reference ..................................................................................169
He ap Me mory ..............................................................................................1 6 9 Sco pe .......................................................................................................170 The sco pe pro blem .....................................................................................171 The heap so lutio n .....................................................................................172
Session 1 4 – A Few More Point ers ................................................................1 7 5 Pointe rs and Arrays .....................................................................................1 7 6 Operatio ns o n po inters ...............................................................................176 Character arrays ........................................................................................180 Operatio ns o n different po inter types ..........................................................185 Differences between po inters and arrays ......................................................185
Argume nts to the Program ...........................................................................1 8 7 Arrays of po inters .....................................................................................187 Arrays of character strings .........................................................................188 The arguments to main( ) ............................................................................190
Session 1 5 – Point ers t o Object s ..................................................................1 9 5 Pointe rs to Obje cts .......................................................................................1 9 5 Passing o bjects ..........................................................................................196 References ................................................................................................198 Return to the heap ....................................................................................199
The Array Data Structure .............................................................................1 9 9 Linke d Lists ................................................................................................2 0 0 Adding to the head of a linked list ..............................................................202 Other o peratio ns o n a linked list .................................................................203 Pro perties of linked lists ...........................................................................205
A Linke d Name Data Program .......................................................................2 0 6 Othe r Containe rs .........................................................................................2 1 0 Session 1 6 – Debugging I I ..........................................................................2 1 3 Which De bugge r? ........................................................................................2 1 4 The Te st Program .........................................................................................2 1 5 Single -Ste pping Through a Program .............................................................2 1 7 Single -Ste pping into a Function ...................................................................2 1 8 Using Bre akpoints .......................................................................................2 2 0 Viewing and Modifying Variable s .................................................................2 2 1 Using the Visual C++ De bugge r ....................................................................2 2 6 Part III–Saturday Afterno o n Review ..............................................................229
Cont ent s
xxiii
Part I V– Sat urday Evening .......................................................2 3 2 Session 1 7 – Object Programming ................................................................2 3 3 Abstraction and Microwave Ove ns ................................................................2 3 3 Functio nal nacho s .....................................................................................234 Object- o riented nacho s ..............................................................................235
Classification and Microwave Ove ns ..............................................................2 3 5 Why Build Obje cts This Way? .......................................................................2 3 6 Se lf-Containe d Classe s .................................................................................2 3 7 Session 1 8 – Act ive Classes .........................................................................2 3 9 Class Review ................................................................................................2 4 0 Limitations of Struct ...................................................................................2 4 1 A functio nal fix ........................................................................................241
De fining an Active Class ..............................................................................2 4 3 Naming member functio ns ..........................................................................244
De fining a Me mbe r Function in the Class .....................................................2 4 5 Writing Me mbe r Functions Outside of the Class ............................................2 4 7 Include files .............................................................................................248
Calling a Me mbe r Function ..........................................................................2 4 9 Calling a member functio n with a po inter ....................................................250 Accessing o ther members fro m a member functio n ........................................251
Ove rloading Me mbe r Functions ....................................................................2 5 3 Session 1 9 – Maint aining Class I nt egrit y ......................................................2 5 7 Cre ating and De stroying Obje cts ...................................................................2 5 7 The co nstructo r .........................................................................................259 The destructo r ..........................................................................................264
Acce ss Control .............................................................................................2 6 6 The pro tected keywo rd ...............................................................................267 Static data members ..................................................................................270
Session 2 0 – Class Const ruct ors I I ...............................................................2 7 3 Constructors with Argume nts .......................................................................2 7 3 Constructing Class Me mbe rs .........................................................................2 7 7 Orde r of Construction ..................................................................................2 8 3 Lo cal o bjects are co nstructed in o rder ..........................................................284 Static o bjects are co nstructed o nly o nce ......................................................284 All glo bal o bjects are co nstructed befo re main( ) ............................................285 Glo bal o bjects are co nstructed in no particular o rder .....................................285 Members are co nstructed in the o rder in which they are declared ....................286 Destructo rs are invo ked in the reverse o rder of the co nstructo rs .....................287
The Copy Constructor ...................................................................................2 8 7 Shallow co pies versus deep co pies ...............................................................290 A “ fall back” co py co nstructo r ....................................................................291
xxiv
Cont ent
Exe rcise s .....................................................................................................2 9 3 Pro blems ..................................................................................................293 Hint ........................................................................................................294 My so lutio n ..............................................................................................294
Part IV–Saturday Evening Review ..................................................................296
SUNDAY ................................................................................2 9 8 Part V– Sunday Morning ..........................................................3 0 0 Session 2 1 – I nherit ance ............................................................................3 0 1 Advantage s of Inhe ritance ...........................................................................3 0 2 Class Factoring ............................................................................................3 0 3 Imple me nting Inhe ritance in C++ ................................................................3 0 3 Constructing a Subclass ...............................................................................3 0 8 The HAS_A Re lationship ..............................................................................3 1 1 Session 2 2 – Polymorphism .........................................................................3 1 5 Ove rriding Me mbe r Functions ......................................................................3 1 6 Ente r Polymorphism ....................................................................................3 1 8 Polymorphism and Obje ct-Orie nte d Programming .........................................3 2 0 How Doe s Polymorphism Work? ...................................................................3 2 2 Whe n Is a Virtual Function Not? ..................................................................3 2 4 Virtual Conside rations .................................................................................3 2 6 Session 2 3 – Abst ract Classes and Fact oring .................................................3 2 9 Factoring .....................................................................................................3 2 9 Abstract Classe s ...........................................................................................3 3 4 Declaring an abstract class .........................................................................335 Making a “co ncrete” class o ut of an abstract class .........................................337 When is a subclass abstract? .......................................................................339 Passing an abstract o bject to a functio n .......................................................341 Why are pure virtual functio ns needed? .......................................................342
Session 2 4 – Mult iple I nherit ance ...............................................................3 4 5 How Doe s Multiple Inhe ritance Work? ..........................................................3 4 6 Inhe ritance Ambiguitie s ..............................................................................3 4 8 Virtual Inhe ritance ......................................................................................3 4 9 Constructing the Obje cts of Multiple Inhe ritance ..........................................3 5 6 A Contrary Opinion ......................................................................................3 5 7 Session 2 5 – Large Programs .......................................................................3 6 1 Why Divide Programs? .................................................................................3 6 1 Se parating Class De finition from Application Program ..................................3 6 2 Dividing the pro gram .................................................................................362 The #include directive ................................................................................364 Dividing applicatio n co de ...........................................................................365 Pro ject file ...............................................................................................367 Reexamining the standard pro gram template ................................................370 Handling o utline member functio ns .............................................................371
Cont ent s
xxv
Session 2 6 – C++ Preprocessor ....................................................................3 7 3 The C++ Pre proce ssor ...................................................................................3 7 3 The # include Dire ctive .................................................................................3 7 4 The # de fine Dire ctive ..................................................................................3 7 5 Defining macro s ........................................................................................376 Co mmo n erro rs using macro s ......................................................................376
Compile Controls .........................................................................................3 7 8 The #if directive ........................................................................................378 The #ifdef directive ...................................................................................379
Part V–Sunday Mo rning Review.....................................................................384
Part VI – Sunday Af t ernoon .....................................................3 8 8 Session 2 7 – Overloading Operat ors .............................................................3 8 9 Why Do I Ne e d to Ove rload Ope rators? ..........................................................3 9 0 What Is the Re lationship Be twe e n Ope rators and Functions? ............................................................................3 9 1 How Doe s Ope rator Ove rloading Work? .........................................................3 9 1 Special co nsideratio ns ................................................................................395
A More De taile d Look ..................................................................................3 9 5 Ope rators as Me mbe r Functions ...................................................................3 9 8 Ye t Anothe r Ove rloading Irritation ...............................................................4 0 1 Whe n Should an Ope rator be a Me mbe r? ......................................................4 0 2 Cast Ope rator ..............................................................................................4 0 2 Session 2 8 – The Assignment Operat or .........................................................4 0 9 Why Is Ove rloading the Assignme nt Ope rator Critical? ..................................4 0 9 Co mpariso n with co py co nstructo r ...............................................................410
How Do I Ove rload the Assignme nt Ope rator? ...............................................4 1 1 Two mo re details abo ut the assignment o perato r ...........................................415
An Escape Hatch ..........................................................................................4 1 6 Session 2 9 – St ream I / O .............................................................................4 1 9 How Doe s Stre am I/ O Work? .........................................................................4 2 0 The fstre am Subclasse s ................................................................................4 2 1 The strstre am Subclasse s .............................................................................4 2 5 Co mpariso n of string- handling techniques ....................................................427
Manipulators ...............................................................................................4 3 1 Custom Inse rte rs .........................................................................................4 3 3 Smart Inse rte rs ...........................................................................................4 3 5 But Why the Shift Ope rators? .......................................................................4 3 8 Session 3 0 – Except ions ..............................................................................4 4 1 Conve ntional Error Handling .......................................................................4 4 1 Why Do I Ne e d a New Error Me chanism? .......................................................4 4 2
xxvi
Cont ent
How Do Exce ptions Work? ............................................................................4 4 4 Why is the exceptio n mechanism an improvement? .......................................446
Trying to Catch the De tails Thrown at You ....................................................4 4 6 What kinds of things can I throw? ...............................................................449
Chaining Catch Phrase s ...............................................................................4 5 3 Part VI–Sunday Afterno o n Review .................................................................456
Appendix A– Answers t o Part Reviews .........................................................4 6 1 Appendix B– Supplement al Problems ..........................................................4 8 3 Appendix C– What ’s On t he CD- ROM ............................................................4 9 7 I ndex .......................................................................................................5 0 1 End- User License Agreement .....................................................................5 1 4 GNU General Public License .......................................................................5 1 7 CD- ROM I nst allat ion I nst ruct ions ...............................................................5 2 6
SESSI ON
1 What I s Programming Anyway?
Session Checklist ✔ Learn the principles of pro gramming ✔ Learn to be a human co mputer pro cesso r ✔ Learn to change a tire
W
ebster’s New Wo rld Co llege Dictio nary lists several definitio ns fo r the no un “ pro gram.” The first definitio n is “a pro clamatio n, a pro spectus, o r a syllabus.” No t much help there. It wasn’t until the sixth definitio n that
I fo und so mething reaso nable: “a lo gical sequence of co ded instructio ns specifying the o peratio ns to be perfo rmed by a co mputer in so lving a pro blem o r in pro cessing data.” After thinking fo r a minute, I realized that this definitio n is a bit restrictive. First, in the phrase “a lo gical sequence of co ded instructio ns . . . ,” I do n’t know whether the instructio ns are encrypted, that is co ded, o r no t, but I know the term “ lo gical” is overly restrictive. I have written pro grams that do n’t do much of anything befo re crashing — actually, mo st of my pro grams crash befo re do ing anything. That do esn’t seem lo gical. Seco nd, “. . . so lving a pro blem o r in pro cessing data.” What abo ut the co mputer that drives the climate co ntro l system in my car?
6
Friday Evening
It do esn’t so lve any pro blem that I’m aware of. I like my air co nditio ner the way it is — push a butto n to turn it o n, push the butto n again to turn it off. The biggest pro blem with Webster’s definitio n is the phrase “. . . o peratio ns to be perfo rmed by a co mputer . . .” A pro gram do es no t need to invo lve a co mputer at all. ( Unless yo u co unt that muddy stuff between yo ur stereo headsets. In that case, yo u can claim that anything yo u do invo lves “a co mputer.” ) A pro gram can be a guide to anything po ssessing so me mo dicum of intelligence — even me. ( Assuming, of co urse, that I do n’t fail the mo dicum of intelligence limitatio n.) Let’s co nsider how we might write a pro gram to guide human behavio r.
A Human Program Writing a pro gram to guide a human is much easier than writing a pro gram to guide a machine. We have a lo t familiarity with and, therefo re, understanding of a human. The mo st impo rtant familiarity is that we share a co mmo n language. In this sectio n, let’s write a “ human pro gram” and study its parts. Let’s co nsider the pro blem of changing a flat tire.
The algorit hm Changing a tire is relatively simple. The steps go so mething like this:
1. 2. 3. 4. 5. 6.
Raise the car. Remove the lug nuts that affix the tire to the car. Remove the faulty tire. Mount the new tire. Install the lug nuts. Lower the car.
( I know that the wo rds tire and wheel are no t syno nymo us — yo u do n’t remove a tire fro m a car, yo u remove a wheel. Jumping back and fo rth between the wo rds wheel and tire gets co nfusing, however. Just assume that the wo rd tire includes the wheel o n which the tire is mo unted.) At its co re, this is the basis fo r a pro gram. I co uld use these instructio ns to repair any of the many flats that I have experienced. Mo re precisely, this is an algo rithm. An algo rithm is a descriptio n of the steps to be perfo rmed, usually at a high level of abstractio n. An algo rithm is to a pro gram as a descriptio n of the principles of TV is to a TV circuit bo ard.
Session 1 — What I s Programming Anyway?
7
The processor To make anything happen, an algo rithm must be co mbined with so me type of so meo ne to man ( uh, I mean pe rso n ) the jack, remove the lug nuts, and lift the tire into place. The o bjects mentio ned — car, tire, and nuts — are powerless to move o n their own. Let’s assume that o ur pro cesso r understands o nly a few wo rds of English and understands them very literally. Let’s assume that o ur pro cesso r understands these no uns, which are co mmo n in the tire- changing industry:
car tire nut jack wrench ( The latter two o bjects were no t mentio ned in the tire-changing algo rithm, but were implied in phrases such as “ replace tire.” That’s the pro blem with algo rithms — so much go es unsaid.) Let’s further assume that o ur pro cesso r understands these verbs:
grab move release turn Finally, o ur pro cesso r perso n needs to be capable of co unting and making simple decisio ns. This is all that o ur tire- changing pro cesso r perso n understands. Any o ther co mmand generates a blank stare.
The program Given the vo cabulary of o ur pro cesso r, it is clear that the pro cesso r canno t perfo rm an o peratio n such as “ Remove the lug nuts fro m the car.” The wo rd “ remove” is no t in the pro cesso r’s vo cabulary. Further, no mentio n is made of the wrench with which to remove the lug nuts. ( These are the types of things that go unsaid in no rmal speech.)
Part I – Friday Evening Session 1
“ do ”er o r pro cesso r. Our tire repair pro gram assumes, fo r example, that there is
8
Friday Evening
The fo llowing steps define the phrase “ remove lug nuts” using terms that the pro cesso r understands:
1. 2. 3. 4. 5.
Grab wrench Move wrench to lug nut Turn wrench counterclockwise five times Remove wrench from lug nut Release wrench
Let’s go over each step of this pro gram in detail. The pro cesso r begins with Step 1 and co ntinues thro ugh each step in turn until reaching Step 5. In pro gramming parlance, we say that the pro gram flows fro m Step 1 thro ugh Step 5 even tho ugh the pro gram do esn’t go anywhere — it’s the pro cesso r perso n. In Step 1, the pro cesso r perso n retrieves the wrench. It is po ssible that the pro cesso r already has the wrench in hand; however, we canno t assume that. Step 2 places the wrench o n the lug nut. Step 3 lo o sens the lug nut. Finally, Steps 4 and 5 return the wrench. One pro blem with this algo rithm jumps o ut immediately. How do we know that turning the wrench five times is sufficient to remove the lug nut? We co uld just make the number of turns large eno ugh that it wo uld remove the lug nut fro m any wheel. No t o nly is this so lutio n wasteful, it may no t even wo rk. What will o ur pro cesso r do if the lug nut falls off and she is asked to turn the wrench again? Will the pro cesso r beco me co nfused and sto p? The fo llowing updated pro gram utilizes o ur pro cesso r’s limited decisio n- making capabilities to remove a lug nut pro perly:
1. 2. 3. 4. 5. 6. 7. 8.
Grab wrench Move wrench to lug nut While lug nut attached { Turn wrench counterclockwise } Remove wrench from lug nut Release wrench
Here the pro gram flows fro m Step 1 thro ugh Step 2 just as befo re. Step 3 is so mething co mpletely different. The pro cesso r perso n is asked to repeat all of the steps co ntained in the parentheses immediately fo llowing Step 3 until so me co nditio n is satisfied. In this case, to co ntinue turning until the lug nut co mes off. After the lug nut is no lo nger attached, the pro cesso r perso n co ntinues executing at Step 7. Steps 3 thro ugh 6 are known as a pro cessing lo o p because the pro cesso r lo o ps in a circle.
Session 1 — What I s Programming Anyway?
9
This so lutio n is far superio r because it makes no assumptio ns abo ut the number of turns required to remove any particular lug nut. Furthermo re, this pro gram is no t wasteful by requiring mo re turns than necessary, and it do es no t ask the pro cesso r As nice as it is, this pro gram still has a pro blem: it o nly removes a single lug nut. Mo st medium- size cars have five lug nuts o n each wheel. We co uld repeat Step 2 thro ugh Step 7 five times, o nce fo r each lug nut. Removing five lug nuts do esn’t wo rk very well either. Co mpact cars typically have fo ur lug nuts and large- size cars and mo st small trucks have six lug nuts. The fo llowing pro gram expands the previo us so lutio n to all of the lug nuts o n a wheel, irrespective of the number of nuts ho lding the wheel in place.
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
Grab wrench For each lug nut on the wheel { Move wrench to lug nut While lug nut attached { Turn wrench counterclockwise } Remove wrench from lug nut } Release wrench
This pro gram begins just as befo re with grabbing the wrench. Beginning with Step 2, the pro gram lo o ps thro ugh Step 10 o nce fo r each lug nut o n wheel. Step 9 moves the wrench fro m o ne lug nut to the next befo re starting over at Step 2. No tice how Steps 5 thro ugh Step 8 are still repeated until the given lug nut co mes off the wheel. Steps 5 thro ugh 8 are known as an inner lo o p, while Steps 2 thro ugh 10 are the o uter lo o p. The co mplete pro gram co nsists of the co mbinatio n of similar so lutio ns fo r each of the six steps in the o riginal algo rithm.
Comput er processors A co mputer pro cesso r wo rks much like o ur human pro cesso r. A co mputer pro cesso r fo llows literally a string of co mmands built fro m a limited vo cabulary. Removing a wheel fro m a car seems like a simple task, and yet o ur pro cesso r perso n requires 11 co mmands to remove just a single wheel. How many instructio ns are required to move each of the tho usands of pixels that make up a window o n the co mputer screen when the user moves the mo use?
Part I – Friday Evening Session 1
to turn a nut that is no lo nger there.
10
Friday Evening
Unlike a human pro cesso r, a silico n pro cesso r is extremely fast. A Pentium II co mputer pro cesso r can execute ro ughly 100 millio n steps in a seco nd. It still requires millio ns of co mmands to move the window aro und, but because the co mputer pro cesso r can execute them so quickly, the window appears to move smo o thly acro ss the screen.
REVI EW This chapter intro duced the principles of pro gramming by describing how yo u might write a pro gram to instruct a very stupid but extremely o bedient mechanic in the intricacies of tire replacement.
쐌 Co mputers do exactly what yo u tell them — no less, and certainly no mo re. 쐌 Co mputer pro cesso rs have a limited but well- defined vo cabulary. 쐌 Co mputer pro cesso rs are smart eno ugh to make simple decisio ns.
QUI Z YOURSELF 1.
What are so me no uns that a “ human pro cesso r” that washes dishes might need?
2.
What are so me verbs?
3.
What kind of decisio ns wo uld a pro cesso r need to make?
SESSI ON
2 Creat ing Your First C++ Program in Visual C++
Session Checklist ✔ Creating yo ur first C++ pro gram using Visual C++ ✔ Building yo ur C++ so urce statements into an executable pro gram ✔ Executing yo ur pro gram ✔ Getting help when pro gramming
hapter 1 lo o ked at how yo u might pro gram a human. This chapter and the
C
next describe how to pro gram a co mputer in C++. This chapter centers o n writing pro grams in Visual C++, while the next co ncentrates o n the public
do main GNU C++, which is co ntained o n the enclo sed C++ We e ke nd Crash Co urse CD- ROM.
Not e
Don’t get t oo worried about t he designat ion Visual C++ or GNU C++. Bot h compilers represent t rue implement at ions of t he C++ st andard language. Eit her compiler can compile any of t he programs in t his book.
The pro gram we are abo ut to create co nverts a temperature entered by the user fro m degrees Celsius to degrees Fahrenheit.
12
Friday Evening
I nst alling Visual C++ Yo u need to install the Visual C++ package o n yo ur co mputer befo re yo u can write a Visual C++ pro gram. The Visual C++ package is used to write yo ur C++ pro grams and to co nvert them to .EXE pro grams that the co mputer can understand.
Not e
Visual C++ does not come wit h t his book. You need t o purchase Visual C++ separat ely, eit her as a part of t he ent ire Visual St udio package or on it s own. The very capable GNU C++ compiler is included.
Co nsult Appendix A if yo u need help installing Visual C++.
Creat ing Your First Program A C++ pro gram begins life as a text file co ntaining the C++ instructio ns. I will lead yo u step- by- step thro ugh this first pro gram. Start the Visual C++ package. Fo r Visual Studio 6.0, click Start fo llowed by Pro grams and the Micro soft Visual Studio 6.0 menu o ptio ns. Fro m there, select Micro soft Visual C++ 6.0. Visual C++ sho uld start with two empty windows labeled Output and Wo rkSpace. If o ther windows appear o r Output o r Wo rkSpace is no t empty, then so meo ne has been using yo ur Visual C++ o n yo ur machine. To clo se o ut whatever they were do ing select File fo llowed by Clo se Wo rkspace. Create an empty text file by clicking o n the small New Text File ico n at the left of the menu bar as shown in Figure 2- 1.
Tip
Don’t worry t oo much about indent at ion — it isn’t crit ical whet her a given line is indent ed t wo spaces or t hree spaces; case, however, is crit ical. C++ does not consider “Cheat ” and “cheat ” t o be t he same word. ( You can cheat and copy t he Conversion.cpp f ile cont ained on t he accompanying CD- ROM.)
CD-ROM
Session 2 — Creat ing Your First C++ Program in Visual C++
13
Part I – Friday Evening Session 2
Figure 2-1 Yo u be gin writing yo ur C++ pro gram by using the Ne w Te xt File butto n to cre ate an e mpty te xt file.
Enter the fo llowing pro gram exactly as written below.
// // Program to convert temperature from Celsius degree // units into Fahrenheit degree units: // Fahrenheit = Celsius * (212 - 32)/100 + 32 // #include #include int main(int nNumberofArgs, char* pszArgs[]) { // enter the temperature in Celsius int nCelsius; cout nCelsius; // calculate conversion factor for Celsius // to Fahrenheit int nFactor; nFactor = 212 - 32; // use conversion factor to convert Celsius // into Fahrenheit values
14
Friday Evening
int nFahrenheit; nFahrenheit = nFactor * nCelsius/100 + 32; // output the results cout