0% found this document useful (0 votes)
114 views

Teach Yourself C++

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
114 views

Teach Yourself C++

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 609
I] TATA McGRAW-HILL EDITION ational eis «) FOR SALE IN INDIA ONLY ere ANI en ae The Most Successful and Proven Method for Learning C++ e Master Standard C++— Including its new features! « Essential for C Programmers moving on to C++ Build your skills with hundreds of examples and exercises ¢ » Covers the Standard Template Library (STL) » Best-Selling C/C++ Author with More Than 1.5 Million Books Sold == Tata McGraw-Hill Teach Yourself C++, Third Edition Copyright © 1998 by The McGraw-Hill Companies , Inc., Alll rights reserved. No part of this publication may be reproduced or distributed in any form or by any means, or stored in a data base or retrieval system, without the prior written permission of the publisher, with the exception that the program listings may be entered, stored, and executed in a computer ‘system, but they may not be reproduced for publication ‘Tata McGraw-Hill Edition 1998 ‘Twentieth reprint 2008 RZZLCDRXRBYDY Reprinted in India by arrangement with The McGraw-Hill Companies, Inc., New York For Sale in India Only ISBN-13: 978-0-07-043870-5 ISBN-10: 0-07-043870-X, Published by Tata McGraw-Hill Publishing Company Limited, 7 West Patel Nagar, New Delhi 110 008, and printed at Krishna Offset, Dethi 110 032 Contents at a Glance 1 An Overview of C++ 1 2 Introducing Classes 41 3 A Closer Look at Classes 87 4 Arrays, Pointers, and References 7 5. Function Overloading 159 6 Introducing Operator Overloading 195 7 Inheritance 231 8 Introducing the C++ I /O System 269 9 Advanced C++ 1/0 20 10_Virtual unctions —____345 1 12 13 14 A B Templates and Exception Handling 371 Run-Time Type Identification and the Casting Operators 407 Namespaces, Conversion Functions, and Miscellaneous Topics 435 Introducing the Standard Template Library 473 A Few More Differences Between C and C++ S31 Answers 533 Index 239 Avout the Autho Herbert Schildt is the world’s leading programming author. He is an-authority on the C and C++ languages, a master Windows programmer, and an expert on Java. His programming books have sold nearly two million copies worldwide and have been translated into all major foreign languages. He is the author of numerous best-sellers, including C: The Complete Referénce, C++: The Complete Reference, C++ from the Ground Up, Expert C++, MFC Programming from the Ground Up, Windows 95 Programming in C and C++, Windows NT 4 Programming from the Ground Up, and many others. Schildt is the president of Universal Computing Laboratories, a software consulting firm in Mahomet, Illinois. He is also a member of both the ANSI C and C++ standardization committees. He holds a master’s degree in computer science from the University of Ilinois Acknowledgments, _ xiii Introduction, _xv For Further Study, _xix 1 An Overview of C++... 1 1.1__WHAT IS ORIECT-ORIENTED PROGRAMMING?, 1.2__ TWO VERSIONS OF C++, 7 1.3__C++ CONSOLE /O, 13 C++ COMMENTS, 1.5 CLASSES: A FIRST LOOK, 21 1.6 SOME DIFFERENCES BETWEEN C AND C++, 28 1.7 INTRODUCING FUNCTION OVERLOADING, 33 1.8 C++ KEYWORDS, 39 SKILLS CHECK, 39 2 Introducing Classes . . . 41 21 CONSTRUCTOR AND DESTRUCTOR FUNCTIONS, 43 2.2 CONSTRUCTORS THAT TAKE PARAMETERS, 52 2.3 INTRODUCING INHERITANCE, 59 24 OBJECT POINTERS, 66 2.5 CLASSES, STRUCTURES, AND UNIONS ARE. RELATED, 68 2.6 IN-LINE FUNCTIONS, 75 27 AUTOMATICIN-LINING, 86 SKILLS CHECK, 83 3 ACloser Look at Classes . . . 87 3.1 ASSIGNING OBJECTS, 89 3.2 PASSING OBJECTS TO FUNCTIONS, 96 3.3 RETURNING OBJECTS FROM FUNCTIONS, 102 3.4 AN INTRODUCTION TO FRIEND FUNCTIONS, 107 SKILLS CHECK, 114 Arrays, Pointers, and References . . . 117 41 ARRAYS OF OBJECTS, 119 4.2 USING POINTERSTO OBJECTS, 124 43 THE this POINTER, 126 4.4 USING new AND delete, 130 4.5 MORE ABOUT new ANDdelete, 134 REFERENCES, 47 PASSING REFERENCES TO OBJECTS, 146 48 RETURNING REFERENCES, 149 4.9 INDEPENDENT REFERENCES AND RESTRICTIONS, 154 SKILLS CHECK, 156 Function Overloading . . . 159 5.1 OVERLOADING CONSTRUCTOR FUNCTIONS, 161 5.2 CREATING AND USING A COPY CONSTRUCTOR, 167 5.3 THE overload ANACHRONISM, 177 5.4 USING DEFAULT ARGUMENTS, 177 5,5 OVERLOADING AND AMBIGUITY, 185 5.6 FINDING THE ADDRESS OF AN OVERLOADED FUNCTION, 189 SKILLS CHECK, 191 Introducing Operator Overloading . . . 195 6.1 ‘THE BASICS OF OPERATOR OVERLOADING, 197 6.2 OVERLOADING BINARY OPERATORS, 199 6.3 OVERLOADING THE RELATIONAL AND LOGICAL OPERATORS, 207 6.4 OVERLOADING A UNARY OPERATOR, 209 65 USING FRIEND OPERATOR FUNCTIONS, 213 6.6 ACLOSER LOOK AT THE ASSIGNMENT. OPERATOR, 218 67 OVERLOADING THE | ] SUBSCRIPT OPERATOR, 222 SKILLS CHECK, 227 7 Inheritance . . . 231 7.1 BASE CLASS ACCESS CONTROL, 234 7.2 USING PROTECTED MEMBERS, 240 7.3. CONSTRUCTORS, DESTRUCTORS, AND INHERITANCE, 244 7.4 MULTIPLE INHERITANCE, 252 7.5 VIRTUAL BASE CLASSES, 259 SKILLS CHECK, 262 8 Introducing the C++1/O System . . . 269 8.1 SOMEC++ I/O BASICS, 273 8.2 FORMATTED I/O, 275 8.3 USING width(), precision( ), AND fill(), 283 84 USING I/O MANIPULATORS, 287 8.5 | CREATING YOUR OWN INSERTERS, 292 8.6 CREATING EXTRACTORS, 299 SKILLS CHECK, 303 9 Advanced C++/O . . . 307 9.1 ___ CREATING YOUR OWN MANIPULATORS, 309 9.2 FILEI/OBASICS, 213 9.3. UNFORMATTED, BINARY I/O, 320 9.4 MORE UNFORMATTED I/O FUNCTIONS, 327 9.5 RANDOM ACCESS, 331 9.6 CHECKING THE I/O STATUS, 334 9.7 CUSTOMIZED I/O AND FILES, 338 SKILLS CHECK, 341 ‘10 Virtual Functions... 345 10.1 __ POINTERS TO DERIVED CLASSES, 347, 10.2. INTRODUCTION TO VIRTUAL FUNCTIONS, 349 10.3. MORE ABOUT VIRTUAL FUNCTIONS, 357 10.4 APPLYING POLYMORPHISM, 362 SKILLS CHECK, 368 11 Templates and Exception Handling . . . 371 11.1 GENERIC FUNCTIONS, 373 11.2 GENERIC CLASSES, 380 11.3 EXCEPTIONHANDLING 385 11.4 MORE ABOUT EXCEPTION HANDLING, 394 12 13 4 411.5 HANDLING EXCEPTIONS THROWN BY new, 401 SKILLS CHECK; 404 Run-Time Type Identification and the Casting Operators . . . 407 12.1 UNDERSTANDING RUN-TIME TYPE, IDENTIFICATION (RTT), 409 12.2 USING dynamic_cast, 420 12.3 _ USING const_cast, reinterpret_cast, AND static_cast, 429 SKILLS CHECK, 432 Namespaces, Conversion Functions, and Miscellaneous Topics . . . 435 13.1 NAMESPACES, 437 13.2 CREATING A CONVERSION. FUNCTION, 446 13.3. STATICCLASS MEMBERS, 449 13.4 const MEMBER FUNCTIONS AND mutable, 455 13.5 A FINAL LOOK AT CONSTRUCTORS, 459 136 USING LINKAGE SPECIFIERS AND THE asm KEYWORD, 463 13.7. ARRAY-BASEDI/O, 466 SKILLS CHECK, 471 Introducing the Standard Template Library . . . 473 14.1 AN OVERVIEW OF THE STANDARD TEMPLATE LIBRARY, 476 14.2 THECONTAINER CLASSES, 479 14.3' VECTORS, 480 14.4 LISTS, 490 14.5 MAPS, 502 14.6 ALGORITHMS, 509 14.7 THE string CLASS, 519 SKILLS CHECK, 529 A Few More Differences Between C andC++ . . . 531 Answers . . . 533 1.3 EXERCISES, 534 1.4 EXERCISES, 535 15 EXERCISES, 535 1.6 EXERCISES, 538 1.7___ EXERCISES, 538 MASTERY SKILLS CHECK: Chapter 1, 541 REVIEW SKILLS CHECK: Chapter 2, 543 21 EXERCISES, 545 2.2 EXERCISES, 548 2.3. EXERCISE, 551 25 EXERCISES, 553 2.6 EXERCISES, 555 27° EXERCISES, 556 MASTERY SKILLS CHECK: Chapter 2, 558 CUMULATIVE SKILLS CHECK: Chapter 2, 560 REVIEW SKILLS CHECK: Chapter 3, 562 3.1 EXERCISES, 563 3.2__ EXERCISES, 565 3.3 EXERCISES, 567 34 EXERCISE, 567 MASTERY SKILLS CHECK: Chapter 3, 569 CUMULATIVE SKILLS CHECK: Chapter 3, 571 REVIEW SKILLS GHECK: Chapter 4, 576 41 EXERCISES, 578 4.2 EXERCISES, 580 4.3 EXERCISE, 582 44 EXERCISES, 583 45 EXERCISES, 584 4.6 EXERCISES, 585 47 — EXERCISE, 585 48 EXERCISES, 587 MASTERY SKILLS CHECK: CHAPTER 4, 589 CUMULATIVE SKILLS CHECK: Chapter 4, 592 REVIEW SKILLS CHECK: Chapter 5, 593 5.1 EXERCISES, 595 EXERCISES, 598 54 EXERCISES, 600 5.6 EXERCISE, 601 MASTERY SKILLS CHECK: Chapter 5, 602 CUMULATIVE SKILLS CHECK: Chapter 5,605 REVIEW SKILLS CHECK: Chapter 6, 607 EXERCISES, 608 6.3 EXERCISE, 609 6.4 EXERCISES, 610 6.5___ EXERCISES, 612 EXERCISE,_616 6.7 EXERCISES, 618 MASTERY SKILLS CHECK: Chapter 6,621 CUMULATIVE SKILLS CHECK: Chapter 6, 629 REVIEW SKILLS CHECK: Chapter 7, 631 7.1 EXERCISES, 637 7.2 EXERCISES, 637 7.3 EXERCISES, 638 EXERCISES, 640 EXERCISES, 641 MASTERY SKILLS CHECK: Chapter 7,641 CUMULATIVE SKILLS CHECK: Chapter 7, 643 REVIEW SKILLS CHECK: Chapter 8, 644 8.2 EXERCISES, 646 8.3__ EXERCISES, 647 84 EXERCISES, 649 8.5 EXERCISES, 650 8.6 EXERCISES, 652 MASTERY SKILLS CHECK: Chapter 8, 655 CUMULATIVE SKILLS CHECK: Chapter 8 659 REVIEW SKILLS CHECK: Chapter 9, 662 9.1 EXERCISES, 664 9.2 EXERCISES, 686 9.3 EXERCISES, 668 EXERCISES, 671 9.5 EXERCISES, 673 9.6 EXERCISE, 674 MASTERY SKILLS CHECK: Chapter 9, 677 CUMULATIVE SKILLS CHECK: Chapter 9, 682 REVIEW SKILLS CHECK: Chapter 10, 684 10,2 EXERCISES, 687 10.3 EXERCISES, 688 10.4 EXERCISE, 689 MASTERY SKILLS CHECK: Chapter 10, 694 CUMULATIVE SKILLS CHECK: Chapter 10, 69% REVIEW SKILLS CHECK: Chapter 11, 698 111_EXERCISES, 698 11.2 EXERCISES, 699 113 EXERCISES, 701 11.4 EXERCISES, 702 11.5 EXERCISES, 702 MASTERY SKILLS CHECK: Chapter 11,703 REVIEW SKILLS CHECK: Chapter 12, 710 12.1 EXERCISES, 712 12.2__ EXERCISES, 712 12.3 EXERCISES, 713 MASTERY SKILLS CHECK: Chapter 12, 714 CUMULATIVE SKILLS CHECK: Chapter 12, 715 REVIEW SKILLS CHECK: Chapter 13, 717 13.1 EXERCISES, 717 13.2. EXERCISES, 719 13.3. EXERCISES, 720 EXERCISES, 723 13.5 EXERCISES, 724 13.7 EXERCISES, 724 MASTERY SKILLS CHECK: Chapter 13, 726 CUMULATIVE SKILLS CHECK: Chapter 13, 727 REVIEW SKILLS CHECK: Chapter 14, 727 14.1 EXERCISES, 728 143 EXERCISES, 728 (14.4 EXERCISES, 729 14.5 EXERCISES. 732 146 EXERCISES, 732 147 EXERCISES, 735 MASTERY SKILLS CHECK: Chapter 14, 737 Index_______739 Se Acknowledgments I wish to say special thanks to Bjame Stroustrup Steve Clamage P. J. Plauger Al Stevens for sharing their knowledge, advice, and expertise during the preparation of this book. It was much appreciated. Introduction If you already know C and are moving up to C+4, this book is for you. C++ is the C programmer's answer to Object-Oriented Programming (OOP). Built upon the solid foundation of C, C++ adds support for OOP (and many other new features) without sacrificing any of C's power, elegance, or flexibility. C++ has become the universal language of programmers around the world and is the language that will create the next generation of high-performance software. It is the single most important language that a professional programmer must know. C++ was invented in 1979 by Bjarne Stroustrup at Bell Laboratories in Murray Hill, New Jersey. Initially it was called "C with classes." The name was changed to C++ in 1983. Since then, C++ has undergone three major revisions, the first in 1985 and the second in 1990. The third occurred during the C++ standardization process. Several years ago, work began ona standard for C++. Towards that end, a joint ANSI (American National Standards Institute) and ISO (International Standards Organization) standardization committee was formed. The first draft of the proposed standard was created on January 25, 1994. In that draft, the ANSI/ISO C++ committee (of which | am a member) kept the features first defined by Stroustrup and added some new ones as well. But, in general, this initial draft reflected the state of C++ at the time. Soon after the completion of the first draft of the standard an event occurred that caused the standard to be greatly expanded: the creation of the Standard Template Library (STL) by Alexander Stepanov. As you will learn, the STL is a set of generic routines that you can use to manipulate data. It is both powerful and elegant. But it is also quite large. Subsequent to the first dratt, the committee voted to include the STL in the specification for C++. The addition of the STL expanded the scope of C++ well beyond its onginal definition. While important, the inclusion of the STL, among other things, slowed the standardization of C++. It is fair to say that the standardization of C++ took far longer than any one had expected when it began. However, it is now nearly complete. The final draft has been prepared and passed out of evi TEACH vouRsELF c++ committee. It now awaits only formal approval. In a practical sense, a standard for C++ is now a reality. Compilers already are beginning to support all of the new features. ‘The material in this book describes Standard C++. This is the version of C++ created by the ANSI/1SO standardization committee and it is the one that is currently accepted by all major compilers. Therefore, using this book, you can be confident that what you learn today will also apply tomorrow. What Is Hew in the Third Edition This is the third edition of Teach Yourself C++. It includes all of the material contained in the first two editions and adds two new chapters and many new topics. The first new chapter covers Run-Time Type ID (RTTI) and the new casting operators. The second covers the Standard Template Library (STL). Both of these topics are major features added to the C++ language since the previous edition was published. New topics include namespaces, the new-style headers, and coverage of the modern-style I/O system. In all, the third edition of Teach Yourself C++ is substantially larger than its preceding two editions. #f You're Using Windows If your computer uses Windows and your goal is to write Windows- based programs, then you have chosen the right language to learn. C++ is completely at home with Windows programming. However, none of the programs in this book are Windows programs. Instead, they are console-based programs. The reason for this is easy to understand: Windows programs are, by their nature, large and complex. The overhead required to create even a minimal Windows skeletal program is 50 to 70 lines of code. To write Windows programs, that demonstrate the features of C++ would require hundreds of lines of code each. Put simply, Windows is not an appropriate environment in which to learn programming, However, you can still use a Windows- based compiler to compile the programs in this book because the compiler will automatically create a console session in which to execute your program. Once you have mastered C++, you will be able to apply your knowledge to Windows programming. In fact, Windows programming mTropucTION will using C++ allows the use of class libraries such as MFC, that can greatly simplify the development of a Windows program. How This Book Is Organized This book is unique because it teaches you the C++ language by applying mastery learning. It presents one idea at a time, followed by numerous examples and exercises to help you master each topic. This approach ensures that you fully understand each topic before moving on. ‘The material is presented sequentially, Therefore, be sure to work carefully through the chapters. Each one assumes that you know the material presented in all preceding chapters. At the start of every chapter (except Chapter 1) there is a Review Skills Check that tests your knowledge of the preceding chapter. At the end of each chapter you will find a Mastery Skills Check that checks your knowledge of the material present in the chapter. Finally, each chapter concludes with a Cumulative Skills Check which tests how well you are integrating new material with that presented in earlier chapters. The answers to the book's many exercises are found in Appendix B ‘This book assumes that you are already an accomplished C programmer. Put simply, you can’t learn to program in C++ until you can program in C. If you can't program in C, take some time to learn it before attempting to use this book. A good way to learn C is to read my book Teach Yourself C, Third Edition (Osborne/McGraw-Hill, Berkeley CA, 1997), It uses the same presentation style as this book Don’t Forget: Code on the Web Remember, the source code for all of the programs in this book is available free-of-charge on the Web at http://www osborne.com. Downloading this code prevents you from having to type in the examples. = For Further Study Teach Yourself C++, Third Edition is your gateway into the "Herb Schildt’ scries of programming books. Here is a partial list of Schildt’s other books. Ifyou want to learn more about C+, then you will find these books especially helpful. C++: The Complete Reference C++ From the Ground Up Expert C++ If you want to learn more about C, the foundation of C++, we recommend Teach Yourself C C: The Complete Reference The Annotated ANS! C Standard If you will be developing programs for the Web, you will want to read Java: The Complete Reference co-authored by Herbert Schildt and Patrick Naughton. Finally, if you want to program for Windows, we recommend Schildt’s Windows 95 Programming in C and C++ Schildt’s Advanced Windows 95 Programming in C and C++ Windows NT 4 From the Ground Up MFC Programming From the Ground Up When you need solid answers, fast, turn to Herbert Schildt, the recognized authority on programming. An Overview of C++ chapter objectives 11.1 What is object-oriented programming? 1.2 Two versions of C++ 1.3 C++ console VO 1.4 C++ comments 1.5 Classes: A first look 1.6 Some differences between C and C++ 1.7 Introducing function overloading 1.8 C++ keywords << 2 TEACHYoURSELF oe ++ is an enhanced version of the C language. C++ includes everything that is part of C and adds support for object- oriented programming (OOP for short). In addition, C++ contains many improvements and features that simply make it a "better C," independent of object-oriented programming. With very few, very minor exceptions, C+ isa superset of C. While everything that you know about the C language is fully applicable to C++, understanding its enhanced features will still require a significant investment of time and effort on your part. However, the rewards of programming in C++ will more than justify the effort you put forth ‘The purpose of this chapter is to introduce you to several of the ‘most important features of C++. As you know, the elements of a computer language do not exist in a void, separate from one another. Instead, they work together to form the complete language. This interrelatedness is especially pronounced in C++. In fact, it is difficult to discuss one aspect of C++ in isolation because the features of C++ are highly integrated. To help overcome this problem, this chapter provides a brief overview of several C++ features. This overview will enable you to understand the examples discussed later in this book. Keep in mind that most topics will be more thoroughly explored in later chapters. Since C++ was invented to support object-oriented programming, this chapter begins with a description of OOP. As you will sce, many features of C++ are related to OOP in one way or another. In fact, the theory of OOP permeates C++. However, it is important to understand that C++ can be used to write programs that are and are not object oriented. How you use C++ is completely up to you. At the time of this writing, the standardization of C++ is being finalized. For this reason, this chapter describes some important differences between versions of C++ that have been in common use during the past several years and the new Standard C++. Since this book teaches Standard C++, this material is especially important if you are using an older compiler. In addition to introducing several important C++ features, this chapter also discusses some differences between C and C++ programming styles. There are several aspects of C++ that allow greater flexibility in the way that you write programs. While some of these features have little or nothing to do with object-oriented ANOVERVIEWOFCH+ = 3 11 WHAT IS OBJECT-ORIENTED PROGRAMMING: = ¥ programming, they are found in most C++ programs, so it is appropriate to discuss them early in this book. Before you begin, a few general comments about the nature and form of C++ are in order. First, for the most part, C++ programs physically look like C programs. Like a C program, a C++ program begins execution at main( ). To include command-line arguments, C++ uses the same arge, argv convention that C uses. Although C++ defines its own, object-oriented library, it also supports all the functions in the C standard library. C++ uses the same control structures as C. C++ includes all of the built-in data types defined by C. ‘This book assumes that you already know the C programming language. In other words, you must be able to program in C before you can learn to program in C++ by using this book. If you don't know C, a good starting place is my book Teach Yourself C, Third Edition (Berkeley: Osborne/McGraw-Hill, 1997). It applies the same systematic approach used in this book and thoroughly covers the entire C language. This book assumes that you know how to compile and execute a program using your C++ compiler. If you don't, you will need to refer to your compiler’s instructions. (Because of the differences between compilers, it is impossible to give compilation instructions for each in this book.) Since programming is best learned by doing, you are strongly urged to enter, compile, and run the examples in the book in the order in which they are presented. Note HAT 1S OBJECT-ORIENTED PROGRAMMING? Object-oriented programming is a powerful way to approach the task of programming. Since its early beginnings, programming has been governed by various methodologies. At each critical point in the evolution of programming, a new approach was created to help the programmer handle increasingly complex programs, The first programs were created by toggling switches on the front panel of the computer. Obviously, this approach is suitable for only the smallest programs. Next, assembly language was invented, which allowed longer programs to be written. The next advance happened in the 1950s when the first high-level language (FORTRAN) was invented. By using a high-level language, a programmer was able to write programs that were several thousand lines long. However, the method . & TACHYOURSELF oH of programming used early on was an ad hoc, anything-goes approach. While this is fine for relatively short programs, it yields unreadable (and unmanageable) "spaghetti code” when applied to larger programs The elimination of spaghetti code became feasible with the invention of structured programming languages in the 1960s. These languages include Algol and Pascal. In loose terms, C is a structured language, and most likely the type of programming you have been doing would be called structured programming. Structured programming relies on well-defined control structures, code blocks, the absence (or at least minimal use) of the GOTO, and stand-alone subroutines that support recursion and local variables. The essence of structured programming is the reduction of a program into its constituent elements. Using structured programming, the average programmer can create and maintain programs that are up to 50,000 lines long. Although structured programming has yielded excellent results when applied to moderately complex programs, even it fails at some point, after a program reaches a certain size. To allow more complex programs to be written, a new approach to the job of programming was needed. Towards this end, object-oriented programming was invented. OOP takes the best of the ideas embodied in structured programming ané combines them with powerful new concepts that allow you to organize your programs more effectively. Object-oriented programming encourages you to decompose a problem into its constituent parts. Each component becomes a self-contained object that contains its own instructions and data that relate to that object. In this way, complexity is reduced and the programmer can manage larger programs. All OOP languages, including C++, share three common defining traits: encapsulation, polymorphism, and inheritance. Let's look at these concepts now. Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse, In an object-oriented language, code and data can be combined in such a way that a self-contained "black box" is created. When code and data are linked together in this fashion, an object is created. In other words, an object is the device that supports encapsulation. AN OVERVIEWOF C++ 1.1 WHATIS OBJECT-ORIENTED PROGRAMMING? ¥ Within an object, code, data, or both may be private to that object or public. Private code or data is known to and accessible only by another part of the object. That is, private code or data cannot be accessed by a piece of the program that exists outside the object. When code or data is public, other parts of your program can access it even though it is defined within an object. Typically, the public parts of an object are used to provide a controlled interface to the private elements of the object. For all intents and purposes, an object is a variable of a user-defined type. It may seem strange that an object that links both code and data can be thought of as a variable. However, in object-oriented programming, this is precisely the case. Each time you define a new type of object, you are creating a new data type. Each specific instance of this data type is a compound variable. POLYMORPHISM Polymorphism (from the Greek, meaning ‘many forms’) is the quality that allows one name to be used for two or more related but technically different purposes. As it relates to OOP, polymorphism allows one name to specify a general class of actions. Within a general class of actions, the specific action to be applied is determined by the type of data, For example, in C, which does not significantly support polymorphism, the absolute value action requires three distinct function names: abs( ), labs( ), and fabs( ). These functions compute and return the absolute value of an integer, a long integer, and a floating-point value, respectively. However, in C++, which supports polymorphism, each function can be called by the same name, such as abs( ). (One way this can be accomplished is shown later in this chapter.) The type of data used to call the function determines which specific version of the function is actually executed. AS you will see, in C++, it is possible to use one function name for iuany different purposes. This is called function overloading. More generally, the concept of polymorphism is characterized by the idea of ‘one interface, multiple methods," which means using a generic interface for a group of related activities. The advantage of polymorphism is that it helps to reduce complexity by allowing one interface to specify a general class of action. It is the compiler’s job to select the specific action as it applies to each situation. You, the programmer, don't need to do this selection manually. You need only remember and utilize the general interface. As the example in the preceding paragraph illustrates, having three names for the absolute value function instead of just one makes the general activity of obtaining the absolute value of a number more complex than it actually is Polymorphism can be applied to operators, too. Virtually all programming languages contain a limited application of polymorphism as it relates to the arithmetic operators. For example, in C, the + sign is used to add integers, long integers, characters, and floating-point values. In these cases, the compiler automatically knows which type of arithmetic to apply. in C++, you can extend this concept to other types of data that you define. This type of polymorphism is called operator overloading. The key point to remember about polymorphism is that it allows you to handle greater complexity by allowing the creation of standard interfaces to related activities. Inheritance is the process by which one object can acquire the properties of another. More specifically, an object can inherit a general set of properties to which it can add those features that are specific only to itself, Inheritance is important because it allows an object to support the concept of hierarchical classification. Most information is made manageable by hierarchical classification. For example, think about the description of a house. A house is part of the general class called building. In turn, building is part of the more general class structure, which is part of the even more general class of objects that we call man-made. In each case, the child class inherits all those qualities associated with the parent and adds to them its own defining characteristics. Without the use of ordered classifications, cach object would have to define all characteristics that relate to it explicitly. However, through inheritance, it is possible to describe an object by stating what general class (or classes) it belongs to along with those specific traits that make it unique. As you will see, inheritance plays a very important role in OOP. AN OVERVIEW OF G++ J 12 Twovesonsorce: = ¥ 1. Encapsulation is not entirely new to OOP. To a degree, encapsulation can be achieved when using the C language. For example, when you use a library function, you are, in effect, using a black-box routine, the internals of which you cannot alter or affect (except, perhaps, through malicious actions). Consider the fopen( ) function. When it is used to open a file, several internal variables are created and initialized. As far as your program is concerned, these variables are hidden and not accessible. However, C++ provides a much more secure approach to encapsulation. 2. Inthe real world, examples of polymorphism are quite common. For example, consider the steering wheel on your car. It works the same whether your car uses power steering, rack-and-pinion steering, or standard, manual steering. The point is that the interface (the steering wheel) is the same no matter what type of actual steering mechanism (method) is used. 3. Inheritance of properties and the more general concept of classification are fundamental to the way knowledge is organized. For example, celery is a member of the vegetable class, which is part of the plant class. In turn, plants are living organisms, and so forth. Without hierarchical classification, systems of knowledge would not be possible. 1. Think about the way that classification and polymorphism play an important role in our day-to-day lives. MEM JWo VERSIONS OF C++ At the time of this writing, C++ is in the midst of a transformation. As explained in the preface to this book, C++ has been undergoing the process of standardization for the past several years. The goal has been B Teachyounseir on to create a stable, standardized, feature-rich language that will suit the needs of programmers well into the next century. As a result, there are really two versions of C++. The first is the traditional version that is based upon Bjarne Stroustrup’s original designs. This is the version of C++ that has been used by programmers for the past decade, The second is the new Standard C++, which was created by Stroustrup and the ANSI/ISO standardization committee. While these two versions of C++ are very similar at their core, Standard C++ contains several enhancements not found in traditional C++. Thus, Standard C++ is essentially a superset of traditional C++. ‘This book teaches Standard C++. This is the version of C++ defined by the ANSI/ISO standardization committee, and it is the version implemented by all modern C++ compilers. The code in this book reflects the contemporary coding style and practices as encouraged by Standard C++. This means that what you learn in this book will be applicable today as well as tomorrow. Put directly, Standard C++ is the future. And, since Standard C++ encompasses all features found in earlier versions of C++, what you learn in this book will enable you to work in all C++ programming environments. However, ifyou are using an older compiler, it might not accept all of the programs in this book. Here's why: During the process of standardization, the ANSI/ISO committee added many new features to the language. As these features were defined, they were implemented by compiler developers. Of course, there is always a lag time between the addition of a new feature to the language and the availability of the feature in commercial compilers. Since features were added to C++ over a period of years, an older compiler might not support one or more of them. This is important because two recent additions to the C++ language affect every program that you will write—even the simplest. If you are using an older compiler that does not accept these new features, don’t worry. There is an easy workaround, which is described in the following paragraphs. The differences between old-style and modern code involve two new features: new-style headers and the namespace statement. To demonstrate these differences we will begin by looking at two versions ofa minimal, do-nothing C++ program. The first version, shown here, reflects the way C++ programs were written until recently. (That is, it uses old-style coding.) ANOVERVIEWOF G++ 12 TWO VERSIONS OF Gv A traditional-style C++ program. #include int main() /* program code */ return 0; ) Since C++ is built on C, this skeleton should be largely familiar, but pay special attention to the #include statement. This stat-ment includes the file iostream.h, which provides suppr~ for C++'s 1/O system, (It is to C++ whet stufo.h is to C.) Here is the second version of the skcleton, which uses the modern style: A modern-style C++ program that uses the new-style headers and a nanespace. vp tinclude using namespace std; int main(, /* program code */ return 0; Notice the two lines in this program immediately after the first comment; this is where the changes occur. First, in the #include statement, there is no .h after the name iostream. And second, the next line, specifying a namespace, is new. Although both the new-style headers and namespaces will be examined in detail later in this book, a brief overview is in order now. THE NEW C++ HEADERS As you know from your C programming experience, when you use a library function in a program, you must include its header file. This is 10 Teach Yours y te done using the #include statement. For example, in C, to include the header file for the 1/O functions, you include stdio.h with a statement like this: #include Here stdio.h is the name of the file used by the 1/O functions, and the preceding statement causes that file to ve included in your program ‘The key point is that the #include statement includes a file When C++ was first invented and for several years after that, it used the same style of headers as did C. In fact, Standard C++ still supports C-style headers for header files that you create and for backward compatibility. However, Standard C++ has introduced a new kind of header that is used by the Standard C++ library, The new-style headers do not specify filenames. Instead, they simply specify standard identifiers that might be mapped to files by the compiler, but they need not be, The new-style C++ headers are abstractions that simply guarantee that the appropriate prototypes and definitions required by the C++ library have been declared. Since the new-style header is not a filename, it does not have a .h extension. Such a header consists solely of the header name contained between angle brackets. For example, here are some of the new-style headers supported by Standard C++: ‘The new-style headers are included using the #include statement. The only difference is that the new-style headers do not necessarily represent filenames. Because C++ includes the entire C function library, it still supports the standard C-style header files associated with that library. That is, header files such as stdio.h and etype.h are still available. However, Standard C++ also defines new-style headers that you can use in place of these header files. The C++ versions of the standard C headers simply add a ¢ prefix to the filename and drop the -h. For example, the new-style C++ header for math.h is , and the one for string.h is . Although it is currently permissible to include a G-style header file when using C library functions, this approach is Remem! iber ANOVERVIEWOFCH 14 12 TWOVERSONSOFCH = V deprecated by Standard C++. (That is, it is not recommended.) For this treason, this book will use new-style C++ headers in all #include statements. If your compiler does not support new-style headers for the C fanction library, simply substitute the old-style, C-like headers. Since the new-style header is a recent addition to.C++, you will still find many, many older programs that don’t use it. These programs instead use C-style headers, in which a filename is specified. As the old-style skeletal program shows, the traditional way to include the V/O header is as sown here: tinclude ‘This causes the file iostream.h to be included in your program, In general, an old-style header will use the same name as its corresponding new-style header with a .h appended. As of this writing, all C++ compilers support the old-style headers. However, the old style headers have been declared obsolete, and their use in new programs is not recommended. This is why they are not used in this book. White still common in existing C++ code, old-style headers are obsolete. When you include a new-style header in your program, the contents of that header are contained in the std namespace. A namespace is simply a declarative region. The purpose of a namespace is to localize the names of identifiers to avoid name collisions. Traditionally, the names of library functions and other such items were simply placed into the global namespace (as they are in C). However, the contents of new-style headers are placed in the std namespace. We will look closely at namespaces later in this book. For now, you don't need to worry about them because you can use the statement using namespace std: to bring the std nantespacé into visibility (i-e., to put std into the global namespace)..after this statement has been compiled, there is no difference between working with an old-style header and a new-style one. As mentioned, both namespaces and the new-style headers are recent additions to the C++ language. While virtually all new C++ compilers support these features, older compilers might not. If you have one of these older compilers, it will report one or more errors when it tries to compile the first two lines of the sample programs in this book. If this is the case, there is an easy workaround: simply use an old-style header and delete the namespace statement. That is, just replace #include using namespace std; with #include ‘This change transforms a modem program into a traditional-style one. Since the old-style header reads all of its contents into the global namespace, there is no need for a namespace statement. One other point: For now and for the next few years, you will see many C++ programs that use the old-style headers and that do not include a namespace statement. Your C++ compiler will be able to compile them just fine. For new programs, however, you should use the modern style because it is the only style of program that complies with Standard C++. While old-style programs will continue to be supported for many years, they are technically noncompliant. 1. Before proceeding, try compiling the new-style skeleton program shown above. Although it does nothing, compiling it will tell you if your compiler supports the modern C++ syntax. If it does not accept the new-style headers or the namespace statement, substitute the old-style header as described. Remember, if your compiler does not accept new-style code, you must make this change for cach program in this book. ‘AN OVERVIEWOF C++ 93 13 Geeconsoevo Y ¢ mat CONSOLE i/O Since C++ isa superset of G, all elements of the C language are also contained in the C++ language. This implies that all C programs are also C++ programs by default. (Actually, there are some very minor exceptions to this rule, which are discussed later in this book.} Therefore, it is possible to write C++ programs that look just like C programs. While there is nothing wrong with this per se, it does mean. that you will not be taking full advantage of C+. To get the maximum benefit from C++, you must write C++-style programs. This means using a coding style and features that are unique to C++. Perhaps the most common C++-specific feature used by C++ programmers is its approach to console I/O. While you may still use functions such as printf() and scanf( ), C++ provides a new, and better, way to perform these types of I/O operations. In C+4, I/O is performed using I/O operators instead of I/O functions. The output operator is << and the input operator is >> As you know, in C, these are the left and right shift operators, respectively. In C+4, they still retain their original meanings (left and right shift) but they also take on the expanded role of performing input and output. Consider this C++ statement: cout << “This string is output to the screen. \n"; This statement causes the string to be displayed on the computer's screen. cout is a predefined stream that is automatically linked to the console when a C++ program begins execution. It is similar to C's stdout. As in C, C++ console I/O may be redirected, but for the rest of this discussion, it is assumed that the console is being used. By using the << output operator, it is possible to output any of C++’s basic types. For example, this statement outputs the value 100.99: cout << 100.99; In general, to output to the console, use this form of the << operator: cout << expression; Here expression can be any valid C++ expression—including another output expression. 1& TCH YoursELF Go To input a value from the keyboard, use the >> input operator. For example, this fragment inputs an integer value into num: int num; cin >> nun; Notice that num is not preceded by an &. As you know, when you use 2's scanf( ) function to input values, variables must have their addresses passed to the function so they can receive the values entered by the user. This is not the case when you are using C++'s input operator. (The reason for this will become clear as you learn more about C++.) In general, to input values from the keyboard, use this form of >>: cin >> variable; The expanded roles of << and >> are examples of operator overloading. In order to use the G++ I/O operators, you must include the header in your program. As explained carlicr, this is one of C++'s standard headers and is supplied by your C++ compiler. 1. This program outputs a string, two integer values, and a double floating-point value: #include using namespace std; int main(/ « int i, ji double d; Bue ) AN OVERVIEWO! c++ 15, 73 Grrconsoevo Y cout << "Here are some values: ~; cout << ' 4; cout << 4; cout << ' 4; return 0; The output of this program is shown here. Here are some values: 10 20 99.101 Remember If you are working with an older compiler, it might not accept the new-style headers and the namespace ‘statements used by this and other programs in this book. If this is the case, substitute the old-style code described in the preceding section. $ . It is possible to output more than one value in a single 1/O expression. For example, this version of the program described in Example 1 shows a more efficient way to code the 1/0 statements: #include using namespace std; int main() { int i, i; double d; 10; 20; 4 = 99.101; cout << "Here are some values: "; cout using namespace std; int main() int i: cout << "Enter a value: "; cin >> i; cout << "Here’s your number: * << i << "\nt; return 0; } Here is a sample run: enter a value: 100 Here's your number: 100 As you can see, the value entered by the user is put into i . The next program prompts the user for an integer value, a floating-point value, and a string. It then uses one input statement to read all three. include using namespace std; int main) { int is ANOVERVIEWOF C++ WF 1a ceeconsoueva | ¥ float £; char s{80); cout << “Enter an inceger, float, and string: *; cin >> i >> f >> 3; cout << “Here's your data col >, all input is line buffered. This means that no information is passed to your C++ program until you press ENTER. (In C, the scanf( ) function is line buffered, so this style of input should not be new to you.) To see the effect of line-buffered input, try this program: include using namespace std; int main() « char ch: cout << “Enter keys, x*to stop.\n'; do ¢ cout << +: * cin >> ch; } while (ch return 0; } When you test this program, you will have to press ENTERafter each key you type in order for the corresponding character to be sent to the program. 1. Write a program that inputs the number of hours that an employee works and the employee's wage. Then display the employee's gross pay. (Be sure to prompt for input.) 2. Write a program that converts feet to inches. Prompt the user for feet and display the equivalent number of inches. Have your program repeat this process until the user enters 0 for the number of feet. 3. Here is a C program. Rewrite it so it uses C++-style 1/O statements, /* Convert this C program into C++ style. ‘This program computes the lowest comnon denominator. ap #include int main(void) 4 int a, b, a, printé(*Enter two numbers: *); scanf (*8d%d!, Ga, &b); min=a>b?b:az for(d = 2; demin; d++) 4£(((a%d)-+0) && ({b%d)--0)) break: ANOVERVIEW OF C++ 9Q 14 Cr+ COMMENTS if(de=min) { print£("No common denoninators\n"); return 0; i printf ("The lowest common denominator is d\n", d); return 0; ( met COMMENTS In C++, you can include comments in your program two different ways. First, you can use the standard, C-like comment mechanism. That is, begin a comment with /* and end it with */. As with C, this type of comment cannot be nested in C+. The second way that you can add a remark to your C++ program is to use the single-line comment. A single-line comment begins with a // and stops at the end of the line. Other than the physical end of the line (that is, a carriage-return/linefeed combination), a single-line comment uses no comment terminator symbol. Typically, C++ programmers use C-like comments for multiline commentaries and reserve C-++-style single-line comments for short remarks. 1. Here is a program that contains both C and C++style comments , This is a C-like comment. This program determines whether an integer is odd or even. finclude using namespace std; z int main() { int num; // this is a C++ single-line comment // read the number cout << "Enter number to be tested: "; // see if even or odd if((num$2)==0) cout << ‘Number is even\n’ else cout << “Number is odd\n"; return 0; ) 2. While multiline comments cannot be nested, it is possible to nest a single-line comment.within a multiline comment. For example, this is perfectly valid: /* This is a multiline comment inside of which // is nested a single-line comment Here is the end of the multiline comment. ” The fact that single-line comments can be nested within multiline comments makes it easier for you to "comment out" several lines of code for debugging purposes. 1. Asan experiment, determine whether this comment (which nests a C-like comment within a C++-style, single-line comment) is valid: // This is a strange /* way to do a comment */ On your own, add comments to the answers to the exercises in section 1.3. ANOVERVIEW OF C++ 271 15 classes Armsrioox Ciasses A FIRST LOOK Perhaps the single most important feature of C++ is the class. The class is the mechanism that is used to create objects. As such, the class, is at the heart of many C++ features. Although the subject of classes is covered in great detail throughout this book, classes are so fundamental to C++ programming that a brief overview is necessary here. A dass is declared using the class keyword. The syntax of a class declaration is similar to that of a structure. Its general form is shown here: class class-name { 1 private functions and variables public: 1 public functions and variables } object-list, Ina class declaration, the object-list is optional. As with a structure, you can declare class cbjects later, as needed. While the class-name js also technically optional, from a practical point of view it is virtually always needed. The reason for this is that the class-name becomes a new type name that is used to declare objects of the class. Functions and variables declared inside a class declaration are said to be members of that class. By default, all functions and variables declared inside a class are private to that class. This means that they are accessible only by other members of that class. To declare public class members, the public keyword is used, followed by a colon. Alt functions and variables declared after the public specifier are accessible both by other members of the class and by any other part of the program that contains the class. Here is a simple class declaration: class myclass { (/ private to myclass int a; public: void set_a(int num); int get_a(); ue aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. AM OVERVIEW OF CH 23, 15 GASSES:ARSTLOOK type specifier. For example, this line declares two objects of type myclass: myclass obl, ob2; // these are objects of type myclass A class declaration is a logical abstraction that defines a new type. It determines what an object of that type will look like. An object declaration creates a physical entity of that type. That is, an object occupies memory space, but a type definition does not. Once an object of a class has been created, your program can reference its public members by using the dot (period) operator in much the same way that structure members are accessed: Assuming the preceding object declaration, the following statement calls set_a( ) for objects ob1 and ob2: obl.set_a(10); // sets obl’s version of a to 10 ob2.set_a(99); // sets ob2’s version of a to 99 As the comments indicate, these statements set ob1's copy of a to 10 and ob2's copy to 99. Each object contains its own copy of all data declared within the class. This means that ob1's a is distinct and different from the a linked to ob2. Each object of a class has its own copy of every variable declared within the class. 1, Asa simple first example, this program demonstrates myclass, described in the text. It sets the value of a for ob1 and ob2 and then displays a's value for each object: #include using namespace sta; class myclass ( /f private to myclass int az public: void set_a(int num) - int get_at); void myclass::set_a(int num) a = num; int myclass: :get_a() return a; int main() myclass obl, ob2; bl -set_a(10) ob2.set_a(99) cout << obl.get_a() << cout <« ob2.get_a() << return 0; As you should expect, this program displays the values 10 and 99 on the screen. In myelass from the preceding example, a is private. This means that only member functions of myclass can access it directly. (This is one reason why the public function get_a( ) is required.) If you try to access a private member of a class from some part of your program that is not a member of that class, a compile-time error will result. For example, assuming that myclass is defined as shown in the preceding example, the following main( ) function will cause an error: J/ This fragment contains an error tinciude using namespace std; int main) ANOVERVEWOF c++ 255 15 CASSES:ARMSTLOOK = nyclass obi, ob2; obl.a ob2.a 10; // ERROR! cannot access private member 99; // by non-member functions. cout << obl.get_a() << "\n"; cout << ob2.get_a() << "\n* return 0; ’ 3. Just as there can be public member functions, there can be public member variables as well. For example, iffa were declared in the public section of myclass, a could be referenced by any part of the program, as shown here: #include using namespace std; class myclass ( public: // now a is public int a; // and there is no need for set_a() or get_al) int main() « myclass obl, ob2; // here a is accessed directly obl.a = 10; ob2.a = 997 cout << obl.a << cout << ob2.a << return 0; d In this example, since a is declared as a public member of miyclass, it is directly accessible from main( ). Notice how the dot operator is used to access a. In general, when you are calling a member function or accessing a member variable from outside | z its class, the object's name followed by the dot operator followed by the member's name is required to fully specify which object's member you are referring to. . To get a taste of the power of objects, let's look at a more practical example. This program creates a class called stack that implements a stack that can be used to store characters: include using namespace std: fdefine SIZE 10 // Declare a stack class for characters class stack ( char stck(ST2F]; // holds the stack int tos; // index of top of stack public: void ii O; // initialize stack void push(char ch); // push character on stack char pop(); // pop character from stack Mh // Tnitialize the stack void stack: :init() { tos = 0; // Push a character. void stack: :push(char ch) { if(tos--STZE) ( cout << "Stack is full*; return; ) stck[tos} = chy Pop a character. pop() char tac if(tos.-0) ¢ ANOVERVIEW OF C++ 27 15 CLASSES:A FRSTLOOK = cout << "Stack is empty’; return 0; // return null on empty stack int main() { stack sl, s2; // create two stacks int is // initialize the stacks sl.init(); s2.init(); sl.push(‘a’); s2.push(‘x'); sl.push(‘b'); s2.push(‘y'); si.push('e'); s2.push(‘z'); for(i=0; ic3; i++) cout << "Pop sl: * << sl.pop({) << "\n"; for(iz0; i<3; l++) cout << “Pop s2: * << s2.pop() << "\n"; return 0; y This program displays the following output: Pop si: Pop si: Pop si: Pop s2: Pop s2: Pop s2: x< Neo Let’s take a clase look at this program now. The class stack contains two private variables: stck and tos. The array stck actually holds the characters pushed onto the stack, and tos contains the index to the top of the stack. The public stack functions are init( ), push( ), and pop( ), which initialize the stack, push a value, and pop a value, respectively. 28 Teach yoursar oH Inside main( ), two stacks, s1 and s2, are created, and three characters are pushed onto each stack. It is important to understand that each stack object is separate from the other. ‘That is, the characters pushed onto s1 in no way affect the characters pushed onto s2. Each object contains its own copy of stck and tos. This concept is fundamental to understanding objects. Although all objects of a class share their member functions, each object creates and maintains its own data. 1. Ifyou have not done so, enter and run the programs shown in the examples for this section. 2. Create a class called card that maintains a library card catalog entry. Have the class store a book's title, author, and number of copies on hand. Store the title and author as strings and the number on hand as an integer. Use a public member function called store( ) to store a book’s information and a public member function called show( ) to display the information. Include a short main( ) function to demonstrate the class. 3. Create a queue class that maintains a circular queue of integers. Make the queue size 100 integers long. Include a short main( ) function that demonstrates its operation. Gome DIFFERENCES BETWEEN C AND C++ Although C++ is a superset of C, there are some small differences between the two, and a few are worth knowing from the start. Before procevding, let's take time to examine them. First, in C, when a function takes no parameters, its prototype has the word void inside its function parameter list. For example, in C, if a ANOVERVIEWOFC++ 29 16 SOME DIFFERENCES BETWEEN CAND G++ function called f1( ) takes no parameters (and returns a char), its prototype will look like this char £1 (void); However, in C++, the void is optional. Therefore, in C++, the prototype for f1( ) is usually written like this: char £10; C++ differs from C in the way that an empty parameter list is specified. If the preceding prototype had occurred in a C program, it would simply mean that nothing is said about the parameters to the function. In C++, it means that the function has no parameters. This is the reason that the preceding examples did not explicitly use void to declare an empty parameters list. (The use of void to declare an empty parameter list is not illegal; it is just redundant. Since most C++ programmers pursue efficiency with a nearly religious zeal, you will almost never see void used in this way.) Remember, in C++, these two declarations are equivalent: char £10; char £1(void); Another subtle difference between C and C++ is that in a CH+ program, all functions must be prototyped. Remember, in C, prototypes are recommended but technically optional. In C++, they are required. As the examples from the previous section show, a member function's prototype contained in a class also serves as its general prototype, and no other separate prototype is required, A third difference between C and G++ is that in C+, if a function is declared as returning a value, it must return a value. That is, ifa function has a return type other than void, any return statement within that function must contain a value. In C, a non-void function is not required to actually retum a value. If it doesn’t, a garbage value is ‘returned." In C, if you don't explicitly specify the return type of a function, an integer return type is assumed. C++ has dropped the "default-to-int" rule. Thus, you must explicitly declare the return type of all functions. One other difference between and G++ that you will commonly encounter in C++ programs has to do with where local variables can be declared. In C, local variables can be declared only at the start of a block, prior to any "action" statements. In C++, local variables can be declared anywhere. One advantage of this approach is that local variables can be declared close to where they are first used, thus helping to prevent unwanted side effects. Finally, C++ defines the bool data type, which is used to store Boolean (i.e., true/false) values. C++ also defines the keywords true and false, which are the only values that a value of type bool can have. In C++, the outcome of the relational and logical operators is a value of type bool, and all conditional statements must evaluate to a bool value. Although this might at first seem to be a big change from ©, it isn’t. In fact, it is virtually transparent. Here's why: As you know, in C, true is any nonzero value and false is 0. This still holds in C++ because any nonzero value is automatically converted into true and any 0 value is automatically converted into false when used in a Boolean expression. The reverse also occurs: true is converted to 1 and false is converted to 0 when a bool value is used in an integer expression. The addition of bool allows more thorough type checking and gives you a way to differentiate between Boolean and integer types. Of course, its use is optional; bool is mostly a convenience. 1. In aG program, it is common practice to declare main( ) as shown here if it takes no command-line argument int main (void) However, in C++, the use of void is redundant and unnecessary. 2. This short C++ program will not compile because the function sum( ) is not prototyped: // This program will not compile. #include using namespace std: int main( 4 int a, b, cout << "Enter two numbers: *; aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. if (palance<0.0: cout << *\nt; out << "8; int main() ‘ cl_type acc (100.12, *Johnson“}; cl_type acc2(-12.34, *Hedricks*); acel.show(); ace2. show(); return 0; ) Here is an example that uses a union to display the binary bit pattern, byte by byte, contained within a double value. #include using namespace std; union bits { bits (double n); void show_bits(); double 4; unsigned char c[sizeof(doubie) }; bits: :bits(double n) t ae :show_bits() for(j = sizeof(double)-1; j>: cout << “Bit pattern in byte * << j = 1) £4 & e[5]) cout << else cout << "0"; cout << *\n*; INTRODUCING CLASSES. 7B 25. CLASSES STRUCTURES AND UNIONS ARE RELATED. int main() ( bits 0b(1991.829); ob. show_bits ( return 0; y The output of this program is Bit pattern in byte 7: 01000000 Bit pattern in byte 6: 10011111 Bit pattern in byte 5: 00011111 Bit pattern in byte 4: 01010000 Bit pattern in byte 1100101 Bit pattern in byte 2: 01100000 Bit pattern in byte 1: 01000001 Bit pattern in byte 0: 10001001 Both structures and unions can have constructors and destructors. The following example shows the strtype class reworked as a structure. It contains both a constructor and a destructor function. Winclude #include #include using namespace std; struct strtype ( strtype(char *ptr); ~strtype(); void show(}; private: char *p: int len; hi strtype::strtype(char *ptr) ‘ len = strlen(pts); P+ (char *) malloc(lenel); Th Weacn yourser om if(tp) ¢ cout << ‘Allocation error\n‘; exit(l): } strepy(p, ptr); strtype::~strtype() { cout << “Freeing p\n"; free(p); void strtype::show() cout << p << * - length: * << len; cout << "\n"; int main() strtype s1(‘This is a test."), s2(7I like C++. si.show(): s2.show(); return 0; . This program uses an anonymous union to display the individual bytes that comprise a double. (This program assumes that doubles are 8 bytes long) (7 Using an anonymous union. finclude using namespace std; int main) union ( unsigned char byres[2); double value; y int. 1; aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. In this example, input( ) creates a local object called str and then reads a string from the keyboard. This string is copied into str.s, and then str is returned by the function. This object is then assigned to ob inside main( ) when it is returned by the call to input( ). You must be careful about returning objects from functions if those objects contain destructor functions because the returned object goes out of scope as soon as the value is returned to the calling routine. For example, if the object returned by the function has a destructor that frees dynamically allocated memory, that memory will be freed even though the object that is assigned the return value is still using it. For example, consider this incorrect version of the preceding program: // Bn error generated by returning an object. #include #include #include using namespace std; class samp ( char *s; public: samp() {8 = ‘\0'7 } ~samp(} { if(s) free(s); cout << ‘Freeing s\n"; } void show() { cout << s << ‘\n"; ) void set(char *str); i // oad a string. void samp::set (char *str) { s = (char *) malloc(strlen(str) +1); if(ts) ( cout << ‘Allocation error\n"; exit(Li: } strepy(s, str); } // Return an object of type samp. samp input() ‘AGLOSER LOOK AT CLASSES 105 33 RETURNING OBJECTS FROM FUNCTIONS ¥ char s{801; samp str: cout << "Enter a string: *; cin >> 8; str.set(s); return str; } int main() ‘ samp ob; // assign returned object to ob ob = input(); // This causes an error! !!! ob. show() return 0; > The output from this program is shown here: Enter a string: Hello Freeing s Freeing s Hello Freeing s Null pointer assignment Notice that samp's destructor function is called three times. First, it is called when the local object str goes out of scone when input( ) returns. The second time ~ samp( ) is called is when the temporary object returned by input( ) is destroyed. Remember, when an object is returned from a function, an invisible (to you) temporary object is automatically generated which holds the return value. In this case, this object is simply a copy of str, which is the return value of the function. Therefore, after the function has returned, the temporary object’s destructor is executed. Finally, the destructor for object ob, inside main( ), is called when the program terminates. The trouble is that in this situation, the first time the destructor executes, the memory allocated to hold the string '1OG Tactvourser input by input( ) is freed. Thus, not only do the other two calls to samp's destructor try to free an already released piece of dynamic memory, but they destroy the dynamic allocation system in the process, as evidenced by the run-time message "Null pointer assignment." (Depending upon your compiler, the memory model used for compilation, and the like, you may or may not see this message if you try this program.) The key point to be understood from this example is that when an object is returned from a function, the temporary object used to effect the return will have its destructor function called. Thus, you should avoid returning objects in which this situation is harmful. (As you will leam in Chapter 5, it is possible to use a copy constructor to manage this situation.) 1. To illustrate exactly when an object is constructed and destructed when returned from a function, create a class called who. Have who's constructor take one character argument that will be used to identify an object. Have the constructor display a message similar to this when constructing an object: Constructing who #x where x is the identifying character associated with each object. When an object is destroyed, have a message similar to this displayed: Destroying who #x where, again, x is the identifying character. Finally, create a function called make_who( ) that returns a who object. Give each object a unique name. Note the output displayed by the program. 2. Other than the incorrect freeing of dynamically allocated memory, think of a situation in which it would be improper to return an object from a function. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. YAO TEACH YourseLF ow “ strepy(p, “This is a test’); Hint: A string is simply an array of characters. 2. Using new, show how to allocate a double and give it an initial value of -123.0987. PREFERENCES C++ contains a feature that is related to the pointer: the reference, A reference is an implicit pointer that for all intents and purposes acts like another name for a variable. There are three ways that a reference can be used. First, a reference can be passed to a function. Second, a reference can be retumed by a function. Finally, an independent reference can be created. Each of these applications of the reference is examined, beginning with reference parameters. Without a doubt, the most important use of a reference is as a parameter to a function. To help you understand what a reference parameter is and how it works, let's first start with a program that uses a pointer (not a reference) as a parameter: #include using namespace std; void f(int *n); // use a pointer parameter int main() ‘ int i = 0: Elails cout << "Here is its new value: * << i << ‘\n'; ARRAYS, POINTERS, AND REFERENCES. 9&1 46 REFERENCES «6 Y return 0; void f(int *n) *n = 100; // put 100 into the argument pointed to by n ) Here f( ) loads the value 100 into the integer pointed to by n. In this program, f( ) is called with the address of i in main( ). Thus, after f( ) returns, i contains the value 100. ‘This program demonstrates how a pointer is used as a parameter to manually create a call-by-reference parameter-passing mechanism. In aC program, this is the only way to achieve a call-by-reference. However, in C++, you can completely automate this process by using a reference parameter. To see how, let's rework the previous program. Here is a version that uses a reference parameter: f#include using namespace std: void £(int én); // declare a reference parameter int main() 4 int i = 0; fii); + cout << ‘Here is i’s new value: " << i << '\n’; return 0; // £() now uses a reference parameter void £(int én) { // notice that no * is needed in the following statement n = 100: // put 100 into the argument used to call £() Examine this program carefully. First, to declare a reference variable or parameter, you precede the variable's name with the & ‘This is how n is declared as a parameter to f( ). Now that n is a reference, it is no longer necessary—or even legal—to apply the * operator. Instead, each time n is used within f( ), it is automatically treated as a pointer to the argument used to call £( ). This means that the statement n = 100; actually puts the value 100 into the variable used to call £( ), which, in this case, is i. Further, when f() is called, there is no need to precede the argument with the & Instead, because f( ) is declared as taking a reference parameter, the address to the argument is automatically passed to £( ). To review, when you use a reference parameter, the compiler automatically passes the address of the variable used as the argument. There is no need to manually generate the address of the argument by preceding it with an & (in fact, it is not allowed). Further, within the function, the compiler automatically uses the variable pointed to by the reference parameter. There is no need to employ the * (and again, it is not allowed). Thus, a reference parameter fully automates the call-by-reference parameter-passing mechanism It is important to understand that you cannot change what a reference is pointing to. For example, if the statement ners were put inside f() in the preceding program, n would still be pointing to i in main( ). Instead of incrementing n, this statement increments the value of the variable being referénced (in this case, i) Reference parameters offer several advantages over their (more or less) equivalent pointer alternatives. First, from a practical point of view, you no longer need to remember to pass the address of an argument. When a reference parameter is used, the address is automatically passed. Second, in the opinion of many programmers, reference parameters offer a cleaner, more elegant interface thanthe rather clumsy explicit pointer mechanism. Third, as you will see in the next section, when an object is passed to a function as a reference, no copy is made, This is one way to eliminate the troubles associated with the copy of an argument damaging something needed elsewhere in the prog ram aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.

You might also like