Teach Yourself C++ in 21 Days

Jesse Liberty

This book is dedicated to the living memory of David Levine.

Copyright © 1994 by Sams Publishing

FIRST EDITION

All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanic al, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Neither is any liability as sued for damages resulting from the use of the information contained herein. For information, address Sams Publishing, 201 W. 103rd St., Indianapolis, IN 46290.

International Standard Book Number: 0-672-30541-0

Library of Congress Catalog Card Number: 94-66277

97    96    95                   4    3    2

Interpretation of the printing code: the rightmost double-digit number is the year of the book's printing; the rightmost single-digit, the number of the book's printing. For example, a printing code of 94-1 shows that the first printing of the book occurred in 1994.

Composed in AGaramond and MCPdigital by Macmillan Computer Publishing

Printed in the United States of America

Trademarks

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

Publisher
Richard K. Swadley

Associate Publisher
Jordan Gold

Acquisitions Manager
Stacy Hiquet

Managing Editor
Cindy Morrow

Acquisitions Editor
Christopher Denny

Development Editor
Brad Jones

Production Editor
Matthew Usher

Editors
Cheri Clark
Gregory A. Horman
Sean Medlock
Tonya R. Simpson

Editorial Coordinator
Bill Whitmer

Editorial Assistants
Carol Ackerman
Sharon Cox
Lynette Quinn

Technical Reviewer
Scott Parker

Marketing Manager
Gregg Bushyeager

Cover Designer
Dan Armstrong

Book Designer
Michele Laseau
Alyssa Yesh

Director of Production and Manufacturing
Jeff Valler

Imprint Manager
Juli Cook

Manufacturing Coordinator
Paul Gilchrist

Production Analysts
Dennis Clay Hager
Mary Beth Wakefield

Graphics Image Specialists
Tim Montgomery
Dennis Sheehan
Susan VandeWalle

Production
Georgiana Briggs
Michael Brumitt
Mona Brown
Elaine Brush
Cheryl Cameron
Mary Ann Cosby
Elaine Crabtree
Jamie Milazzo
Brian-Kent Proffitt
Caroline Roop
Kim Scott
Marc Shecter
SA Springer
Suzanne Tully

Indexer
Jeanne Clark

Overview

    Week 1 at a Glance                                  1

    Day     1   Getting Started                         3
            2   The Parts of a Program                  19
            3   Variables and Constants                 33
            4   Expressions and Statements              55
            5   Functions                               85
            6   Basic Classes                           123
            7   More Program Flow                       157

    Week 1 in Review                                    189

    Week 2 at a Glance                                  195

    Day     8   Pointers                                197
            9   References                              227
            10  Advanced Functions                      261
            11  Arrays                                  299
            12  Inheritance                             337
            13  Polymorphism                            371
            14  Special Classes and Functions           407

    Week 2 in Review                                    435

    Week 3 at a Glance                                  445

    Day     15  Advanced Inheritance                    447
            16  Streams                                 485
            17  The Preprocessor                        525
            18  Object-Oriented Analysis and Design     553
            19  Templates                               585
            20  Exceptions and Error Handling           615
            21  What's Next                             643

    Week 3 in Review                                    673

    Appendixes

            A   Operator Precedence                     685
            B   C++ Keywords                            687
            C   Binary and Hexadecimal                  689
            D   Answers                                 699

    Index                                               789

Acknowledgments

I would like to acknowledge the many people who contributed to this book, both directly and indirectly. First and foremost, Stacey and Robin Liberty, whose support, encouragement and patience made it possible. Also, Mike Kraley, Ed Belove, and Patrick Johnson, who create an intellectual atmosphere at the Interchange Online Network, which makes it a gas to come to work every day, and the many, many developers at Ziff from whom I learned whatever it is I know about C++.

I must particularly acknowledge those who taught me how to program, Skip Gilbrech and David McCune, and those who taught me C++, including Steve Rogers and especially Steven Zagieboylo.

Others who contributed directly or indirectly to this book include: Scott Boag, David Bogartz, Gene Broadway, Drew and Al Carlson, Frank Childs, Jim Culbert, Fran Daniels, Thomas Dobbing, James Efstratiou, June Goldstein, Basha Goldstein-Weiss, Michael Griffin, David Heath, Eric Helliwell, Gisele and Ed Herlihy, Mushtaq Khalique, Matt Kingman, Steve Leland, Sa ngam Pant, Mike Rothman, Michael Smith, Frank Tino, Seth Weiss, Donovan White, Mark Woodbury and Alan Zeitchek. Special thanks go to Wayne Wylupski and Steven Zagieboylo.

