Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
50%
(4)
50% found this document useful (4 votes)
11K views
609 pages
Teach Yourself C++
Its a book about learning C++, by Herbert Shield.
Uploaded by
KamruzzamanKamrul
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save Teach Yourself c++ For Later
50%
50% found this document useful, undefined
50%
, undefined
Embed
Share
Print
Report
50%
(4)
50% found this document useful (4 votes)
11K views
609 pages
Teach Yourself C++
Its a book about learning C++, by Herbert Shield.
Uploaded by
KamruzzamanKamrul
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save Teach Yourself c++ For Later
50%
50% found this document useful, undefined
50%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 609
Search
Fullscreen
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 032Contents 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 239Avout 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 IlinoisAcknowledgments, _ 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, 963.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, 2277 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, 39412 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, 53515 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, 607EXERCISES, 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, 698111_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_______739Se 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 ofevi 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 programmingmTropucTION 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-orientedANOVERVIEWOFCH+ = 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, theprogrammer, 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 beenB 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 is10 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 isRemem! 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 isno 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 isANOVERVIEWOF 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(); ueaa 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 azpublic: 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 aANOVERVIEWOFC++ 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 ablock, 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 areference, 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 ramaa 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.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.FUNCTION OVERLOADING 185 55 OVERLOADING AND AmaicuTY QUWERLOADING AND AMBIGUITY When you are overloading functions, it is possible to introduce ambiguity into your program. Overloading-caused ambiguity can be introduced through type conversions, reference parameters, and default arguments. Further, some types of ambiguity are caused by the overloaded functions themselves. Other types occur in the manner in which an overloaded function is called. Ambiguity must be removed before your program will compile without error. ET 1. One of the most common types of ambiguity is caused by C++'s automatic type conversion rules. As you know, when a function is called with an argument that is of a compatible (but not the same) type as the parameter to which it is being passed, the type of the argument is automatically converted to the target type. In fact, it is this sort of type conversion that allows a function such as putchar( ) to be called with a character even though its argument is specified as an int. However, in some cases, this automatic type conversion will cause an ambiguous situation when a function is overloaded. To see how, examine this program: // This program contains an ambiguity error. #include
using namespace std; float £(float i) 4 return i / 2.0; ) double f(double i) 4 return i / 3.0; ) int main() 4 float x = 10.09; double y = 10.09;cout << f(x); // unambiguous - use f (float) cout << f(y); // unambiguous ~ use £ (double) cout << £(10); // ambiguous, convert 10 to double or float?? return 0; ) As the comments in main( ) indicate, the compiler is able to select the correct version of f( ) when it is called with eithera float or a double variable. However, what happens when it is called with an integer? Does the compiler call f(float) or (double)? (Both are valid conversions!) In either case, it is valid to promote an integer into either a float or a double. ‘Thus, the ambiguous situation is created. This example also points out that ambiguity can be introduced by the way an overloaded function is called. The fact is that there is no inherent ambiguity in the overloaded versions of f( ) as long as each is called with an unambiguous argument. . Here is another example of function overloading that is not ambiguous in and of itself. However, when this function is called with the wrong type of argument, C++'s automatic conversion rules cause an ambiguous situation. // This progran is ambiguous. #include
using namespace std; void f(unsigned char c) { cout << ¢; ) void f(char ¢) cout << ¢; ) int main() ( EC); £(86); // which £() is called???FUNCTION OVERLOADING 187 55 OVERLOADING AND AMerGUTY return 0; } Here, when f( ) is called with the numeric constant 86, the compiler cannot know whether to call f(unsigned char) or f(char). Either conversion is equally valid, thus leading to ambiguity. . One type of ambiguity is caused when you try to overload functions in which the only difference is the fact that one uses a reference parameter and the other uses the default call-by-value parameter. Given C++'s formal syntax, there is no way for the compiler to know which function to call. Remember, there is no syntactical difference between calling a function that takes a value parameter and calling a function that takes a reference parameter. For example: // Bn ambiguous program. #include
using namespace std; int £(int a, int b) { return a+b; i // this is inherently ambiguous int f(int a, int @b) { return a-b; d int main() ‘ int x1, y= cout << £(x, y); // which version of £() is called??? return 0; ) Here, £(x, y) is ambiguous because it could be calling either version of the function. In fact, the compiler will flag an error before this statement is even specified because the overloadingaa 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.// Output count number of spaces. void space(int count) ‘ for( ; count; count--) cout << ' *; output count number of chs. void space(int count, char ch) for( ; count; count--) cout
Gkuts CHECK Mi ‘Skills Check At this point you should be able to perform the following exercises and answer the questions. 1. Overload the date( ) constructor from Section 5.1, Example 3, so that it accepts a parameter of type time_t. (Remember, time_t is a type defined by the standard time and date functions found in your C++ compiler’s library.) N . What is wrong with the following fragment? class samp ( int a; public: samp(int i) { a= Of sea ye192 react YounsEF om int main() samp x, y(10); We ) Give two reasons why you might want (or need) to overload a class's constructor. What is the most common general form of a copy constructor? What type of operations will cause the copy constructor to be invoked? . Briefly explain what the overload keyword does and why it is no longer needed. 7. Briefly describe a default argument. 8, Create a function called reverse( ) that takes two parameters 10. i. The first parameter, called str, is a pointer to a string that will be reversed upon return from the function. The second parameter is called count, and it specifies how many characters of str to reverse. Give count a default value that, when present, tells reverse( ) to reverse the entire string. What is wrong with the following prototype? char *wordwrap(char *str, int size=0, char ch); Explain some ways that ambiguity can be introduced when you are overloading functions What is wrong with the following fragment? void compute (double *num, int divisor=1); void compute (double *num); Uses compute (6x) 5FUNCTION OVERLOADING 193 ‘sauscHECK VY 12. When you are assigning the address of an overloaded function to a pointer, what is it that determines which version of the function is used? ‘Skills Check This section checks how well you have integrated material in this chapter with that from the preceding chapters 1. Create a function called order ) that takes two integer reference parameters. If the first argument is greater than the second argument, reverse the two arguments. Otherwise, take no action. That is, order the two arguments used to call order( ) so that, upon return, the first argument will be less than the second. For example, given int xe1, y=0; order (x, y); following the call, x will be 0 and y will be 1. 2. Why are the following two overloaded functions inherently ambiguous? int £(int a); int £(int gab; 3. Explain why using a default argument is related to function overloading. 4. Given the following partial class, add the necessary constructor functions so that both declarations within main( ) are valid. (Hint: You need to overload samp( ) twice.)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.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.INMERTANCE 265 73. CONSTRUCTORS, DESTRUCTORS, AND INHERTANCE passed to the derived class's constructor in the normal fashion. However, if you need to pass an argument to the constructor of the base class, a little more effort is needed. To accomplish this, 2 chain of argument passing is established. First, all necessary arguments to both the base class and the derived class are passed to the derived class's constructor. Using an expanded form of the derived class's constructor declaration, you then pass the appropriate arguments along to the base class. The syntax for passing along an argument from the derived class to the base class is shown here: derived-constructor (arg-list) : base(arg-list) { 11 body of derived class constructor } Here base is the name of the base class. It is permissible for both the derived class and the base class to use the same argument. It is also possible for the derived class to ignore all arguments and just pass them along to the base. EXAMPLES 1. Here is a very short program that illustrates when base class and derived class constructor and destructor functions are executed: include
using namespace std; class base { public: base|) { cout << ‘Constructing base class\n" ~base() { cout << ‘Destructing base class\n" bs » y class derived : public base 1 public: derived() ( cout
using namespace std; class base { public: pase() ( cout << “Constructing base class\n"; } -base() ( cout << "Destructing base class\n": } class derived : public base { int ji: public: derived(int n) ¢ cout << "Constructing derived class\i ~derived() { cout << "Destructing derived class\n"; void showj() { cout << j << ‘\n"; } fe int main() { derived 0(10); o- shows (1+ return 0;INHERITANCE 2497 73 CONSTRUCTORS, DESTRUCTORS, AND InHERTANGE Notice that the argument is passed to the derived class's constructor in the normal fashion. In the following example, both the derived class and the base class constructors take arguments. In this specific case, both use the same argument, and the derived class simply passes along the argument to the base. #include
using namespace std; class base ( int i; public: base(int n) { cout << "Constructing base class\n"; dosent 3 ~base() ( cout << ‘Destructing base class\n"; } void showi() { cout
using namespace std; class base ( int i; public: base(int nm) { cout << ‘Constructing base class\n" deny ~base|} { cout << ‘Destructing base classin"; } void showi() { cout << i << ‘\n'; ) de class derived : public base ( int J; public: derived(int n, int m) : base(m) { // pass arg to base class cout << ‘Constructing derived class\n jen > ~derived(} { cout
tos--; return stck{tos]; . Write a program that contains a class called watch. Using the standard time functions, have this class's constructor read the system time and store it. Create an inserter that displays the time. . Using the following class, which converts feet to inches, create an extractor that prompts the user for feet. Also, create an inserter that displays the number of feet and inches. Include a program that demonstrates that your inserter and extractor work. class ft_to_inches { double fect; double inches; public: void set (double £) { feet = f; inches = £ * 12;9 Advanced C++ I/O chapter objectives f a 9.1 Creating your own manipulators _— wy 9.2 File VO basics 9.3 Unformatted, binary /O 9.4 More unformatted VO functions ( ef 9.5 Random access 2 9.6 Checking the VO status Lo ad 9.7 Customized 1/0 and files 307 vaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.ADVANCED C++0 SOD 91. CREATING YOUR OWN MANIPULATORS 7. What predefined streams are created when a C++ program begins execution? CREATING YOUR OWN MANIPULATORS In addition to overloading the insertion and extraction operators, you can further customize C++'s I/O system by creating your own manipulator functions, Custom manipulators are important for two main reasons. First, a manipulator can consolidate a sequence of several separate I/O operations. For example, it is not uncommon to have situations in which the same sequence of I/O operations occurs frequently within a program. In these cases you can use a custom manipulator to perform these actions, thus simplifying your source code,and preventing accidental errors. Second, a custom manipulator can be important when you need to perform I/O operations on a nonstandard device. For example, you could use a manipulator to send control codes to a special type of printer or an optical recognition system. Custom manipulators are a feature of C++ that supports OOP, but they can also benefit programs that aren't object oriented. As you will see, custom manipulators can help make any I/O-intensive program clearer and more efficient. As you know, there are two basic types of manipulators: those that operate on input streams and those that operate on output streams. In addition to these two broad categories, there is a secondary division: those manipulators that take an argument and those that don’t. There are some significant differences between the way a parameterless manipulator and a parameterized manipulator are created. Further, creating parameterized manipulators is substantially more difficult than creating parameteriess ones and is beyond the scope of this book However, writing your own parameterless manipulators is quite easy and is examined here. ‘All parameterless manipulator output functions have this skeleton: ostream &manip-name(ostream &stream) { /I your code here retum stream, }BIO rach voursar ue OH Here manip-name is the name of the manipulator and stream is a reference to the invoking stream. A reference to the stream is returned, This is necessary if a manipulator is used as part of a larger 1/O expression. It is important to understand that even though the manipulator has as its single argument a reference to the stream upon which it is operating, no argument is used when the manipulator is called in an output operation. All parameterless input manipulator functions have this skeleton: istream &manip-name(istream &stream) { 1 your code here retum stream, } An input manipulator receives a reference to the stream on which it was invoked. This stream must be returned by the manipulator. * it is crucial that your manipulators retum a reference to the invoking stream. If this is not done, your manipulators cannot be used in a sequence of input or output operations. 1. Asa simple first example, the following program creates a manipulator called setup( ) that sets the field width to 10, the precision to 4, and the fill character to *. #include
using namespace std; ostream ksetup(ostream &stream) { stream.width(10) ; stream.precision (4); stream. £i11(°*"); return stream; , int main()ADVANCED C++ 0 BT 91 CREATING YouR OM MAMPLLATORS « Y { cout << setup << 123,123456; return 0; 1 As you can see, setup is used as part of an I/O expression in the same way that any of the built-in manipulators would be used. Custom manipulators need not be complex to be useful. For example, the simple manipulators atn( ) and note( ), shown here, provide a shorter way to output frequently used words or phrases. #include
using namespace std; J/ Attention: ostream gatn(ostream &stream) { stream << “Attention: *; return stream; } // Please note: ostream gnote (ostream &stream) ‘ stream << "Please Note: *; return stream; ) int main() { cout << atn << ‘High voltage circuit\n* cout << note << “Turn off all lights\n-; return 0; Even though they are simple, if used frequently, these manipulators save you from some tedious typing. This program creates the getpass( ) input manipulator, which rings the bell and then prompts for a password: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.=~) f OY f 4 } C- g 10 Virtual Functions chapter objectives 10.1 Pointers to derived classes 10.2 Introduction to virtual functions 10.3 More about virtual functions 10.4 Applying poymorphismB&G TEACH voursar 1s chapter examines another important aspect of C++: the virtual function. What makes virtual functions important is that they are used to support tun-time polymorphism. Polymorphism is supported by C++ in two ways. First, it is supported at compile time, through the use of overloaded operators and functions. Second, it is supported at run time, through the use of virtual functions. As you will learn, run-time polymorphism provides the greatest flexibility. ‘At the foundation of virtual functions and run-time polymorphism are pointers to derived classes. For this reason this chapter begins with a discussion of such pointers. (FA. a Skills Check Before proceeding, you should be able to correctly answer the following questions and do the exercises. 1. Create a manipulator that causes numbers to be displayed in scientific notation, using a capital E. Write a program that copies a text file. During the copy process, convert all tabs into the correct number of spaces. 3. Write a program that searches a text file for a word specified on the command line. Have the program display how many times the specified word is found. For simplicity, assume that anything surrounded by whitespace is a word. 4, Show the statement that sets the put pointer to the 234th byte in a file linked to a stream called out. 5. What functions report status information about the C++ 1/O system? 6. Give one advantage of using the C++ I/O functions instead of the Clike I/O system.VIRTUAL FUNCTIONS 347 10) pomrTeRs To DERWED cLasses | Y Pointers TO DERIVED CLASSES Although Chapter 4 discussed C-++ pointers at some length, one special aspect was deferred until now because it relates specifically to virtual functions. The feature is this: A pointer declared as a pointer to a base class can afso be used to point to any class derived from that base. For example, assume two classes called base and derived, where derived inherits base. Given this situation, the following statements are correct: base *p; // base class pointer base base_ob; // object of type base derived derived_ob; // object of type der ved // pcan, of course, point to base objects p= &base_ob; // p points to base object // pcan also point to derived objects without error P = &derived_ob; // p points to derived object As the comments suggest, a base pointer can point to an object of any class derived from that base without generating a type mismatch error. Although you can use a base pointer to point to a derived object, you can access only those members of the derived object that were inherited from the base. This is because the base pointer has knowledge only of the base class. It knows nothing about the members added by the derived class. ‘While it is permissible for a base pointer to point to a derived object, the reverse is not true. A pointer of the derived type cannot be used to access an object of the base class. (A type cast can be used to overcome this restriction, but its use is not recommended practice.) One final point: Remember that pointer arithmetic is relative to the data type the pointer is dectared as pointing to. Thus, ifyou point a base pointer to a derived object and then increment that pointer, it will not be pointing to the next derived object. It will be pointing to (what it thinks is) the next base object. Be careful about this.1. Here is a short program that illustrates how a base class pointer can be used to access a derived class: // Demonstrate pointer to derived class. #include
using namespace std; class base { int public: void setx(int i) (x = i; } int getx() ( return x; } ve class derived : public base { int y; public: void sety(int i) ( y = is } int gety() { return y; } int main() ‘ base *p; // pointer to base type base b_ob; // object of base derived d_ob; // object of derived // use p to access base object p = &b_ob; p-ssetx(10); // access base object cout << ‘Base object x: * << p-agetx() << ‘\n/; // use p to access derived object p = &Lob; // point to derived object pr>setx(99); // access derived object // can’t use p to set y, so do it directly dob. sety (88); cout << "Derived object x: * << p->getx() << ‘\n"; cout << “Derived object y: * << dob.gety() << ‘\n'7 return 0;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.VIRTUAL FUNCTIONS 357 103 MORE ABOUT VIRTUAL FUNCTIONS p= &t; cout << “Triangle has area: " << p->getarea() << ‘\n'; return 0; d Notice that the definition of getarea( ) inside area is just a placeholder and performs no real function. Because area is not linked to any specific type of figure, there is no meaningful definition that can be given to getarea( ) inside area. In fact, getarea( ) must be overridden by a derived class in order to be useful. In the next section, you will see a way to enforce this. 1. Write a program that creates a base class called num. Have this class hold an integer value and contain a virtual function called shownum( ). Create two derived classes called outhex and outoct that inherit num. Have the derived classes override shownum( ) so that it displays the value in hexadecimal and octal, respectively. 2. Write a program that creates a base class called dist that stores the distance between two points in a double variable. In dist, create a virtual function called trav_time( ) that outputs the time it takes to travel that distance, assuming that the distance is in miles and the speed is 60 miles per hour. In a derived class called metric, override trav_time( ) so that it outputs the travel time assuming that the distance is in kilometers and the speed is 100 kilometers per hour. MEEME fore asour viRTUAL FUNCTIONS As Example 4 from the preceding section illustrates, sometimes when a virtual function is declared in the base class there is no meaningful operation for it to perform. This situation is common because often abase class does not define a complete class by itself. Instead, it simply supplies a core set of member functions and variables to which the derived class supplies the remainder. When there is no meaningful action for a base class virtual function to perform, the implication is that any derived class must override this function. To ensure that this will occur, C++ supports pure virtual functions. A pure virtual function has no definition relative to the base class. Only the function’s prototype is included. To make a pure virtual function, use this general form: virtual type func-name( parameter-list) = 0; ‘The key part of this declaration is the setting of the function equal to 0. This tells the compiler that no body exists for this function relative to the base class. When a virtual function is made pure, it forces any derived class to override it. If a derived class does not, a compile-time error results. Thus, making a virtual function pure is a way to guarantee that a derived class will provide its own redefinition. When a class contains at least one pure virtual function, it is referred to as an abstract class. Since an abstract class contains at least one function for which no body exists, it is, technically, an incomplete type, and no objects of that class can be created. Thus, abstract classes exist only to be inherited. They are neither intended nor able to stand alone. It is important to understand, however, that you can still create a pointer to an abstract class, since it is through the use of base class pointers that run-time polymorphism is achieved. (It is also permissible to have a reference to an abstract class.) When a virtual function is inherited, so is its virtual nature. This means that when a derived class inherits a virtual function from a base class and then the derived class is used as a base for yet another derived class, the virtual function can be overridden by the final derived class (as well as the first derived class). For example, if base class B contains a virtual function called f( ), and D1 inherits B and D2 inherits D1, both D1 and D2 can override f( ) relative to their respective classes.MiRTUAL FUNCTIONS 359) 193 MOREABQUTRTUAL FuncTiONS 1. Here is an improved version of the program shown in Example 4 in the preceding section. In this version, the function getarea( ) is declared as pure in the base class area. // Create an abstract class. #include
using namespace std; class area ( double diml, dim2; // dimensions of figure public: void setarea (double di, double d2) { diml = dl; dim2 = d2; y void getdim(double sd1, double £42) { dl = diml; d2 = dima; + virtual double getarea() = 0; // pure virtual function he class rectangle : public area { public: double getarea() ( double di, 42; getdim(d1, 42); return dl * a2; class triangle : public area {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.TEMPLATES AND EXCEPTIONHANDLING 397 114 MORE AZQUT EXCEPTION HANDLING d int main() { cout << ‘start\n"; Xhandler (0); Xhandler (1) ; yhandler (2) 7 cout << ‘end’; return 0; ) ‘The output produced by this program is shown here: start Caught 0 Caught One! Caught One! end As this example suggests, using catch(...) as a default is a good way to catch all exceptions that you don't want to handle explicitly. Also, by catching all exceptions, you prevent an unhandled exception from causing an abnormal program termination. ‘The following program shows how to restrict the types of exceptions that can be thrown from a function: j/ Restricting function throw types. finclude
using namespace std: // This function can only throw ints, chars, and doubles. void xhandler(int test) throw(int, char, double) { if (tes! if (tes! if (tes! ) throw test; // throw int throw 'a‘; // throw char throw 123.23; // throw double int main() v39B TEACH vourser Cr cout << ‘start\n"; try{ Xhandler(0); // also, try passing 1 and 2 to Xhandler() } catch(int i) { cout << "Caught int\n*; ) catchichar c) { cout << “Caught char\n"; > catch(double 4) { cout << ‘Caught double\n"; } cout << tend"; return 0; > In this program, the function Xhandler( ) can throw only integer, character, and double exceptions. If it attempts to throw any other type of exception, an abnormal program termination will occur. (That is, unexpected( ) will be called.) To sce an example of this, remove int from the list and retry the program. It is important to understand that a function can only be restricted in what types of exceptions it throws back to the try block that called it. That is, a try block within a function can throw any type of exception so long as it is caught within that function. The restriction applies only when throwing an exception out of the function. . The following change to Xhandler( ) prevents it from throwing any exceptions: // This function can throw NO exceptions! void xhandler(int test) throw(| 4 /* The following statements no longer work, Instead, they will cause an abnormal program termination. */ if(test-=0) throw test; if(test==1) throw ‘a’;This program displays the following output: start Caught char * inside xhandler Caught char * inside main end 5. Here is a skeleton for a function called dit Before continuing, compile and run all of the examples in this section. Be sure you understand why each program produces the output that it does. What is wrong with this fragment? try ¢ VE eee throw 10; 2: catch(int *p) { Hh vss s 3. Show one way to fix the preceding fragment. 4, What catch expression catches all types of exceptions? ide( ). double divide(double a, double b) ( // add error handling return a/b; 3 ‘This function returns the result of dividing a by b. Add error checking to this function using C++ exception handling. Specifically, prevent a divide-by-zero error. Demonstrate your solution in a program.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.416 TEACH YourseF return NULL; int main() 4 int i; Shape * for(i=0; icl0; i++) { Pp = generator(); // get next object cout << typeid(*p).name() << endl; // daw object only if it is not a NullShape if(typeid(*p) t= typeid(Nullshape) ) p->example () i return 0; , Sample output from the program is shown here. class Rectangle class NullShape class Triangle class Line class Rectangle class LineRUN-TIME TYPEIDENTIFICATION AND THE CASTING OPERATORS 4117 12.1 UNDERSTANDING RUN-TIME TYPE IDENTIFICATION (RTT) «= class Triangle class Triangle class Triangle class Line The typeid operator can be applied to template classes. For example, consider the following program. It creates a hierarchy of template classes that store a value. The virtual function get_val( ) returns a value that is defined by each class. For class Num, this is the value of the number itself. For Square, it is the square of the number, and for Sqr_root, it is the square root of the number. Objects derived from Num are generated by the generator( ) function. The typeid operator is used to determine what type of object has been generated. // typeid can be used with templates. #include
#include
#include
#include
using namespace std; template
class Nun { public: Tx: Num(T i) (x = i; ) virtual T get_val() { return x; }: yh template
class Square : public NumcT> {[RUN-TIME TYPE IDENTIFICATION AND THE CASTING OPERATORS 419 12.1 UNDERSTANDING RUN-TIME TYPE IDENTICATION (RT? pl = generator (); // get next object if (typeid(*pl) == typeid(Squarecdouble>)) - cout << “Square object: "; if(typeid(*pl) == typeid(Sar_root
)) cout << “Sar_root object: "; cour cout << pl->get_val(); return 0; > ‘The output from the program is shown here. claas Numedouble> class Square
class Sqr_root
is Square
Value is: 10000 Now, generate some Objects. Sqr_root object: Value is: 6.18535 Square object: Value is: 0 Sqr_root object: Value is: 4.89898 Square object: Value is: 3364 Square object: Value is: 4096 Sqr_root “object: value is: 6.7082 Sqr_root object: Value is: 5.19615 Sqr_root object: Value is: 9.53939 Sqr_root object: Value is: 6.48074 Sqr_root object: Value is: 6 1. Why is RTTI a necessary feature of C++? 2. Try the experiment described in Example 1. What output do you see? 3. Is the following fragment correct? cout << typeid(float).name();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.(G28 TEACH YOURSELF oF if(p2) cout << “Square object: *; p3 = dynamic_cast
*> (pl): if(p3) cout << "Sqr_root object: "7 cout
*Bp; Square
“we Dp = dynamic_cast
> (Bp);3. void f(const double &i) i = 100; // Brror -- fix using const_cast te main() double x = 98.6; cout << x << endl; E(x); cout << x << endl; return 0; Explain why const_cast should normally be reserved for special cases. Gries CHECK Mas Skills Check At this point you should be able to perform the following exercises and answer the questions. eur » . Describe the operation of typeid. ‘What header must you include in order to use typeid? In addition to the standard cast, C++ defines four casting operators. What are they and what are they for? Complete the following partial program so that it reports which type of object has been selected by the user.[RUN-TIME TYPE IDENTIFICATION AND THE CASTING OPERATORS 433 snus cHex ¥ #include
#include
using namespace std; class A { virtual void £() {) de class B : public A { dy class C: public B { ii int main() ‘ A *p, a_ob; B bob, C cob; int i; cout << "Enter @ for A objects, *; cout << "1 for B objects or cout << "2 for ¢ objects. \n"; cin >> i: if(is=1) p = &b_ob; else if(i==2) p = &c_ob; else p = &a_ob; // veport type of object selected by user return , 5. Explain how dynamic_cast can sometimes be an alternative to typeid. 6. What type of object is obtained by the typeid operator?‘Cumulative: ‘Skills Check This section checks how well you have integrated material in this chapter with that from the preceding chapters. 1. Rework the program in Section 12.1, Example 4 so that it uses exception handling to watch for an allocation failure within the generator( ) function. 2. Change the generatar( ) function from Question 1 so that it uses the nothrow version of new. Be sure to check for errors. 3. Special Challenge: On your own, create a class hierarchy that has at its top an abstract class called DataStruct. Create two concrete subclasses. Have one implement a stack, the other a queue. Create a function called DataStructFactory( ) that has this prototype: DataStruct *DataStructFactory(char what); Have DataStructFactory( ) create a stack if what iss and a queue if what is g. Return a pointer to the object created. Demonstrate that your factory function works,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.NAMESPACES, CONVERSION FUNCTIONS, AND MISCELLANEOUS TOPICS 46571 135 AFINALLOOKAT CONSTRUCTORS class myclass ( int a; public: myclass(int x) (a= x; } myclass(char *str) (a = atoi(str); } int geta() { return a; } Mu int main() { myclass obl * 4; // converts to myclass (4) myclass ob2 ~ °123"; // converts to myclase ("123"); cout << ‘obl: * << obl.geta() << end cout << "ob2: * << ob2.geta() << end return 0; } Since both constructors use different type arguments (as, of course, they must), each initialization statement is automatically converted into its equivalent constructor call. . The automatic conversion from the type of a constructor's first argument into a call to the constructor itself has interesting implications. For example, assuming myclass from Example 1, the following main( ) function makes use of the conversions from int and char * to assign ob] and ob2 new values. int main() 4 myclass obl = 4; // converts to myclass (4) myclass ob2 = "123"; // converts to myclass(7123"); cout << ‘obi: cout << ‘ob2 << obl.getal) << endl << ob2.geta() << endl; // use automatic conversions to assign new values obl = *1776"; // converts into obl = myclass("1776" ob2 = 2001; // converts into ob2 = myclass(200i); cout << ‘obl: * << obl.getal) << endl; cout << ‘ob2: 7 << ob2.getal) << endl;return , 3. To prevent the conversions just shown, you could specify the constructors as explicit, as shown here: #include
#include
using namespace std; class myclass { int a: public: explicit myclass(int x) ( a = explicit myclass(char *str) ( int geta() ( return a; } x} a = atoi(str); } 1. In Example 3, if only myclase(int) is made explicit, will myclase(char *) still allow implicit conversions? (Hint: Try it.) 2. Will the following fragment work? class Demo { double x public: Demo(double i) { x = i; } Pees de Th wes Demo counter = 10; 3. Justify the inclusion of the explicit keyword. (In other words, explain why implicit constructor conversions might not be a desirable feature of C++ in some cases.)NAMESPACES, CONVERSION FUNCTIONS, AND MISCELLANEOUS TOPICS 463 136 USING LINKAGE SPEGIFIERS AND THE asm KEMWORD Ufsine LINKAGE SPECIFIERS AND THE asm KEYWORD C++ provides two important mechanisms that make it easier to link C++ to other languages. One is the linkage specifier, which tells the compiler that one or more functions in your C++ program will be linked with another language that might have a different approach to naming, parameter passing, stack restoration, and the like. The second is the asm keyword, which allows you to embed assembly language instructions in your C++ source code. Both are examined here. By default, all functions in a C++ program are compiled and linked as C++ functions. However, you can tell the C++ compiler to link a function so that it is compatible with another type of language. All C++ compilers allow functions to be linked as either C or C++ functions. Some also allow you to link functions with languages such as Pascal, Ada, or FORTRAN. To cause a function to be linked for a different language, use this general form of the linkage specification: extern "/anguage" function-prototype; Here language is the name of the language with which you want the specified function to link. If you want to specify linkage for more than one function, use this form of the linkage specification: extern "/anguage” ( function-prototypes } All linkage specifications must be global; they cannot be used inside a function. ‘The most common use of linkage specifications occurs when linking C++ programs to C code. By specifying "C" linkage you prevent the compiler from mangling (also known as decorating) the names of functions with embedded type information. Because of C++'s ability to overload functions and create member functions, the link-name of a function usually has type information added to it. Since C does not support overloading or member functions, it cannot recognize a mangled name. Using 'C” linkage avoids this problem.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.Member Function Description void splice(iterator i, Removes the element pointed to by e/ from the list
&0b, list 0b and stores it in the invoking list at the iterator ef); location pointed to by i void splice(iterator i, Removes the range defined by start and end from list
&ab, ob and stores it in the invoking list beginning at iterator start iterator end); the location pointed to by i void swap(list
&0b) Exchanges the elements stored in the invoking list with those in ob. void unique(); Removes duplicate elements from the invoking template
list. The second form uses pr to determine void unique(BinPred pA; uniqueness. The list Member Functions (continued) ¥ 1. Here is a simple example of a list. // List basics. #include
#include
using namespace std; int main() ‘ listechar> Ist: // create an empty list int i; j itt) Ist.pushback('A' sil; cout Size = * << lst.size() << endl; list
::iterator p; out << ‘Contents: le(!ist.empty()) { p = lst.begin(); cout << * Ast -pop_front ();INTRODUCING THE STANDARD TEMPLATE LIBRARY QF maa ists Vv 4. You can sorta list by calling the sort( ) member function. The following program creates a list of random characters and then puts the list into sorted order. ¢/ Gort a list. #include
include
#include
using namespace std; int main() 1 listechar> Ist; int i; // create a list of random characters for(i=0; icl0; iss) Ast.push_back("A‘+ (rand ()$26))7 cout << "Original contents: *; list
::iterator p = Ist.begin(); while(p != Ist.end()) { cout << *p; peer y cout << endl << endl; /f sort the list Ast.sort (); 5 \ 1 cout << "Sorted contents: p = Ist.begin(); while(p f= Ist-end()) { cout << *p: ptr ) return 0; } Here is sample output produced by the program. Original contents: PHOGHUMEAY Sorted contents: AEGHHMPQUY5. One ordered list can be merged with another. The result is an ordered list that contains the contents of the two original lists. The new list is left in the invoking list and the second list is left empty. This example merges two lists. The first contains the letters ACEGI and the second BDFHJ. These lists are then merged to produce the sequence ABCDEFGHV. // Merge two lists. include
include
using namespace std; int main() { list
Istl, 1st2; int i; for(is0; icl0; ive2) Ist1.push_back(‘A'+il; for(i=1; i
::iterator p = 1stl.begin(); while(p != Istl.endi)} ¢ cout << *p; pee; » cout << endl << endl; cout << ‘Contents of Ist2 p = 1st2.begin(); while(p != lst2.endi)) { cout << “ps pee; y cout <« endl << endl; // now, merge the two lists Istl.merge(1st2); if(1st2.empty()) cout << ‘Ist2 is now empty\n': cout << ‘Contents of Isti after merge: \n"; p = Isti.begin(); while(p + letl.endiy) 4 cout << *p: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.INTRODUCING THE STANDARD TEMPLATE LIBRARY 519) Tey HESTRING CLASS | The sequences to be merged are defined by startl, end] and start2, end2. The result is put into the sequence pointed to by result. An iterator to the end of the resulting sequence is returned. Demonstrate this algorithm Ea Fue STRING CLASS As you know, C++ does not support a built-in string type, per se. It does, however, provide two ways to handle strings. First, you can use the traditional, null-terminated character array with which you are already familiar. This is sometimes referred to as a C string. The second method is to use a class object of type string. This is the approach that is examined here. Actually, the string class is a specialization of a more general template class called basic_string. In fact, there are two specializations of basic_string: string, which supports 8-bit character strings, and wstring, which supports wide character strings. Since 8-bit characters are by far the most commonly used characters in normal programming, string is the version of basic_string examined here. Before you look at the string class, it is important that you understand why it is part of the C++ library. Standard classes have not been casually added to C++. In fact, a significant amount of thought and debate has accompanied each new addition. Given that C++ already contains some support for strings as null-terminated character arrays, it might at first seem that the inclusion of the string class is an exception to this rule. However, this is actually far from the truth. Here is why: Null-terminated strings cannot be manipulated by any of the standard C++ operators, nor can they take part in normal C++ expressions. For example, consider this fragment: char s1[80], s2{80], s3{80]; sl s2 83 tone"; // can’t do *twot; // can't do sl + 82; // error, not allowedAs the comments show, in C++ it is not possible to use the assignment operator to give a character array a new value (except during initialization), nor is it possible to use the + operator to concatenate two strings. These operations must be written using library functions. as shown he: strcpy(si, ‘one* strepy(s2, "two"); strepy(s3, sl); streat(s3, s2); Since null-terminated character arrays are not technically data types in their own right, the C++ operators cannot be applied to them. ‘This makes even the most rudimentary string operations clumsy. More than anything else, it is the inability to operate on null- terminated strings using the standard C++ operators that has driven the development of a standard string class. Remember, when you define a class in C++, you are defining a new data type that can be fully integrated into the C++ environment. This, of course, means that the operators can be overloaded relative to the new class Therefore, with the addition of a standard string class, it becomes possible to manage strings in the same way that any other type of data is managed: through the use of operators. There is, however, one other reason for the standard string class: safety. An inexperienced or careless programmer can very easily overrun the end of an array that holds a null-terminated string. For example, consider the standard string copy function strepy( ). This function contains no provision for checking the boundary of the target array. If the source array contains more characters than the target array can hold, a program error or system crash is possible (likely). As you will see, the standard string class prevents such errors. In the final analysis, there are three reasons for the inclusion of the standard string class: consistency (a string now defines a data type), convenience (you can use the standard C++ operators), and safety (array boundaries will not be overrun). Keep in mind that there is no reason that you should abandon normal, null-terminated strings altogether. They are still the most efficient way in which to implement strings, However, when speed is not an overriding concer, the new string class gives you access to a safe and fully integrated way to manage strings.INTRODUCING THE STANDARD TEMPLATE LIBRARY 52 147 TESTING CASS Vv Although not traditionally thought of as part of the STL, string is another container class defined by C++. This means that it supports the algorithms described in the previous section. However, strings have additional capabilities. To have access to the string class you must include
in your program. The string class is very large, with many constructors and member functions. Also, many member functions have multiple overloaded forms. For this reason, it is not possible to look at the entire contents of string in this chapter. Instead, we will examine several of its most commonly used features. Once you have a general understanding of how string works, you will be able to easily explore the rest of it on your own. The string class supports several constructors. The prototypes for three of its most commonly used constructors are shown here. string); string(const char *st); string(const string &st7); The first form creates an empty string object. The second creates a string object from the null-erminated string pointed to by str. This form provides a conversion from null-terminated strings to string objects. The third form creates a string object from another string object. A number of operators that apply to strings are defined for string objects, including those listed in the following table: Operator Meaning = Assignment Concatenation Concatenation assignment Equality Inequality Less than Less than or equal Greater than Greater than or equal a SubscriptingOperator Meaning << Output >»> Input These operators allow the use of string objects in normal expressions and eliminate the need for calls to functions such as strepy( ) or strcat( ), for example. In general, you can mix string objects with normal, null-terminated strings in expressions. For example, a string object can be assigned a null-terminated string. ‘The + operator can be used to concatenate a string object with another string object or a string object with a C-style string. That is, the following variations are supported: string + sting string + C-string C-string + string The + operator can also be used to concatenate a character onto the end ofa string. The string class defines the constant npos, which is usually -1. This constant represents the length of the longest possible string. Although most simple string operations can be accomplished with the string operators, more complex or subtle ones are accomplished with string class member functions. Although there are far too many to discuss in this chapter, we will examine several of the most common ones. To assign one string to another, use the assign( ) function. Two of its forms are shown here: string &assign(const string &strob. size_type start. size_type num): string &assign(const char *str, size_type num); In the first form, num characters from strob beginning at the index specified by start will be assigned to the invoking object. In the second form, the first num characters of the null-terminated string str. are assigned to the invoking object. In each case, a reference to the invoking object is returned. Of course, it is much easier to use the = operator to assign one entire string to another. You will need to use, the assign( ) function only when assigning a partial string. You can append part of one string to another using the append( ) member function. Two of its forms are shown here:
You might also like
Teach Yourself C
PDF
No ratings yet
Teach Yourself C
647 pages
Java-The Complete Reference J2EE by Jim Keogh, 4th Edition Tata Mcgraw-Hill
PDF
0% (1)
Java-The Complete Reference J2EE by Jim Keogh, 4th Edition Tata Mcgraw-Hill
865 pages
DSC++ Unit - I
PDF
100% (1)
DSC++ Unit - I
37 pages
Full Introduction To Algorithms Fourth Edition. Edition Clifford Stein Ebook All Chapters
PDF
0% (1)
Full Introduction To Algorithms Fourth Edition. Edition Clifford Stein Ebook All Chapters
35 pages
Chemistry Formula Handbook
PDF
No ratings yet
Chemistry Formula Handbook
14 pages
Systems Programming and Operating Systems by Dhamdhere PDF
PDF
22% (9)
Systems Programming and Operating Systems by Dhamdhere PDF
95 pages
CPP Pocket Reference PDF
PDF
100% (1)
CPP Pocket Reference PDF
138 pages
C++ Programming (Mastering Programming Languages Series) by Theophilus Edet
PDF
100% (1)
C++ Programming (Mastering Programming Languages Series) by Theophilus Edet
336 pages
PDF Programming With C Second Edition Byron Gottfried
PDF
0% (7)
PDF Programming With C Second Edition Byron Gottfried
2 pages
Computer Science An Overview (12th Edition)
PDF
0% (4)
Computer Science An Overview (12th Edition)
437 pages
Teach Yourself CNC
PDF
0% (1)
Teach Yourself CNC
605 pages
OOPinC byJohnsonbaughMartin
PDF
No ratings yet
OOPinC byJohnsonbaughMartin
566 pages
Cplusplus
PDF
No ratings yet
Cplusplus
897 pages
Computer Science A Structured Approach Using C by Behrouz A. Forouzan Richard F. Gilberg
PDF
91% (11)
Computer Science A Structured Approach Using C by Behrouz A. Forouzan Richard F. Gilberg
1,176 pages
C Without Fear A Beginners Guide That Makes You Feel Smart Overland Instant Download
PDF
No ratings yet
C Without Fear A Beginners Guide That Makes You Feel Smart Overland Instant Download
79 pages
C++ For Java Programmers PDF
PDF
100% (5)
C++ For Java Programmers PDF
290 pages
Banerjee P. From Novice To Ninja. Mastering DSA in C++ 2023
PDF
No ratings yet
Banerjee P. From Novice To Ninja. Mastering DSA in C++ 2023
104 pages
Prentice Cplusplus For Java Programmers 013919424X
PDF
100% (1)
Prentice Cplusplus For Java Programmers 013919424X
290 pages
Lec1. C++ Basics
PDF
No ratings yet
Lec1. C++ Basics
38 pages
DS Through C
PDF
100% (1)
DS Through C
542 pages
Accelerated C++ 2000
PDF
No ratings yet
Accelerated C++ 2000
453 pages
Derek Capper (Auth.) - Introducing C++ For Scientists, Engineers and Mathematicians-Springer London (2001) PDF
PDF
No ratings yet
Derek Capper (Auth.) - Introducing C++ For Scientists, Engineers and Mathematicians-Springer London (2001) PDF
551 pages
Computing Notes - A Level
PDF
92% (12)
Computing Notes - A Level
185 pages
Unit Ii
PDF
No ratings yet
Unit Ii
52 pages
C++ For Java Programmers
PDF
100% (1)
C++ For Java Programmers
289 pages
DK Kharate
PDF
No ratings yet
DK Kharate
343 pages
Anization and Design The Hardware Software Interface 3rd
PDF
100% (6)
Anization and Design The Hardware Software Interface 3rd
684 pages
C in Depth (2nd Ed.) (Srivastava 2009-06-30) PDF
PDF
75% (16)
C in Depth (2nd Ed.) (Srivastava 2009-06-30) PDF
550 pages
E. Balaguruswamy - Introduction To Computing and Problem Solving Using Python-Mc Graw Hill India (2016) Pages 301 - 336 - Flip PDF Download - FlipHTML5
PDF
No ratings yet
E. Balaguruswamy - Introduction To Computing and Problem Solving Using Python-Mc Graw Hill India (2016) Pages 301 - 336 - Flip PDF Download - FlipHTML5
340 pages
Fundamentals of Data Structures in C by Ellis Horowitz, Sartaj Sahni, Susan Anderson-Freed
PDF
80% (10)
Fundamentals of Data Structures in C by Ellis Horowitz, Sartaj Sahni, Susan Anderson-Freed
605 pages
Advanced C++ Programming
PDF
No ratings yet
Advanced C++ Programming
3 pages
Ocr A Level Computer Science For A Level Includes Annas Archive
PDF
No ratings yet
Ocr A Level Computer Science For A Level Includes Annas Archive
284 pages
Let Us C Solutions PDF
PDF
No ratings yet
Let Us C Solutions PDF
188 pages
Introduction To Computer Science Using Python
PDF
50% (4)
Introduction To Computer Science Using Python
12 pages
Teach Yourself C++ (Introductory Pages)
PDF
No ratings yet
Teach Yourself C++ (Introductory Pages)
17 pages
Advanced Practical Physics Worsnop and Flint
PDF
83% (6)
Advanced Practical Physics Worsnop and Flint
689 pages
Introduction To C++
PDF
No ratings yet
Introduction To C++
48 pages
Lecture 1
PDF
No ratings yet
Lecture 1
31 pages
C++ Journey
PDF
No ratings yet
C++ Journey
24 pages
01 01 Intro
PDF
No ratings yet
01 01 Intro
30 pages
Mastering C++ Programming
PDF
100% (5)
Mastering C++ Programming
451 pages
Iit Delhi 22
PDF
No ratings yet
Iit Delhi 22
76 pages
Summer Training: C/C++ Programming
PDF
No ratings yet
Summer Training: C/C++ Programming
21 pages
C Is Better Than C
PDF
No ratings yet
C Is Better Than C
10 pages
Mathematics: DSC - Part II
PDF
88% (8)
Mathematics: DSC - Part II
512 pages
Block-1: Unit-Ii
PDF
No ratings yet
Block-1: Unit-Ii
52 pages
Bca C202 SM01
PDF
No ratings yet
Bca C202 SM01
26 pages
PDF
PDF
0% (1)
PDF
36 pages
C++ Overview of C++: Object-Oriented Programming
PDF
No ratings yet
C++ Overview of C++: Object-Oriented Programming
35 pages
C Is Better Than C
PDF
No ratings yet
C Is Better Than C
10 pages
Test Your C Skills by "Yashwant Kanetkar"
PDF
82% (28)
Test Your C Skills by "Yashwant Kanetkar"
129 pages
C Plus Plus How To Program 11e Contents
PDF
No ratings yet
C Plus Plus How To Program 11e Contents
16 pages
Myths Final
PDF
No ratings yet
Myths Final
23 pages
CPP
PDF
No ratings yet
CPP
92 pages
Data Structures Using C and C++ - Y. Langsam, M. Augenstein and A. M. Tenenbaum
PDF
No ratings yet
Data Structures Using C and C++ - Y. Langsam, M. Augenstein and A. M. Tenenbaum
99 pages
Puzzle Putih A
PDF
No ratings yet
Puzzle Putih A
6 pages
Programming Fundamentals - CS116
PDF
100% (2)
Programming Fundamentals - CS116
2 pages
MSC Preparation Buet
PDF
No ratings yet
MSC Preparation Buet
1 page
Content Organization: Tions
PDF
No ratings yet
Content Organization: Tions
2 pages