Programming is as much a business and creative experience as it is a technical one, and I must therefore acknowledge Tom Hottenstein, Jay Leve, David Rollert, David Shnaider and Robert Spielvogel. I also want to thank the many people at Sams Publishing who worked so hard to create this book, including Christopher Denny, Bradley Jones, and Matthew Usher. If any of what I've written is especially clear, it is thanks to the editors.

Finally, I'd like to thank Mrs. Kalish, who taught my sixth-grade class how to do binary arithmetic in 1965, when neither she nor we knew why.

About the Author

Jesse Liberty

Jesse Liberty has been programming computers professionally for over ten years. He is a Software Architect at AT&T Interchange Online Network, where he was a founding member of the Software Development Team. He is also president of The Liberty Group, Inc., and a former vice president of Citibank's Development Division. Jesse lives with his wife, Stacey, and his daughter, Robin, in the suburbs of Cambridge, Massachusetts. He can be reached via the Internet at jliberty@zdi.ziff.com.

About This Book

This book is designed to help you teach yourself how to program with C++. In just 21 days, you'll learn about such fundamentals as the managing I/O, loops and arrays, object-oriented programming, templates, and creating C++ applicationsall in well-structured and easy-to-follow lessons. Lessons provide sample listingscomplete with sample output and an analysis of the codeto illustrate the topics of the day. Syntax examples are clearly marked for handy reference.

To help you become more proficient, each lesson ends with a set of common questions and answers, exercises, and a quiz. You can check your progress by examining the quiz and exercise answers provided in the book's appendix.

Who Should Read This Book

You don't need any previous experience in programming to learn C++ with this book. This book starts you from the beginning and teaches you both the language and the concepts involved with programming C++. You'll find the numerous examples of syntax and detailed analysis of code an excellent guide as you begin your journey into this rewarding environment. Whether you are just beginning or already have some experience programming, you will find that this book's clear organization makes learning C++ fast and easy.

Conventions

Note: These boxes highlight information that can make your C++ programming more efficient and effective.

Warning: These focus your attention on problems or side effects that can occur in specific situations.

New Term: These boxes provide clear definitions of essential terms.

DO use the "Do/Don't" boxes to find a quick summary of a fundamental principle in a lesson.

DON'T overlook the useful information offered in these boxes.

This book uses various typefaces to help you distinguish C++ code from regular English. Actual C++ code is typeset in a special monospace font. Placeholders words or characters temporarily used to represent the real words or characters you would type in code are typeset in italic monospace New or important terms are typeset in italic.

In the listings in this book, each real code line is numbered. If you see an unnumbered line in a listing, you'll know that the unnumbered line is really a continuation of the preceding numbered code line (some code lines are too long for the width of the book). In this case, you should t ype the two lines as one; do not divide them.

Contents

Week 1 at a Glance                                                          1
Day 1     Getting Started                                                   3

    2     The Parts of a C++ Program                                        19

     3     Variables and Constants                                          33
     4     Expressions and Statements                                       55
     5     Functions                                                        85
     6     Basic Classes                                                   123
     7     More Program Flow                                               157
Week 1 in Review                                                           189
Week 2 at a Glance                                                         195
Day     8     Pointers                                                     197
     9     References                                                      227
     10     Advanced Functions                                             261
     11     Arrays                                                         299
     12     Inheritance                                                    337
     13     Polymorphism                                                   371
     14     Special Classes and Functions                                  407
Week 2 in Review                                                           435
Week 3 at a Glance                                                         445
Day     15     Advanced Inheritance                                        447
     16     Streams                                                        485
     17     The Preprocessor                                               525
     18     Object-Oriented Analysis and Design                            553
     19     Templates                                                      585
     20     Exceptions and Error Handling                                  615
     21     What's Next                                                    643
Week 3 in Review                                                           673
Appendixes
A    Operator Precedence                                                   685
           Introduction                                                    686
B    C++ Keywords                                                          687
           Introduction                                                    688
C    Binary and Hexadecimal                                                689
           Introduction                                                    690
     Other Bases                                                           690
     Around the Bases                                                      691
           Binary                                                          692
           Why Base Two?                                                   693
           Bits, Bytes, and Nybbles                                        693
           What's a K?                                                     694
           Binary Numbers                                                  694
     Hexadecimal                                                           694
D    Answers                                                               699
     Index                                                                 789