The C++ Programming language


The C+ + Programming Language Third Edition Bjarne Stroustrup AT&T Labs Murray Hill, New Jersey Addison-Wesley An Imprint of Addison Wesley Longman, Inc. Reading, Massachusetts • Harlow, England • Menlo Park, California Berkeley, California • Don Mills, Ontario • Sydney Bonn • Amsterdam • Tokyo • Mexico Cityii Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed in initial capital letters or all capital letters The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information contained herein. The publisher offers discounts on this book when ordered in quantity for special sales. For more information please contact: Corporate & Professional Publishing Group Addison-Wesley Publishing Company One Jacob Way Reading, Massachusetts 01867 Library of Congress Cataloging-in-Publication Data Stroustrup, Bjarne The C++ Programming Language / Bjarne Stroustrup. Ð 3rd. ed. p. cm. Includes index. ISBN 0-201-88954-4 1. C++ (Computer Programming Language) I. Title QA76.73.C153S77 1997 97-20239 005.13’3Ðdc21 CIP Copyright © 1997 by AT&T All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America. This book was typeset in Times and Courier by the author. ISBN 0-201-88954-4 Printed on recycled paper 1 2 3 4 5 6 7 8 9ÐCRWÐ0100999897 First printing, June 1997Contents Contents iii Preface v Preface to Second Edition vii Preface to First Edition ix Introductory Material 1 1 Notes to the Reader ..................................................................... 3 2 A Tour of C++ ............................................................................. 21 3 A Tour of the Standard Library .................................................. 45 Part I: Basic Facilities 67 4 Types and Declarations ............................................................... 69 5 Pointers, Arrays, and Structures .................................................. 87 6 Expressions and Statements ........................................................ 107 7 Functions ..................................................................................... 143 8 Namespaces and Exceptions ....................................................... 165 9 Source Files and Programs .......................................................... 197 The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.iv Contents Part II: Abstraction Mechanisms 221 10 Classes ........................................................................................ 223 11 Operator Overloading ................................................................. 261 12 Derived Classes ........................................................................... 301 13 Templates .................................................................................... 327 14 Exception Handling .................................................................... 355 15 Class Hierarchies ........................................................................ 389 Part III: The Standard Library 427 16 Library Organization and Containers .......................................... 429 17 Standard Containers .................................................................... 461 18 Algorithms and Function Objects ............................................... 507 19 Iterators and Allocators ............................................................... 549 20 Strings ......................................................................................... 579 21 Streams ........................................................................................ 605 22 Numerics ..................................................................................... 657 Part IV: Design Using C++ 689 23 Development and Design ............................................................ 691 24 Design and Programming ........................................................... 723 25 Roles of Classes .......................................................................... 765 Appendices 791 A The C++ Grammar ...................................................................... 793 B Compatibility .............................................................................. 815 C Technicalities .............................................................................. 827 Index 869 The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Preface Programming is understanding. ± Kristen Nygaard I find using C++ more enjoyable than ever. C++’s support for design and programming has improved dramatically over the years, and lots of new helpful techniques have been developed for its use. However, C++ is not just fun. Ordinary practical programmers have achieved significant improvements in productivity, maintainability, flexibility, and quality in projects of just about any kind and scale. By now, C++ has fulfilled most of the hopes I originally had for it, and also suc- ceeded at tasks I hadn’t even dreamt of. This book introduces standard C++² and the key programming and design techniques supported by C++. Standard C++ is a far more powerful and polished language than the version of C++ intro- duced by the first edition of this book. New language features such as namespaces, exceptions, templates, and run-time type identification allow many techniques to be applied more directly than was possible before, and the standard library allows the programmer to start from a much higher level than the bare language. About a third of the information in the second edition of this book came from the first. This third edition is the result of a rewrite of even larger magnitude. It offers something to even the most experienced C++ programmer; at the same time, this book is easier for the novice to approach than its predecessors were. The explosion of C++ use and the massive amount of experience accu- mulated as a result makes this possible. The definition of an extensive standard library makes a difference to the way C++ concepts can be presented. As before, this book presents C++ independently of any particular implementation, and as before, the tutorial chapters present language constructs and concepts in a ‘‘bottom up’’ order so that a construct is used only after it has been defined. However, it is much easier to use a well-designed library than it is to understand the details of its implementation. Therefore, the stan- dard library can be used to provide realistic and interesting examples well before a reader can be assumed to understand its inner workings. The standard library itself is also a fertile source of pro- gramming examples and design techniques. __________________ ² ISO/IEC 14882, Standard for the C++ Programming Language. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.vi Preface This book presents every major C++ language feature and the standard library. It is organized around language and library facilities. However, features are presented in the context of their use. That is, the focus is on the language as the tool for design and programming rather than on the lan- guage in itself. This book demonstrates key techniques that make C++ effective and teaches the fundamental concepts necessary for mastery. Except where illustrating technicalities, examples are taken from the domain of systems software. A companion, The Annotated C++ Language Stan- dard, presents the complete language definition together with annotations to make it more compre- hensible. The primary aim of this book is to help the reader understand how the facilities offered by C++ support key programming techniques. The aim is to take the reader far beyond the point where he or she gets code running primarily by copying examples and emulating programming styles from other languages. Only a good understanding of the ideas behind the language facilities leads to mastery. Supplemented by implementation documentation, the information provided is sufficient for completing significant real-world projects. The hope is that this book will help the reader gain new insights and become a better programmer and designer. Acknowledgments In addition to the people mentioned in the acknowledgement sections of the first and second edi- tions, I would like to thank Matt Austern, Hans Boehm, Don Caldwell, Lawrence Crowl, Alan Feuer, Andrew Forrest, David Gay, Tim Griffin, Peter Juhl, Brian Kernighan, Andrew Koenig, Mike Mowbray, Rob Murray, Lee Nackman, Joseph Newcomer, Alex Stepanov, David Vandevo- orde, Peter Weinberger, and Chris Van Wyk for commenting on draft chapters of this third edition. Without their help and suggestions, this book would have been harder to understand, contained more errors, been slightly less complete, and probably been a little bit shorter. I would also like to thank the volunteers on the C++ standards committees who did an immense amount of constructive work to make C++ what it is today. It is slightly unfair to single out indi- viduals, but it would be even more unfair not to mention anyone, so I’d like to especially mention Mike Ball, Dag Br. .uck, Sean Corfield, Ted Goldstein, Kim Knuttila, Andrew Koenig, José e Lajoie, Dmitry Lenkov, Nathan Myers, Martin O’Riordan, Tom Plum, Jonathan Shopiro, John Spicer, Jerry Schwarz, Alex Stepanov, and Mike Vilot, as people who each directly cooperated with me over some part of C++ and its standard library. Murray Hill, New Jersey Bjarne Stroustrup The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Preface to the Second Edition The road goes ever on and on. ± Bilbo Baggins As promised in the first edition of this book, C++ has been evolving to meet the needs of its users. This evolution has been guided by the experience of users of widely varying backgrounds working in a great range of application areas. The C++ user-community has grown a hundredfold during the six years since the first edition of this book; many lessons have been learned, and many techniques have been discovered and/or validated by experience. Some of these experiences are reflected here. The primary aim of the language extensions made in the last six years has been to enhance C++ as a language for data abstraction and object-oriented programming in general and to enhance it as a tool for writing high-quality libraries of user-defined types in particular. A ‘‘high-quality library,’’ is a library that provides a concept to a user in the form of one or more classes that are convenient, safe, and efficient to use. In this context, safe means that a class provides a specific type-safe interface between the users of the library and its providers; efficient means that use of the class does not impose significant overheads in run-time or space on the user compared with hand- written C code. This book presents the complete C++ language. Chapters 1 through 10 give a tutorial introduc- tion; Chapters 11 through 13 provide a discussion of design and software development issues; and, finally, the complete C++ reference manual is included. Naturally, the features added and resolu- tions made since the original edition are integral parts of the presentation. They include refined overloading resolution, memory management facilities, and access control mechanisms, type-safe linkage, c co on ns st t and s st ta at ti ic c member functions, abstract classes, multiple inheritance, templates, and exception handling. C++ is a general-purpose programming language; its core application domain is systems pro- gramming in the broadest sense. In addition, C++ is successfully used in many application areas that are not covered by this label. Implementations of C++ exist from some of the most modest microcomputers to the largest supercomputers and for almost all operating systems. Consequently, this book describes the C++ language itself without trying to explain a particular implementation, programming environment, or library. This book presents many examples of classes that, though useful, should be classified as ‘‘toys.’’ This style of exposition allows general principles and useful techniques to stand out more The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.viii Preface to the Second Edition clearly than they would in a fully elaborated program, where they would be buried in details. Most of the useful classes presented here, such as linked lists, arrays, character strings, matrices, graphics classes, associative arrays, etc., are available in ‘‘bulletproof’’ and/or ‘‘goldplated’’ versions from a wide variety of commercial and non-commercial sources. Many of these ‘‘industrial strength’’ classes and libraries are actually direct and indirect descendants of the toy versions found here. This edition provides a greater emphasis on tutorial aspects than did the first edition of this book. However, the presentation is still aimed squarely at experienced programmers and endeavors not to insult their intelligence or experience. The discussion of design issues has been greatly expanded to reflect the demand for information beyond the description of language features and their immediate use. Technical detail and precision have also been increased. The reference man- ual, in particular, represents many years of work in this direction. The intent has been to provide a book with a depth sufficient to make more than one reading rewarding to most programmers. In other words, this book presents the C++ language, its fundamental principles, and the key tech- niques needed to apply it. Enjoy! Acknowledgments In addition to the people mentioned in the acknowledgements section in the preface to the first edi- tion, I would like to thank Al Aho, Steve Buroff, Jim Coplien, Ted Goldstein, Tony Hansen, Lor- raine Juhl, Peter Juhl, Brian Kernighan, Andrew Koenig, Bill Leggett, Warren Montgomery, Mike Mowbray, Rob Murray, Jonathan Shopiro, Mike Vilot, and Peter Weinberger for commenting on draft chapters of this second edition. Many people influenced the development of C++ from 1985 to 1991. I can mention only a few: Andrew Koenig, Brian Kernighan, Doug McIlroy, and Jonathan Shopiro. Also thanks to the many participants of the ‘‘external reviews’’ of the reference manual drafts and to the people who suffered through the first year of X3J16. Murray Hill, New Jersey Bjarne Stroustrup The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Preface to the First Edition Language shapes the way we think, and determines what we can think about. ± B.L.Whorf C++ is a general purpose programming language designed to make programming more enjoyable for the serious programmer. Except for minor details, C++ is a superset of the C programming lan- guage. In addition to the facilities provided by C, C++ provides flexible and efficient facilities for defining new types. A programmer can partition an application into manageable pieces by defining new types that closely match the concepts of the application. This technique for program construc- tion is often called data abstraction. Objects of some user-defined types contain type information. Such objects can be used conveniently and safely in contexts in which their type cannot be deter- mined at compile time. Programs using objects of such types are often called object based. When used well, these techniques result in shorter, easier to understand, and easier to maintain programs. The key concept in C++ is class. A class is a user-defined type. Classes provide data hiding, guaranteed initialization of data, implicit type conversion for user-defined types, dynamic typing, user-controlled memory management, and mechanisms for overloading operators. C++ provides much better facilities for type checking and for expressing modularity than C does. It also contains improvements that are not directly related to classes, including symbolic constants, inline substitu- tion of functions, default function arguments, overloaded function names, free store management operators, and a reference type. C++ retains C’s ability to deal efficiently with the fundamental objects of the hardware (bits, bytes, words, addresses, etc.). This allows the user-defined types to be implemented with a pleasing degree of efficiency. C++ and its standard libraries are designed for portability. The current implementation will run on most systems that support C. C libraries can be used from a C++ program, and most tools that support programming in C can be used with C++. This book is primarily intended to help serious programmers learn the language and use it for nontrivial projects. It provides a complete description of C++, many complete examples, and many more program fragments. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.x Preface to the First Edition Acknowledgments C++ could never have matured without the constant use, suggestions, and constructive criticism of many friends and colleagues. In particular, Tom Cargill, Jim Coplien, Stu Feldman, Sandy Fraser, Steve Johnson, Brian Kernighan, Bart Locanthi, Doug McIlroy, Dennis Ritchie, Larry Rosler, Jerry Schwarz, and Jon Shopiro provided important ideas for development of the language. Dave Pre- sotto wrote the current implementation of the stream I/O library. In addition, hundreds of people contributed to the development of C++ and its compiler by sending me suggestions for improvements, descriptions of problems they had encountered, and compiler errors. I can mention only a few: Gary Bishop, Andrew Hume, Tom Karzes, Victor Milenkovic, Rob Murray, Leonie Rose, Brian Schmult, and Gary Walker. Many people have also helped with the production of this book, in particular, Jon Bentley, Laura Eaves, Brian Kernighan, Ted Kowalski, Steve Mahaney, Jon Shopiro, and the participants in the C++ course held at Bell Labs, Columbus, Ohio, June 26-27, 1985. Murray Hill, New Jersey Bjarne Stroustrup The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Introduction This introduction gives an overview of the major concepts and features of the C++ pro- gramming language and its standard library. It also provides an overview of this book and explains the approach taken to the description of the language facilities and their use. In addition, the introductory chapters present some background information about C++, the design of C++, and the use of C++. Chapters 1 Notes to the Reader 2 A Tour of C++ 3 A Tour of the Standard Library The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.2 Introduction Introduction ‘‘... and you, Marcus, you have given me many things; now I shall give you this good advice. Be many people. Give up the game of being always Marcus Cocoza. You have worried too much about Marcus Cocoza, so that you have been really his slave and prisoner. You have not done anything without first considering how it would affect Marcus Cocoza’s happiness and prestige. You were always much afraid that Marcus might do a stupid thing, or be bored. What would it really have mattered? All over the world people are doing stupid things ... I should like you to be easy, your lit- tle heart to be light again. You must from now, be more than one, many people, as many as you can think of ...’’ ± Karen Blixen (‘‘The Dreamers’’ from ‘‘Seven Gothic Tales’’ written under the pseudonym Isak Dinesen, Random House, Inc. Copyright, Isac Dinesen, 1934 renewed 1961) The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 1 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Notes to the Reader "The time has come," the Walrus said, "to talk of many things." ± L.Carroll Structure of this book Ð how to learn C++ Ð the design of C++ Ð efficiency and struc- ture Ð philosophical note Ð historical note Ð what C++ is used for Ð C and C++ Ð suggestions for C programmers Ð suggestions for C++ programmers Ð thoughts about programming in C++ Ð advice Ð references. 1.1 The Structure of This Book This book consists of six parts: Introduction: Chapters 1 through 3 give an overview of the C++ language, the key programming styles it supports, and the C++ standard library. Part I: Chapters 4 through 9 provide a tutorial introduction to C++'s built-in types and the basic facilities for constructing programs out of them. Part II: Chapters 10 through 15 are a tutorial introduction to object-oriented and generic pro- gramming using C++. Part III: Chapters 16 through 22 present the C++ standard library. Part IV: Chapters 23 through 25 discuss design and software development issues. Appendices: Appendices A through E provide language-technical details. Chapter 1 provides an overview of this book, some hints about how to use it, and some background information about C++ and its use. You are encouraged to skim through it, read what appears inter- esting, and return to it after reading other parts of the book. Chapters 2 and 3 provide an overview of the major concepts and features of the C++ program- ming language and its standard library. Their purpose is to motivate you to spend time on funda- mental concepts and basic language features by showing what can be expressed using the complete The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.4 Notes to the Reader Chapter 1 C++ language. If nothing else, these chapters should convince you that C++ isn't (just) C and that C++ has come a long way since the first and second editions of this book. Chapter 2 gives a high- level acquaintance with C++. The discussion focuses on the language features supporting data abstraction, object-oriented programming, and generic programming. Chapter 3 introduces the basic principles and major facilities of the standard library. This allows me to use standard library facilities in the following chapters. It also allows you to use library facilities in exercises rather than relying directly on lower-level, built-in features. The introductory chapters provide an example of a general technique that is applied throughout this book: to enable a more direct and realistic discussion of some technique or feature, I occasion- ally present a concept briefly at first and then discuss it in depth later. This approach allows me to present concrete examples before a more general treatment of a topic. Thus, the organization of this book reflects the observation that we usually learn best by progressing from the concrete to the abstract ± even where the abstract seems simple and obvious in retrospect. Part I describes the subset of C++ that supports the styles of programming traditionally done in C or Pascal. It covers fundamental types, expressions, and control structures for C++ programs. Modularity ± as supported by namespaces, source files, and exception handling ± is also discussed. I assume that you are familiar with the fundamental programming concepts used in Part I. For example, I explain C++'s facilities for expressing recursion and iteration, but I do not spend much time explaining how these concepts are useful. Part II describes C++'s facilities for defining and using new types. Concrete and abstract classes (interfaces) are presented here (Chapter 10, Chapter 12), together with operator overloading (Chapter 11), polymorphism, and the use of class hierarchies (Chapter 12, Chapter 15). Chapter 13 presents templates, that is, C++'s facilities for defining families of types and functions. It demon- strates the basic techniques used to provide containers, such as lists, and to support generic pro- gramming. Chapter 14 presents exception handling, discusses techniques for error handling, and presents strategies for fault tolerance. I assume that you either aren't well acquainted with object- oriented programming and generic programming or could benefit from an explanation of how the main abstraction techniques are supported by C++. Thus, I don't just present the language features supporting the abstraction techniques; I also explain the techniques themselves. Part IV goes fur- ther in this direction. Part III presents the C++ standard library. The aim is to provide an understanding of how to use the library, to demonstrate general design and programming techniques, and to show how to extend the library. The library provides containers (such as l li is st t, v ve ec ct to or r, and m ma ap p; Chapter 16, Chapter 17), standard algorithms (such as s so or rt t, f fi in nd d, and m me er rg ge e; Chapter 18, Chapter 19), strings (Chapter 20), Input/Output (Chapter 21), and support for numerical computation (Chapter 22). Part IV discusses issues that arise when C++ is used in the design and implementation of large software systems. Chapter 23 concentrates on design and management issues. Chapter 24 discusses the relation between the C++ programming language and design issues. Chapter 25 presents some ways of using classes in design. Appendix A is C++'s grammar, with a few annotations. Appendix B discusses the relation between C and C++ and between Standard C++ (also called ISO C++ and ANSI C++) and the ver- sions of C++ that preceded it. Appendix C presents some language-technical examples. Appendix D explains the standard library's facilities supporting internationalization. Appendix E discusses the exception-safety guarantees and requirements of the standard library. The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.Section 1.1.1 Examples and References 5 1.1.1 Examples and References This book emphasizes program organization rather than the writing of algorithms. Consequently, I avoid clever or harder-to-understand algorithms. A trivial algorithm is typically better suited to illustrate an aspect of the language definition or a point about program structure. For example, I use a Shell sort where, in real code, a quicksort would be better. Often, reimplementation with a more suitable algorithm is an exercise. In real code, a call of a library function is typically more appropriate than the code used here for illustration of language features. Textbook examples necessarily give a warped view of software development. By clarifying and simplifying the examples, the complexities that arise from scale disappear. I see no substitute for writing realistically-sized programs for getting an impression of what programming and a program- ming language are really like. This book concentrates on the language features, the basic tech- niques from which every program is composed, and the rules for composition. The selection of examples reflects my background in compilers, foundation libraries, and simu- lations. Examples are simplified versions of what is found in real code. The simplification is nec- essary to keep programming language and design points from getting lost in details. There are no ``cute'' examples without counterparts in real code. Wherever possible, I relegated to Appendix C language-technical examples of the sort that use variables named x x and y y, types called A A and B B, and functions called f f() and g g(). In code examples, a proportional-width font is used for identifiers. For example: #i in nc cl lu ud de e i in nt t m ma ai in n() { s st td d: :c co ou ut t << "H He el ll lo o, n ne ew w w wo or rl ld d!\ \n n"; } At first glance, this presentation style will seem ``unnatural'' to programmers accustomed to seeing code in constant-width fonts. However, proportional-width fonts are generally regarded as better than constant-width fonts for presentation of text. Using a proportional-width font also allows me to present code with fewer illogical line breaks. Furthermore, my experiments show that most peo- ple find the new style more readable after a short while. Where possible, the C++ language and library features are presented in the context of their use rather than in the dry manner of a manual. The language features presented and the detail in which they are described reflect my view of what is needed for effective use of C++. A companion, The Annotated C++ Language Standard, authored by Andrew Koenig and myself, is the complete defi- nition of the language together with comments aimed at making it more accessible. Logically, there ought to be another companion, The Annotated C++ Standard Library. However, since both time and my capacity for writing are limited, I cannot promise to produce that. References to parts of this book are of the form §2.3.4 (Chapter 2, section 3, subsection 4), §B.5.6 (Appendix B, subsection 5.6), and §6.6[10] (Chapter 6, exercise 10). Italics are used spar- ingly for emphasis (e.g., ``a string literal is not acceptable''), for first occurrences of important con- cepts (e.g., polymorphism), for nonterminals of the C++ grammar (e.g., for-statement), and for com- ments in code examples. Semi-bold italics are used to refer to identifiers, keywords, and numeric values from code examples (e.g., c co ou un nt te er r, c cl la as ss s, and 1 17 71 12 2). The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.6 Notes to the Reader Chapter 1 1.1.2 Exercises Exercises are found at the ends of chapters. The exercises are mainly of the write-a-program vari- ety. Always write enough code for a solution to be compiled and run with at least a few test cases. The exercises vary considerably in difficulty, so they are marked with an estimate of their diffi- culty. The scale is exponential so that if a (∗1) exercise takes you ten minutes, a (∗2) might take an hour, and a (∗3) might take a day. The time needed to write and test a program depends more on your experience than on the exercise itself. A (∗1) exercise might take a day if you first have to get acquainted with a new computer system in order to run it. On the other hand, a (∗5) exercise might be done in an hour by someone who happens to have the right collection of programs handy. Any book on programming in C can be used as a source of extra exercises for Part I. Any book on data structures and algorithms can be used as a source of exercises for Parts II and III. 1.1.3 Implementation Note The language used in this book is ``pure C++'' as defined in the C++ standard [C++,1998]. There- fore, the examples ought to run on every C++ implementation. The major program fragments in this book were tried using several C++ implementations. Examples using features only recently adopted into C++ didn't compile on every implementation. However, I see no point in mentioning which implementations failed to compile which examples. Such information would soon be out of date because implementers are working hard to ensure that their implementations correctly accept every C++ feature. See Appendix B for suggestions on how to cope with older C++ compilers and with code written for C compilers. 1.2 Learning C++ The most important thing to do when learning C++ is to focus on concepts and not get lost in language-technical details. The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones. For this, an appreciation of programming and design techniques is far more important than an understanding of details; that understanding comes with time and practice. C++ supports a variety of programming styles. All are based on strong static type checking, and most aim at achieving a high level of abstraction and a direct representation of the programmer's ideas. Each style can achieve its aims effectively while maintaining run-time and space efficiency. A programmer coming from a different language (say C, Fortran, Smalltalk, Lisp, ML, Ada, Eiffel, Pascal, or Modula-2) should realize that to gain the benefits of C++, they must spend time learning and internalizing programming styles and techniques suitable to C++. The same applies to pro- grammers used to an earlier and less expressive version of C++. Thoughtlessly applying techniques effective in one language to another typically leads to awk- ward, poorly performing, and hard-to-maintain code. Such code is also most frustrating to write because every line of code and every compiler error message reminds the programmer that the lan- guage used differs from ``the old language.'' You can write in the style of Fortran, C, Smalltalk, etc., in any language, but doing so is neither pleasant nor economical in a language with a different philosophy. Every language can be a fertile source of ideas of how to write C++ programs. The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.Section 1.2 Learning C++ 7 However, ideas must be transformed into something that fits with the general structure and type system of C++ in order to be effective in the different context. Over the basic type system of a lan- guage, only Pyrrhic victories are possible. C++ supports a gradual approach to learning. How you approach learning a new programming language depends on what you already know and what you aim to learn. There is no one approach that suits everyone. My assumption is that you are learning C++ to become a better programmer and designer. That is, I assume that your purpose in learning C++ is not simply to learn a new syn- tax for doing things the way you used to, but to learn new and better ways of building systems. This has to be done gradually because acquiring any significant new skill takes time and requires practice. Consider how long it would take to learn a new natural language well or to learn to play a new musical instrument well. Becoming a better system designer is easier and faster, but not as much easier and faster as most people would like it to be. It follows that you will be using C++ ± often for building real systems ± before understanding every language feature and technique. By supporting several programming paradigms (Chapter 2), C++ supports productive programming at several levels of expertise. Each new style of program- ming adds another tool to your toolbox, but each is effective on its own and each adds to your effectiveness as a programmer. C++ is organized so that you can learn its concepts in a roughly lin- ear order and gain practical benefits along the way. This is important because it allows you to gain benefits roughly in proportion to the effort expended. In the continuing debate on whether one needs to learn C before C++, I am firmly convinced that it is best to go directly to C++. C++ is safer, more expressive, and reduces the need to focus on low-level techniques. It is easier for you to learn the trickier parts of C that are needed to compen- sate for its lack of higher-level facilities after you have been exposed to the common subset of C and C++ and to some of the higher-level techniques supported directly in C++. Appendix B is a guide for programmers going from C++ to C, say, to deal with legacy code. Several independently developed and distributed implementations of C++ exist. A wealth of tools, libraries, and software development environments are also available. A mass of textbooks, manuals, journals, newsletters, electronic bulletin boards, mailing lists, conferences, and courses are available to inform you about the latest developments in C++, its use, tools, libraries, implemen- tations, etc. If you plan to use C++ seriously, I strongly suggest that you gain access to such sources. Each has its own emphasis and bias, so use at least two. For example, see [Barton,1994], [Booch,1994], [Henricson,1997], [Koenig,1997], [Martin,1995]. 1.3 The Design of C++ Simplicity was an important design criterion: where there was a choice between simplifying the language definition and simplifying the compiler, the former was chosen. However, great impor- tance was attached to retaining a high degree of compatibility with C [Koenig,1989] [Strous- trup,1994] (Appendix B); this precluded cleaning up the C syntax. C++ has no built-in high-level data types and no high-level primitive operations. For example, the C++ language does not provide a matrix type with an inversion operator or a string type with a concatenation operator. If a user wants such a type, it can be defined in the language itself. In fact, defining a new general-purpose or application-specific type is the most fundamental programming The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.8 Notes to the Reader Chapter 1 activity in C++. A well-designed user-defined type differs from a built-in type only in the way it is defined, not in the way it is used. The C++ standard library described in Part III provides many examples of such types and their uses. From a user's point of view, there is little difference between a built-in type and a type provided by the standard library. Features that would incur run-time or memory overheads even when not used were avoided in the design of C++. For example, constructs that would make it necessary to store ``housekeeping information'' in every object were rejected, so if a user declares a structure consisting of two 16-bit quantities, that structure will fit into a 32-bit register. C++ was designed to be used in a traditional compilation and run-time environment, that is, the C programming environment on the UNIX system. Fortunately, C++ was never restricted to UNIX; it simply used UNIX and C as a model for the relationships between language, libraries, compilers, linkers, execution environments, etc. That minimal model helped C++ to be successful on essen- tially every computing platform. There are, however, good reasons for using C++ in environments that provide significantly more support. Facilities such as dynamic loading, incremental compila- tion, and a database of type definitions can be put to good use without affecting the language. C++ type-checking and data-hiding features rely on compile-time analysis of programs to pre- vent accidental corruption of data. They do not provide secrecy or protection against someone who is deliberately breaking the rules. They can, however, be used freely without incurring run-time or space overheads. The idea is that to be useful, a language feature must not only be elegant; it must also be affordable in the context of a real program. For a systematic and detailed description of the design of C++, see [Stroustrup,1994]. 1.3.1 Efficiency and Structure C++ was developed from the C programming language and, with few exceptions, retains C as a subset. The base language, the C subset of C++, is designed to ensure a very close correspondence between its types, operators, and statements and the objects that computers deal with directly: num- bers, characters, and addresses. Except for the n ne ew w, d de el le et te e, t ty yp pe ei id d, d dy yn na am mi ic c_ _c ca as st t, and t th hr ro ow w oper- ators and the try-block, individual C++ expressions and statements need no run-time support. C++ can use the same function call and return sequences as C ± or more efficient ones. When even such relatively efficient mechanisms are too expensive, a C++ function can be substituted inline, so that we can enjoy the notational convenience of functions without run-time overhead. One of the original aims for C was to replace assembly coding for the most demanding systems programming tasks. When C++ was designed, care was taken not to compromise the gains in this area. The difference between C and C++ is primarily in the degree of emphasis on types and struc- ture. C is expressive and permissive. C++ is even more expressive. However, to gain that increase in expressiveness, you must pay more attention to the types of objects. Knowing the types of objects, the compiler can deal correctly with expressions when you would otherwise have had to specify operations in painful detail. Knowing the types of objects also enables the compiler to detect errors that would otherwise persist until testing ± or even later. Note that using the type sys- tem to check function arguments, to protect data from accidental corruption, to provide new types, to provide new operators, etc., does not increase run-time or space overheads in C++. The emphasis on structure in C++ reflects the increase in the scale of programs written since C was designed. You can make a small program (say, 1,000 lines) work through brute force even The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.Section 1.3.1 Efficiency and Structure 9 when breaking every rule of good style. For a larger program, this is simply not so. If the structure of a 100,000-line program is bad, you will find that new errors are introduced as fast as old ones are removed. C++ was designed to enable larger programs to be structured in a rational way so that it would be reasonable for a single person to cope with far larger amounts of code. In addition, the aim was to have an average line of C++ code express much more than the average line of C or Pas- cal code. C++ has by now been shown to over-fulfill these goals. Not every piece of code can be well-structured, hardware-independent, easy-to-read, etc. C++ possesses features that are intended for manipulating hardware facilities in a direct and efficient way without regard for safety or ease of comprehension. It also possesses facilities for hiding such code behind elegant and safe interfaces. Naturally, the use of C++ for larger programs leads to the use of C++ by groups of program- mers. C++'s emphasis on modularity, strongly typed interfaces, and flexibility pays off here. C++ has as good a balance of facilities for writing large programs as any language has. However, as programs get larger, the problems associated with their development and maintenance shift from being language problems to more global problems of tools and management. Part IV explores some of these issues. This book emphasizes techniques for providing general-purpose facilities, generally useful types, libraries, etc. These techniques will serve programmers of small programs as well as pro- grammers of large ones. Furthermore, because all nontrivial programs consist of many semi- independent parts, the techniques for writing such parts serve programmers of all applications. You might suspect that specifying a program by using a more detailed type structure would lead to a larger program source text. With C++, this is not so. A C++ program declaring function argu- ment types, using classes, etc., is typically a bit shorter than the equivalent C program not using these facilities. Where libraries are used, a C++ program will appear much shorter than its C equiv- alent, assuming, of course, that a functioning C equivalent could have been built. 1.3.2 Philosophical Note A programming language serves two related purposes: it provides a vehicle for the programmer to specify actions to be executed, and it provides a set of concepts for the programmer to use when thinking about what can be done. The first purpose ideally requires a language that is ``close to the machine'' so that all important aspects of a machine are handled simply and efficiently in a way that is reasonably obvious to the programmer. The C language was primarily designed with this in mind. The second purpose ideally requires a language that is ``close to the problem to be solved'' so that the concepts of a solution can be expressed directly and concisely. The facilities added to C to create C++ were primarily designed with this in mind. The connection between the language in which we think/program and the problems and solu- tions we can imagine is very close. For this reason, restricting language features with the intent of eliminating programmer errors is at best dangerous. As with natural languages, there are great ben- efits from being at least bilingual. A language provides a programmer with a set of conceptual tools; if these are inadequate for a task, they will simply be ignored. Good design and the absence of errors cannot be guaranteed merely by the presence or the absence of specific language features. The type system should be especially helpful for nontrivial tasks. The C++ class concept has, in fact, proven itself to be a powerful conceptual tool. The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.10 Notes to the Reader Chapter 1 1.4 Historical Note I invented C++, wrote its early definitions, and produced its first implementation. I chose and for- mulated the design criteria for C++, designed all its major facilities, and was responsible for the processing of extension proposals in the C++ standards committee. Clearly, C++ owes much to C [Kernighan,1978]. Except for closing a few serious loopholes in the type system (see Appendix B), C is retained as a subset. I also retained C's emphasis on facili- ties that are low-level enough to cope with the most demanding systems programming tasks. C in turn owes much to its predecessor BCPL [Richards,1980]; in fact, BCPL's / / comment convention was (re)introduced in C++. The other main source of inspiration for C++ was Simula67 [Dahl,1970] [Dahl,1972]; the class concept (with derived classes and virtual functions) was bor- rowed from it. C++'s facility for overloading operators and the freedom to place a declaration wherever a statement can occur resembles Algol68 [Woodward,1974]. Since the original edition of this book, the language has been extensively reviewed and refined. The major areas for revision were overload resolution, linking, and memory management facilities. In addition, several minor changes were made to increase C compatibility. Several generalizations and a few major extensions were added: these included multiple inheritance, s st ta at ti ic c member func- tions, c co on ns st t member functions, p pr ro ot te ec ct te ed d members, templates, exception handling, run-time type identification, and namespaces. The overall theme of these extensions and revisions was to make C++ a better language for writing and using libraries. The evolution of C++ is described in [Strous- trup,1994]. The template facility was primarily designed to support statically typed containers (such as lists, vectors, and maps) and to support elegant and efficient use of such containers (generic program- ming). A key aim was to reduce the use of macros and casts (explicit type conversion). Templates were partly inspired by Ada's generics (both their strengths and their weaknesses) and partly by Clu's parameterized modules. Similarly, the C++ exception-handling mechanism was inspired partly by Ada [Ichbiah,1979], Clu [Liskov,1979], and ML [Wikstr. .om,1987]. Other developments in the 1985 to 1995 time span ± such as multiple inheritance, pure virtual functions, and name- spaces ± were primarily generalizations driven by experience with the use of C++ rather than ideas imported from other languages. Earlier versions of the language, collectively known as ``C with Classes'' [Stroustrup,1994], have been in use since 1980. The language was originally invented because I wanted to write some event-driven simulations for which Simula67 would have been ideal, except for efficiency consid- erations. ``C with Classes'' was used for major projects in which the facilities for writing programs that use minimal time and space were severely tested. It lacked operator overloading, references, virtual functions, templates, exceptions, and many details. The first use of C++ outside a research organization started in July 1983. The name C++ (pronounced ``see plus plus'') was coined by Rick Mascitti in the summer of 1983. The name signifies the evolutionary nature of the changes from C; ``++'' is the C increment operator. The slightly shorter name ``C+'' is a syntax error; it has also been used as the name of an unrelated language. Connoisseurs of C semantics find C++ inferior to ++C. The language is not called D, because it is an extension of C, and it does not attempt to remedy problems by removing features. For yet another interpretation of the name C++, see the appendix of [Orwell,1949]. C++ was designed primarily so that my friends and I would not have to program in assembler, The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.Section 1.4 Historical Note 11 C, or various modern high-level languages. Its main purpose was to make writing good programs easier and more pleasant for the individual programmer. In the early years, there was no C++ paper design; design, documentation, and implementation went on simultaneously. There was no ``C++ project'' either, or a ``C++ design committee.'' Throughout, C++ evolved to cope with problems encountered by users and as a result of discussions between my friends, my colleagues, and me. Later, the explosive growth of C++ use caused some changes. Sometime during 1987, it became clear that formal standardization of C++ was inevitable and that we needed to start prepar- ing the ground for a standardization effort [Stroustrup,1994]. The result was a conscious effort to maintain contact between implementers of C++ compilers and major users through paper and elec- tronic mail and through face-to-face meetings at C++ conferences and elsewhere. AT&T Bell Laboratories made a major contribution to this by allowing me to share drafts of revised versions of the C++ reference manual with implementers and users. Because many of these people work for companies that could be seen as competing with AT&T, the significance of this contribution should not be underestimated. A less enlightened company could have caused major problems of language fragmentation simply by doing nothing. As it happened, about a hundred individuals from dozens of organizations read and commented on what became the generally accepted reference manual and the base document for the ANSI C++ standardization effort. Their names can be found in The Annotated C++ Reference Manual [Ellis,1989]. Finally, the X3J16 committee of ANSI was convened in December 1989 at the initiative of Hewlett-Packard. In June 1991, this ANSI (American national) standardization of C++ became part of an ISO (international) standardization effort for C++. From 1990, these joint C++ standards committees have been the main forum for the evolution of C++ and the refinement of its definition. I served on these commit- tees throughout. In particular, as the chairman of the working group for extensions, I was directly responsible for the handling of proposals for major changes to C++ and the addition of new lan- guage features. An initial draft standard for public review was produced in April 1995. The ISO C++ standard (ISO/IEC 14882) was ratified in 1998. C++ evolved hand-in-hand with some of the key classes presented in this book. For example, I designed complex, vector, and stack classes together with the operator overloading mechanisms. String and list classes were developed by Jonathan Shopiro and me as part of the same effort. Jonathan's string and list classes were the first to see extensive use as part of a library. The string class from the standard C++ library has its roots in these early efforts. The task library described in [Stroustrup,1987] and in §12.7[11] was part of the first ``C with Classes'' program ever written. I wrote it and its associated classes to support Simula-style simulations. The task library has been revised and reimplemented, notably by Jonathan Shopiro, and is still in extensive use. The stream library as described in the first edition of this book was designed and implemented by me. Jerry Schwarz transformed it into the iostreams library (Chapter 21) using Andrew Koenig's manipulator technique (§21.4.6) and other ideas. The iostreams library was further refined during standardiza- tion, when the bulk of the work was done by Jerry Schwarz, Nathan Myers, and Norihiro Kumagai. The development of the template facility was influenced by the v ve ec ct to or r, m ma ap p, l li is st t, and s so or rt t tem- plates devised by Andrew Koenig, Alex Stepanov, me, and others. In turn, Alex Stepanov's work on generic programming using templates led to the containers and algorithms parts of the standard C++ library (§16.3, Chapter 17, Chapter 18, §19.2). The v va al la ar rr ra ay y library for numerical computa- tion (Chapter 22) is primarily the work of Kent Budge. The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.12 Notes to the Reader Chapter 1 1.5 Use of C++ C++ is used by hundreds of thousands of programmers in essentially every application domain. This use is supported by about a dozen independent implementations, hundreds of libraries, hun- dreds of textbooks, several technical journals, many conferences, and innumerable consultants. Training and education at a variety of levels are widely available. Early applications tended to have a strong systems programming flavor. For example, several major operating systems have been written in C++ [Campbell,1987] [Rozier,1988] [Hamilton,1993] [Berg,1995] [Parrington,1995] and many more have key parts done in C++. I considered uncom- promising low-level efficiency essential for C++. This allows us to use C++ to write device drivers and other software that rely on direct manipulation of hardware under real-time constraints. In such code, predictability of performance is at least as important as raw speed. Often, so is compactness of the resulting system. C++ was designed so that every language feature is usable in code under severe time and space constraints [Stroustrup,1994,§4.5]. Most applications have sections of code that are critical for acceptable performance. However, the largest amount of code is not in such sections. For most code, maintainability, ease of exten- sion, and ease of testing is key. C++'s support for these concerns has led to its widespread use where reliability is a must and in areas where requirements change significantly over time. Exam- ples are banking, trading, insurance, telecommunications, and military applications. For years, the central control of the U.S. long-distance telephone system has relied on C++ and every 800 call (that is, a call paid for by the called party) has been routed by a C++ program [Kamath,1993]. Many such applications are large and long-lived. As a result, stability, compatibility, and scalabil- ity have been constant concerns in the development of C++. Million-line C++ programs are not uncommon. Like C, C++ wasn't specifically designed with numerical computation in mind. However, much numerical, scientific, and engineering computation is done in C++. A major reason for this is that traditional numerical work must often be combined with graphics and with computations relying on data structures that don't fit into the traditional Fortran mold [Budge,1992] [Barton,1994]. Graph- ics and user interfaces are areas in which C++ is heavily used. Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used C++ because the primary user inter- faces of these systems are C++ programs. In addition, some of the most popular libraries support- ing X for UNIX are written in C++. Thus, C++ is a common choice for the vast number of applica- tions in which the user interface is a major part. All of this points to what may be C++'s greatest strength: its ability to be used effectively for applications that require work in a variety of application areas. It is quite common to find an appli- cation that involves local and wide-area networking, numerics, graphics, user interaction, and data- base access. Traditionally, such application areas have been considered distinct, and they have most often been served by distinct technical communities using a variety of programming lan- guages. However, C++ has been widely used in all of those areas. Furthermore, it is able to coexist with code fragments and programs written in other languages. C++ is widely used for teaching and research. This has surprised some who ± correctly ± point out that C++ isn't the smallest or cleanest language ever designed. It is, however ± clean enough for successful teaching of basic concepts, ± realistic, efficient, and flexible enough for demanding projects, The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.Section 1.5 Use of C++ 13 ± available enough for organizations and collaborations relying on diverse development and execution environments, ± comprehensive enough to be a vehicle for teaching advanced concepts and techniques, and ± commercial enough to be a vehicle for putting what is learned into non-academic use. C++ is a language that you can grow with. 1.6 C and C++ C was chosen as the base language for C++ because it [1] is versatile, terse, and relatively low-level; [2] is adequate for most systems programming tasks; [3] runs everywhere and on everything; and [4] fits into the UNIX programming environment. C has its problems, but a language designed from scratch would have some too, and we know C's problems. Importantly, working with C enabled ``C with Classes'' to be a useful (if awkward) tool within months of the first thought of adding Simula-like classes to C. As C++ became more widely used, and as the facilities it provided over and above those of C became more significant, the question of whether to retain compatibility was raised again and again. Clearly some problems could be avoided if some of the C heritage was rejected (see, e.g., [Sethi,1981]). This was not done because [1] there are millions of lines of C code that might benefit from C++, provided that a complete rewrite from C to C++ were unnecessary; [2] there are millions of lines of library functions and utility software code written in C that could be used from/on C++ programs provided C++ were link-compatible with and syntacti- cally very similar to C; [3] there are hundreds of thousands of programmers who know C and therefore need only learn to use the new features of C++ and not relearn the basics; and [4] C++ and C will be used on the same systems by the same people for years, so the differ- ences should be either very large or very small so as to minimize mistakes and confusion. The definition of C++ has been revised to ensure that a construct that is both legal C and legal C++ has the same meaning in both languages (with a few minor exceptions; see §B.2). The C language has itself evolved, partly under the influence of the development of C++ [Rosler,1984]. The ANSI C standard [C,1990] contains a function declaration syntax borrowed from ``C with Classes.'' Borrowing works both ways. For example, the v vo oi id d* pointer type was invented for ANSI C and first implemented in C++. As promised in the first edition of this book, the definition of C++ has been reviewed to remove gratuitous incompatibilities; C++ is now more compatible with C than it was originally. The ideal was for C++ to be as close to ANSI C as possi- ble ± but no closer [Koenig,1989]. One hundred percent compatibility was never a goal because that would compromise type safety and the smooth integration of user-defined and built-in types. Knowing C is not a prerequisite for learning C++. Programming in C encourages many tech- niques and tricks that are rendered unnecessary by C++ language features. For example, explicit type conversion (casting) is less frequently needed in C++ than it is in C (§1.6.1). However, good C programs tend to be C++ programs. For example, every program in Kernighan and Ritchie, The The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.14 Notes to the Reader Chapter 1 C Programming Language (2nd Edition) [Kernighan,1988], is a C++ program. Experience with any statically typed language will be a help when learning C++. 1.6.1 Suggestions for C Programmers The better one knows C, the harder it seems to be to avoid writing C++ in C style, thereby losing some of the potential benefits of C++. Please take a look at Appendix B, which describes the dif- ferences between C and C++. Here are a few pointers to the areas in which C++ has better ways of doing something than C has: [1] Macros are almost never necessary in C++. Use c co on ns st t (§5.4) or e en nu um m (§4.8) to define mani- fest constants, i in nl li in ne e (§7.1.1) to avoid function-calling overhead, t te em mp pl la at te es (Chapter 13) to specify families of functions and types, and n na am me es sp pa ac ce es (§8.2) to avoid name clashes. [2] Don't declare a variable before you need it so that you can initialize it immediately. A declaration can occur anywhere a statement can (§6.3.1), in for-statement initializers (§6.3.3), and in conditions (§6.3.2.1). [3] Don't use m ma al ll lo oc c(). The n ne ew w operator (§6.2.6) does the same job better, and instead of r re ea al ll lo oc c(), try a v ve ec ct to or r (§3.8). [4] Try to avoid v vo oi id d*, pointer arithmetic, unions, and casts, except deep within the implemen- tation of some function or class. In most cases, a cast is an indication of a design error. If you must use an explicit type conversion, try using one of the ``new casts'' (§6.2.7) for a more precise statement of what you are trying to do. [5] Minimize the use of arrays and C-style strings. The C++ standard library s st tr ri in ng g (§3.5) and v ve ec ct to or r (§3.7.1) classes can often be used to simplify programming compared to traditional C style. In general, try not to build yourself what has already been provided by the standard library. To obey C linkage conventions, a C++ function must be declared to have C linkage (§9.2.4). Most important, try thinking of a program as a set of interacting concepts represented as classes and objects, instead of as a bunch of data structures with functions twiddling their bits. 1.6.2 Suggestions for C++ Programmers By now, many people have been using C++ for a decade. Many more are using C++ in a single environment and have learned to live with the restrictions imposed by early compilers and first- generation libraries. Often, what an experienced C++ programmer has failed to notice over the years is not the introduction of new features as such, but rather the changes in relationships between features that make fundamental new programming techniques feasible. In other words, what you didn't think of when first learning C++ or found impractical just might be a superior approach today. You find out only by re-examining the basics. Read through the chapters in order. If you already know the contents of a chapter, you can be through in minutes. If you don't already know the contents, you'll have learned something unex- pected. I learned a fair bit writing this book, and I suspect that hardly any C++ programmer knows every feature and technique presented. Furthermore, to use the language well, you need a perspec- tive that brings order to the set of features and techniques. Through its organization and examples, this book offers such a perspective. The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.Section 1.7 Thinking about Programming in C++ 15 1.7 Thinking about Programming in C++ Ideally, you approach the task of designing a program in three stages. First, you gain a clear under- standing of the problem (analysis), then you identify the key concepts involved in a solution (design), and finally you express that solution in a program (programming). However, the details of the problem and the concepts of the solution often become clearly understood only through the effort to express them in a program and trying to get it to run acceptably. This is where the choice of programming language matters. In most applications, there are concepts that are not easily represented as one of the fundamental types or as a function without associated data. Given such a concept, declare a class to represent it in the program. A C++ class is a type. That is, it specifies how objects of its class behave: how they are created, how they can be manipulated, and how they are destroyed. A class may also specify how objects are represented, although in the early stages of the design of a program that should not be the major concern. The key to writing good programs is to design classes so that each cleanly represents a single concept. Often, this means that you must focus on questions such as: How are objects of this class created? Can objects of this class be copied and/or destroyed? What opera- tions can be applied to such objects? If there are no good answers to such questions, the concept probably wasn't ``clean'' in the first place. It might then be a good idea to think more about the problem and its proposed solution instead of immediately starting to ``code around'' the problems. The concepts that are easiest to deal with are the ones that have a traditional mathematical for- malism: numbers of all sorts, sets, geometric shapes, etc. Text-oriented I/O, strings, basic contain- ers, the fundamental algorithms on such containers, and some mathematical classes are part of the standard C++ library (Chapter 3, §16.1.2). In addition, a bewildering variety of libraries supporting general and domain-specific concepts are available. A concept does not exist in a vacuum; there are always clusters of related concepts. Organizing the relationship between classes in a program ± that is, determining the exact relationship between the different concepts involved in a solution ± is often harder than laying out the individual classes in the first place. The result had better not be a muddle in which every class (concept) depends on every other. Consider two classes, A and B. Relationships such as ``A calls functions from B,'' ``A creates Bs,'' and ``A has a B member'' seldom cause major problems, while relationships such as ``A uses data from B'' can typically be eliminated. One of the most powerful intellectual tools for managing complexity is hierarchical ordering, that is, organizing related concepts into a tree structure with the most general concept as the root. In C++, derived classes represent such structures. A program can often be organized as a set of trees or directed acyclic graphs of classes. That is, the programmer specifies a number of base classes, each with its own set of derived classes. Virtual functions (§2.5.5, §12.2.6) can often be used to define operations for the most general version of a concept (a base class). When necessary, the interpretation of these operations can be refined for particular special cases (derived classes). Sometimes even a directed acyclic graph seems insufficient for organizing the concepts of a program; some concepts seem to be inherently mutually dependent. In that case, we try to localize cyclic dependencies so that they do not affect the overall structure of the program. If you cannot eliminate or localize such mutual dependencies, then you are most likely in a predicament that no programming language can help you out of. Unless you can conceive of some easily stated rela- tionships between the basic concepts, the program is likely to become unmanageable. The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.16 Notes to the Reader Chapter 1 One of the best tools for untangling dependency graphs is the clean separation of interface and implementation. Abstract classes (§2.5.4, §12.3) are C++'s primary tool for doing that. Another form of commonality can be expressed through templates (§2.7, Chapter 13). A class template specifies a family of classes. For example, a list template specifies ``list of T,'' where ``T'' can be any type. Thus, a template is a mechanism for specifying how one type is generated given another type as an argument. The most common templates are container classes such as lists, vectors, and associative arrays (maps) and the fundamental algorithms using such containers. It is usually a mistake to express parameterization of a class and its associated functions with a type using inheritance. It is best done using templates. Remember that much programming can be simply and clearly done using only primitive types, data structures, plain functions, and a few library classes. The whole apparatus involved in defin- ing new types should not be used except when there is a real need. The question ``How does one write good programs in C++?'' is very similar to the question ``How does one write good English prose?'' There are two answers: ``Know what you want to say'' and ``Practice. Imitate good writing.'' Both appear to be as appropriate for C++ as they are for English ± and as hard to follow. 1.8 Advice Here is a set of ``rules'' you might consider while learning C++. As you get more proficient you can evolve them into something suitable for your kind of applications and your style of program- ming. They are deliberately very simple, so they lack detail. Don't take them too literally. To write a good program takes intelligence, taste, and patience. You are not going to get it right the first time. Experiment! [1] When you program, you create a concrete representation of the ideas in your solution to some problem. Let the structure of the program reflect those ideas as directly as possible: [a] If you can think of ``it'' as a separate idea, make it a class. [b] If you can think of ``it'' as a separate entity, make it an object of some class. [c] If two classes have a common interface, make that interface an abstract class. [d] If the implementations of two classes have something significant in common, make that commonality a base class. [e] If a class is a container of objects, make it a template. [f] If a function implements an algorithm for a container, make it a template function imple- menting the algorithm for a family of containers. [g] If a set of classes, templates, etc., are logically related, place them in a common namespace. [2] When you define either a class that does not implement either a mathematical entity like a matrix or a complex number or a low-level type such as a linked list: [a] Don't use global data (use members). [b] Don't use global functions. [c] Don't use public data members. [d] Don't use friends, except to avoid [a] or [c]. [e] Don't put a ``type field'' in a class; use virtual functions. [f] Don't use inline functions, except as a significant optimization. The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.Section 1.8 Advice 17 More specific or detailed rules of thumb can be found in the ``Advice'' section of each chapter. Remember, this advice is only rough rules of thumb, not immutable laws. A piece of advice should be applied only ``where reasonable.'' There is no substitute for intelligence, experience, common sense, and good taste. I find rules of the form ``never do this'' unhelpful. Consequently, most advice is phrased as suggestions of what to do, while negative suggestions tend not to be phrased as absolute prohibi- tions. I know of no major feature of C++ that I have not seen put to good use. The ``Advice'' sec- tions do not contain explanations. Instead, each piece of advice is accompanied by a reference to the appropriate section of the book. Where negative advice is given, that section usually provides a suggested alternative. 1.8.1 References There are few direct references in the text, but here is a short list of books and papers that are men- tioned directly or indirectly. [Barton,1994] John J. Barton and Lee R. Nackman: Scientific and Engineering C++. Addison-Wesley. Reading, Mass. 1994. ISBN 0-201-53393-6. [Berg,1995] William Berg, Marshall Cline, and Mike Girou: Lessons Learned from the OS/400 OO Project. CACM. Vol. 38 No. 10. October 1995. [Booch,1994] Grady Booch: Object-Oriented Analysis and Design. Benjamin/Cummings. Menlo Park, Calif. 1994. ISBN 0-8053-5340-2. [Budge,1992] Kent Budge, J. S. Perry, and A. C. Robinson: High-Performance Scientific Computation using C++. Proc. USENIX C++ Conference. Portland, Oregon. August 1992. [C,1990] X3 Secretariat: Standard ± The C Language. X3J11/90-013. ISO Standard ISO/IEC 9899. Computer and Business Equipment Manufacturers Association. Washington, DC, USA. [C++,1998] X3 Secretariat: International Standard ± The C++ Language. X3J16-14882. Information Technology Council (NSITC). Washington, DC, USA. [Campbell,1987] Roy Campbell, et al.: The Design of a Multiprocessor Operating System. Proc. USENIX C++ Conference. Santa Fe, New Mexico. November 1987. [Coplien,1995] James O. Coplien and Douglas C. Schmidt (editors): Pattern Languages of Program Design. Addison-Wesley. Reading, Mass. 1995. ISBN 0-201- 60734-4. [Dahl,1970] O-J. Dahl, B. Myrhaug, and K. Nygaard: SIMULA Common Base Language. Norwegian Computing Center S-22. Oslo, Norway. 1970. [Dahl,1972] O-J. Dahl and C. A. R. Hoare: Hierarchical Program Construction in Struc- tured Programming. Academic Press, New York. 1972. [Ellis,1989] Margaret A. Ellis and Bjarne Stroustrup: The Annotated C++ Reference Man- ual. Addison-Wesley. Reading, Mass. 1990. ISBN 0-201-51459-1. [Gamma,1995] Erich Gamma, et al.: Design Patterns. Addison-Wesley. Reading, Mass. 1995. ISBN 0-201-63361-2. [Goldberg,1983] A. Goldberg and D. Robson: SMALLTALK-80 ± The Language and Its Imple- mentation. Addison-Wesley. Reading, Mass. 1983. The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.18 Notes to the Reader Chapter 1 [Griswold,1970] R. E. Griswold, et al.: The Snobol4 Programming Language. Prentice-Hall. Englewood Cliffs, New Jersey. 1970. [Griswold,1983] R. E. Griswold and M. T. Griswold: The ICON Programming Language. Prentice-Hall. Englewood Cliffs, New Jersey. 1983. [Hamilton,1993] G. Hamilton and P. Kougiouris: The Spring Nucleus: A Microkernel for Objects. Proc. 1993 Summer USENIX Conference. USENIX. [Henricson,1997] Mats Henricson and Erik Nyquist: Industrial Strength C++: Rules and Recom- mendations. Prentice-Hall. Englewood Cliffs, New Jersey. 1997. ISBN 0- 13-120965-5. [Ichbiah,1979] Jean D. Ichbiah, et al.: Rationale for the Design of the ADA Programming Lan- guage. SIGPLAN Notices. Vol. 14 No. 6. June 1979. [Kamath,1993] Yogeesh H. Kamath, Ruth E. Smilan, and Jean G. Smith: Reaping Benefits with Object-Oriented Technology. AT&T Technical Journal. Vol. 72 No. 5. September/October 1993. [Kernighan,1978] Brian W. Kernighan and Dennis M. Ritchie: The C Programming Language. Prentice-Hall. Englewood Cliffs, New Jersey. 1978. [Kernighan,1988] Brian W. Kernighan and Dennis M. Ritchie: The C Programming Language (Second Edition). Prentice-Hall. Englewood Cliffs, New Jersey. 1988. ISBN 0-13-110362-8. [Koenig,1989] Andrew Koenig and Bjarne Stroustrup: C++: As close to C as possible ± but no closer. The C++ Report. Vol. 1 No. 7. July 1989. [Koenig,1997] Andrew Koenig and Barbara Moo: Ruminations on C++. Addison Wesley Longman. Reading, Mass. 1997. ISBN 0-201-42339-1. [Knuth,1968] Donald Knuth: The Art of Computer Programming. Addison-Wesley. Read- ing, Mass. [Liskov,1979] Barbara Liskov et al.: Clu Reference Manual. MIT/LCS/TR-225. MIT Cam- bridge. Mass. 1979. [Martin,1995] Robert C. Martin: Designing Object-Oriented C++ Applications Using the Booch Method. Prentice-Hall. Englewood Cliffs, New Jersey. 1995. ISBN 0-13-203837-4. [Orwell,1949] George Orwell: 1984. Secker and Warburg. London. 1949. [Parrington,1995] Graham Parrington et al.: The Design and Implementation of Arjuna. Com- puter Systems. Vol. 8 No. 3. Summer 1995. [Richards,1980] Martin Richards and Colin Whitby-Strevens: BCPL ± The Language and Its Compiler. Cambridge University Press, Cambridge. England. 1980. ISBN 0-521-21965-5. [Rosler,1984] L. Rosler: The Evolution of C ± Past and Future. AT&T Bell Laboratories Technical Journal. Vol. 63 No. 8. Part 2. October 1984. [Rozier,1988] M. Rozier, et al.: CHORUS Distributed Operating Systems. Computing Sys- tems. Vol. 1 No. 4. Fall 1988. [Sethi,1981] Ravi Sethi: Uniform Syntax for Type Expressions and Declarations. Software Practice & Experience. Vol. 11. 1981. [Stepanov,1994] Alexander Stepanov and Meng Lee: The Standard Template Library. HP Labs Technical Report HPL-94-34 (R. 1). August, 1994. The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.Section 1.8.1 References 19 [Stroustrup,1986] Bjarne Stroustrup: The C++ Programming Language. Addison-Wesley. Reading, Mass. 1986. ISBN 0-201-12078-X. [Stroustrup,1987] Bjarne Stroustrup and Jonathan Shopiro: A Set of C Classes for Co-Routine Style Programming. Proc. USENIX C++ Conference. Santa Fe, New Mexico. November 1987. [Stroustrup,1991] Bjarne Stroustrup: The C++ Programming Language (Second Edition). Addison-Wesley. Reading, Mass. 1991. ISBN 0-201-53992-6. [Stroustrup,1994] Bjarne Stroustrup: The Design and Evolution of C++. Addison-Wesley. Read- ing, Mass. 1994. ISBN 0-201-54330-3. [Tarjan,1983] Robert E. Tarjan: Data Structures and Network Algorithms. Society for Indus- trial and Applied Mathematics. Philadelphia, Penn. 1983. ISBN 0-898- 71187-8. [Unicode,1996] The Unicode Consortium: The Unicode Standard, Version 2.0. Addison- Wesley Developers Press. Reading, Mass. 1996. ISBN 0-201-48345-9. [UNIX,1985] UNIX Time-Sharing System: Programmer's Manual. Research Version, Tenth Edition. AT&T Bell Laboratories, Murray Hill, New Jersey. February 1985. [Wilson,1996] Gregory V. Wilson and Paul Lu (editors): Parallel Programming Using C++. The MIT Press. Cambridge. Mass. 1996. ISBN 0-262-73118-5. [Wikstr. .om,1987] AÊ ke Wikstr. .om: Functional Programming Using ML. Prentice-Hall. Engle- wood Cliffs, New Jersey. 1987. [Woodward,1974] P. M. Woodward and S. G. Bond: Algol 68-R Users Guide. Her Majesty's Sta- tionery Office. London. England. 1974. References to books relating to design and larger software development issues can be found at the end of Chapter 23. The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved.20 Notes to the Reader Chapter 1 The C++ Programming Language, Special Edition by Bjarne Stroustrup. Copyright 2000 by AT&T. Published by Addison Wesley, Inc. ISBN 0-201-70073-5. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 2 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ A Tour of C+ + The first thing we do, let´s kill all the language lawyers. ± Henry VI, part II What is C++? Ð programming paradigms Ð procedural programming Ð modularity Ð separate compilation Ð exception handling Ð data abstraction Ð user-defined types Ð concrete types Ð abstract types Ð virtual functions Ð object-oriented programming Ð generic programming Ð containers Ð algorithms Ð language and programming Ð advice. 2.1 What is C++? [tour.intro] C++ is a general-purpose programming language with a bias towards systems programming that ± is a better C, ± supports data abstraction, ± supports object-oriented programming, and ± supports generic programming. This chapter explains what this means without going into the finer details of the language defini- tion. Its purpose is to give you a general overview of C++ and the key techniques for using it, not to provide you with the detailed information necessary to start programming in C++. If you find some parts of this chapter rough going, just ignore those parts and plow on. All will be explained in detail in later chapters. However, if you do skip part of this chapter, do yourself a favor by returning to it later. Detailed understanding of language features ± even of all features of a language ± cannot com- pensate for lack of an overall view of the language and the fundamental techniques for using it. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.22 A Tour of C++ Chapter 2 2.2 Programming Paradigms [tour.paradigm] Object-oriented programming is a technique for programming ± a paradigm for writing ‘‘good’’ programs for a set of problems. If the term ‘‘object-oriented programming language’’ means any- thing, it must mean a programming language that provides mechanisms that support the object- oriented style of programming well. There is an important distinction here. A language is said to support a style of programming if it provides facilities that make it convenient (reasonably easy, safe, and efficient) to use that style. A language does not support a technique if it takes exceptional effort or skill to write such pro- grams; it merely enables the technique to be used. For example, you can write structured programs in Fortran77 and object-oriented programs in C, but it is unnecessarily hard to do so because these languages do not directly support those techniques. Support for a paradigm comes not only in the obvious form of language facilities that allow direct use of the paradigm, but also in the more subtle form of compile-time and/or run-time checks against unintentional deviation from the paradigm. Type checking is the most obvious example of this; ambiguity detection and run-time checks are also used to extend linguistic support for para- digms. Extra-linguistic facilities such as libraries and programming environments can provide fur- ther support for paradigms. One language is not necessarily better than another because it possesses a feature the other does not. There are many examples to the contrary. The important issue is not so much what features a language possesses, but that the features it does possess are sufficient to support the desired pro- gramming styles in the desired application areas: [1] All features must be cleanly and elegantly integrated into the language. [2] It must be possible to use features in combination to achieve solutions that would otherwise require extra, separate features. [3] There should be as few spurious and ‘‘special-purpose’’ features as possible. [4] A feature’s implementation should not impose significant overheads on programs that do not require it. [5] A user should need to know only about the subset of the language explicitly used to write a program. The first principle is an appeal to aesthetics and logic. The next two are expressions of the ideal of minimalism. The last two can be summarized as ‘‘what you don’t know won’t hurt you.’’ C++ was designed to support data abstraction, object-oriented programming, and generic pro- gramming in addition to traditional C programming techniques under these constraints. It was not meant to force one particular programming style upon all users. The following sections consider some programming styles and the key language mechanisms supporting them. The presentation progresses through a series of techniques starting with procedu- ral programming and leading up to the use of class hierarchies in object-oriented programming and generic programming using templates. Each paradigm builds on its predecessors, each adds some- thing new to the C++ programmer’s toolbox, and each reflects a proven design approach. The presentation of language features is not exhaustive. The emphasis is on design approaches and ways of organizing programs rather than on language details. At this stage, it is far more important to gain an idea of what can be done using C++ than to understand exactly how it can be achieved. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 2.3 Procedural Programming 23 2.3 Procedural Programming [tour.proc] The original programming paradigm is: Decide which procedures you want; use the best algorithms you can find. The focus is on the processing ± the algorithm needed to perform the desired computation. Lan- guages support this paradigm by providing facilities for passing arguments to functions and return- ing values from functions. The literature related to this way of thinking is filled with discussion of ways to pass arguments, ways to distinguish different kinds of arguments, different kinds of func- tions (e.g., procedures, routines, and macros), etc. A typical example of ‘‘good style’’ is a square-root function. Given a double-precision floating-point argument, it produces a result. To do this, it performs a well-understood mathemati- cal computation: d do ou ub bl le e s sq qr rt t(d do ou ub bl le e a ar rg g) { / / code for calculating a square root } v vo oi id d f f() { d do ou ub bl le e r ro oo ot t2 2 = s sq qr rt t(2 2) ; / / ... } Curly braces, { }, express grouping in C++. Here, they indicate the start and end of the function bodies. The double slash, / /, begins a comment that extends to the end of the line. The keyword v vo oi id d indicates that a function does not return a value. From the point of view of program organization, functions are used to create order in a maze of algorithms. The algorithms themselves are written using function calls and other language facili- ties. The following subsections present a thumb-nail sketch of C++’s most basic facilities for expressing computation. 2.3.1 Variables and Arithmetic [tour.var] Every name and every expression has a type that determines the operations that may be performed on it. For example, the declaration i in nt t i in nc ch h; specifies that i in nc ch h is of type i in nt t; that is, i in nc ch h is an integer variable. A declaration is a statement that introduces a name into the program. It specifies a type for that name. A type defines the proper use of a name or an expression. C++ offers a variety of fundamental types, which correspond directly to hardware facilities. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.24 A Tour of C++ Chapter 2 b bo oo ol l / / Boolean, possible values are true and false c ch ha ar r / / character, for example, ’a’, ’z’, and ’9’ i in nt t / / integer, for example, 1, 42, and 1216 d do ou ub bl le e / / double-precision floating-point number, for example, 3.14 and 299793.0 A c ch ha ar r variable is of the natural size to hold a character on a given machine (typically a byte), and an i in nt t variable is of the natural size for integer arithmetic on a given machine (typically a word). The arithmetic operators can be used for any combination of these types: + / / plus, both unary and binary - / / minus, both unary and binary * / / multiply / / / divide % / / remainder So can the comparison operators: == / / equal != / / not equal < / / less than > / / greater than <= / / less than or equal >= / / greater than or equal In assignments and in arithmetic operations, C++ performs all meaningful conversions between the basic types so that they can be mixed freely: v vo oi id d s so om me e_ _f fu un nc ct ti io on n() / / function that doesn’t return a value { d do ou ub bl le e d d = 2 2.2 2; / / initialize floating-point number i in nt t i i = 7 7; / / initialize integer d d = d d+i i; / / assign sum to d i i = d d*i i; / / assign product to i } As in C, = is the assignment operator and == tests equality. 2.3.2 Tests and Loops [tour.loop] C++ provides a conventional set of statements for expressing selection and looping. For example, here is a simple function that prompts the user and returns a Boolean indicating the response: b bo oo ol l a ac cc ce ep pt t() { c co ou ut t << "D Do o y yo ou u w wa an nt t t to o p pr ro oc ce ee ed d (y y o or r n n)?\ \n n"; / / write question c ch ha ar r a an ns sw we er r = 0 0; c ci in n >> a an ns sw we er r; / / read answer i if f (a an ns sw we er r == ´y y´) r re et tu ur rn n t tr ru ue e; r re et tu ur rn n f fa al ls se e; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 2.3.2 Tests and Loops 25 The << operator (‘‘put to’’) is used as an output operator; c co ou ut t is the standard output stream. The >> operator (‘‘get from’’) is used as an input operator; c ci in n is the standard input stream. The type of the right-hand operand of >> determines what input is accepted and is the target of the input opera- tion. The \ \n n character at the end of the output string represents a newline. The example could be slightly improved by taking an ‘n’ answer into account: b bo oo ol l a ac cc ce ep pt t2 2() { c co ou ut t << "D Do o y yo ou u w wa an nt t t to o p pr ro oc ce ee ed d (y y o or r n n)?\ \n n"; / / write question c ch ha ar r a an ns sw we er r = 0 0; c ci in n >> a an ns sw we er r; / / read answer s sw wi it tc ch h (a an ns sw we er r) { c ca as se e ´y y´: r re et tu ur rn n t tr ru ue e; c ca as se e ´n n´: r re et tu ur rn n f fa al ls se e; d de ef fa au ul lt t: c co ou ut t << "I I´l ll l t ta ak ke e t th ha at t f fo or r a a n no o.\ \n n"; r re et tu ur rn n f fa al ls se e; } } A switch-statement tests a value against a set of constants. The case constants must be distinct, and if the value tested does not match any of them, the d de ef fa au ul lt t is chosen. The programmer need not provide a d de ef fa au ul lt t. Few programs are written without loops. In this case, we might like to give the user a few tries: b bo oo ol l a ac cc ce ep pt t3 3() { i in nt t t tr ri ie es s = 1 1; w wh hi il le e (t tr ri ie es s < 4 4) { c co ou ut t << "D Do o y yo ou u w wa an nt t t to o p pr ro oc ce ee ed d (y y o or r n n)?\ \n n"; / / write question c ch ha ar r a an ns sw we er r = 0 0; c ci in n >> a an ns sw we er r; / / read answer s sw wi it tc ch h (a an ns sw we er r) { c ca as se e ´y y´: r re et tu ur rn n t tr ru ue e; c ca as se e ´n n´: r re et tu ur rn n f fa al ls se e; d de ef fa au ul lt t: c co ou ut t << "S So or rr ry y, I I d do on n´t t u un nd de er rs st ta an nd d t th ha at t.\ \n n"; t tr ri ie es s = t tr ri ie es s + 1 1; } } c co ou ut t << "I I´l ll l t ta ak ke e t th ha at t f fo or r a a n no o.\ \n n"; r re et tu ur rn n f fa al ls se e; } The while-statement executes until its condition becomes f fa al ls se e. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.26 A Tour of C++ Chapter 2 2.3.3 Pointers and Arrays [tour.ptr] An array can be declared like this: c ch ha ar r v v[1 10 0] ; / / array of 10 characters Similarly, a pointer can be declared like this: c ch ha ar r* p p; / / pointer to character In declarations, [] means ‘‘array of’’ and * means ‘‘pointer to.’’ All arrays have 0 0 as their lower bound, so v v has ten elements, v v[0 0]...v v[9 9]. A pointer variable can hold the address of an object of the appropriate type: p p = &v v[3 3] ; / / p points to v’s fourth element Unary & is the address-of operator. Consider copying ten elements from one array to another: v vo oi id d a an no ot th he er r_ _f fu un nc ct ti io on n() { i in nt t v v1 1[1 10 0] ; i in nt t v v2 2[1 10 0] ; / / ... f fo or r (i in nt t i i=0 0; i i<1 10 0; ++i i) v v1 1[i i]=v v2 2[i i] ; } This for-statement can be read as ‘‘set i i to zero, while i i is less than 1 10 0, copy the i ith element and increment i i.’’ When applied to an integer variable, the increment operator ++ simply adds 1 1. 2.4 Modular Programming [tour.module] Over the years, the emphasis in the design of programs has shifted from the design of procedures and toward the organization of data. Among other things, this reflects an increase in program size. A set of related procedures with the data they manipulate is often called a module. The program- ming paradigm becomes: Decide which modules you want; partition the program so that data is hidden within modules. This paradigm is also known as the data-hiding principle. Where there is no grouping of proce- dures with related data, the procedural programming style suffices. Also, the techniques for design- ing ‘‘good procedures’’ are now applied for each procedure in a module. The most common exam- ple of a module is the definition of a stack. The main problems that have to be solved are: [1] Provide a user interface for the stack (e.g., functions p pu us sh h() and p po op p()). [2] Ensure that the representation of the stack (e.g., an array of elements) can be accessed only through this user interface. [3] Ensure that the stack is initialized before its first use. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 2.4 Modular Programming 27 C++ provides a mechanism for grouping related data, functions, etc., into separate namespaces. For example, the user interface of a S St ta ac ck k module could be declared and used like this: n na am me es sp pa ac ce e S St ta ac ck k { / / interface v vo oi id d p pu us sh h(c ch ha ar r) ; c ch ha ar r p po op p() ; } v vo oi id d f f() { S St ta ac ck k: :p pu us sh h(´c c´) ; i if f (S St ta ac ck k: :p po op p() != ´c c´) e er rr ro or r("i im mp po os ss si ib bl le e") ; } The S St ta ac ck k: : qualification indicates that the p pu us sh h() and p po op p() are those from the S St ta ac ck k name- space. Other uses of those names will not interfere or cause confusion. The definition of the S St ta ac ck k could be provided in a separately-compiled part of the program: n na am me es sp pa ac ce e S St ta ac ck k { / / implementation c co on ns st t i in nt t m ma ax x_ _s si iz ze e = 2 20 00 0; c ch ha ar r v v[m ma ax x_ _s si iz ze e] ; i in nt t t to op p = 0 0; v vo oi id d p pu us sh h(c ch ha ar r c c) { /* check for overflow and push c */ } c ch ha ar r p po op p() { /* check for underflow and pop */ } } The key point about this S St ta ac ck k module is that the user code is insulated from the data representation of S St ta ac ck k by the code implementing S St ta ac ck k: :p pu us sh h() and S St ta ac ck k: :p po op p(). The user doesn’t need to know that the S St ta ac ck k is implemented using an array, and the implementation can be changed without affecting user code. Because data is only one of the things one might want to ‘‘hide,’’ the notion of data hiding is trivially extended to the notion of information hiding; that is, the names of functions, types, etc., can also be made local to a module. Consequently, C++ allows any declaration to be placed in a namespace (§8.2). This S St ta ac ck k module is one way of representing a stack. The following sections use a variety of stacks to illustrate different programming styles. 2.4.1 Separate Compilation [tour.comp] C++ supports C’s notion of separate compilation. This can be used to organize a program into a set of semi-independent fragments. Typically, we place the declarations that specify the interface to a module in a file with a name indicating its intended use. Thus, n na am me es sp pa ac ce e S St ta ac ck k { / / interface v vo oi id d p pu us sh h(c ch ha ar r) ; c ch ha ar r p po op p() ; } would be placed in a file s st ta ac ck k.h h, and users will include that file, called a header file, like this: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.28 A Tour of C++ Chapter 2 #i in nc cl lu ud de e "s st ta ac ck k.h h" / / get the interface v vo oi id d f f() { S St ta ac ck k: :p pu us sh h(´c c´) ; i if f (S St ta ac ck k: :p po op p() != ´c c´) e er rr ro or r("i im mp po os ss si ib bl le e") ; } To help the compiler ensure consistency, the file providing the implementation of the S St ta ac ck k module will also include the interface: #i in nc cl lu ud de e "s st ta ac ck k.h h" / / get the interface n na am me es sp pa ac ce e S St ta ac ck k { / / representation c co on ns st t i in nt t m ma ax x_ _s si iz ze e = 2 20 00 0; c ch ha ar r v v[m ma ax x_ _s si iz ze e] ; i in nt t t to op p = 0 0; } v vo oi id d S St ta ac ck k: :p pu us sh h(c ch ha ar r c c) { /* check for overflow and push c */ } c ch ha ar r S St ta ac ck k: :p po op p() { /* check for underflow and pop */ } The user code goes in a third file, say u us se er r.c c. The code in u us se er r.c c and s st ta ac ck k.c c shares the stack interface information presented in s st ta ac ck k.h h, but the two files are otherwise independent and can be separately compiled. Graphically, the program fragments can be represented like this: S St ta ac ck k i in nt te er rf fa ac ce e . . #i in nc cl lu ud de e " "s st ta ac ck k. .h h" " u us se e s st ta ac ck k . . #i in nc cl lu ud de e " "s st ta ac ck k. .h h" " d de ef fi in ne e s st ta ac ck k . stack.h: user.c: stack.c: Separate compilation is an issue in all real programs. It is not simply a concern in programs that present facilities, such as a S St ta ac ck k, as modules. Strictly speaking, using separate compilation isn’t a language issue; it is an issue of how best to take advantage of a particular language implementation. However, it is of great practical importance. The best approach is to maximize modularity, repre- sent that modularity logically through language features, and then exploit the modularity physically through files for effective separate compilation (Chapter 8, Chapter 9). 2.4.2 Exception Handling [tour.except] When a program is designed as a set of modules, error handling must be considered in light of these modules. Which module is responsible for handling what errors? Often, the module that detects an error doesn’t know what action to take. The recovery action depends on the module that invoked The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 2.4.2 Exception Handling 29 the operation rather than on the module that found the error while trying to perform the operation. As programs grow, and especially when libraries are used extensively, standards for handling errors (or, more generally, ‘‘exceptional circumstances’’) become important. Consider again the S St ta ac ck k example. What ought to be done when we try to p pu us sh h() one too many characters? The writer of the S St ta ac ck k module doesn’t know what the user would like to be done in this case, and the user cannot consistently detect the problem (if the user could, the over- flow wouldn’t happen in the first place). The solution is for the S St ta ac ck k implementer to detect the overflow and then tell the (unknown) user. The user can then take appropriate action. For exam- ple: n na am me es sp pa ac ce e S St ta ac ck k { / / interface v vo oi id d p pu us sh h(c ch ha ar r) ; c ch ha ar r p po op p() ; c cl la as ss s O Ov ve er rf fl lo ow w { }; / / type representing overflow exceptions } When detecting an overflow, S St ta ac ck k: :p pu us sh h() can invoke the exception-handling code; that is, ‘‘throw an O Ov ve er rf fl lo ow w exception:’’ v vo oi id d S St ta ac ck k: :p pu us sh h(c ch ha ar r c c) { i if f (t to op p == m ma ax x_ _s si iz ze e) t th hr ro ow w O Ov ve er rf fl lo ow w() ; / / push c } The t th hr ro ow w transfers control to a handler for exceptions of type S St ta ac ck k: :O Ov ve er rf fl lo ow w in some function that directly or indirectly called S St ta ac ck k: :p pu us sh h(). To do that, the implementation will unwind the function call stack as needed to get back to the context of that caller. Thus, the t th hr ro ow w acts as a mul- tilevel r re et tu ur rn n. For example: v vo oi id d f f() { / / ... t tr ry y { / / exceptions here are handled by the handler defined below w wh hi il le e (t tr ru ue e) S St ta ac ck k: :p pu us sh h(´c c´) ; } c ca at tc ch h (S St ta ac ck k: :O Ov ve er rf fl lo ow w) { / / oops: stack overflow; take appropriate action } / / ... } The w wh hi il le e loop will try to loop forever. Therefore, the c ca at tc ch h-clause providing a handler for S St ta ac ck k: :O Ov ve er rf fl lo ow w will be entered after some call of S St ta ac ck k: :p pu us sh h() causes a t th hr ro ow w. Use of the exception-handling mechanisms can make error handling more regular and readable. See §8.3 and Chapter 14 for further discussion and details. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.30 A Tour of C++ Chapter 2 2.5 Data Abstraction [tour.da] Modularity is a fundamental aspect of all successful large programs. It remains a focus of all design discussions throughout this book. However, modules in the form described previously are not sufficient to express complex systems cleanly. Here, I first present a way of using modules to provide a form of user-defined types and then show how to overcome some problems with that approach by defining user-defined types directly. 2.5.1 Modules Defining Types [tour.types] Programming with modules leads to the centralization of all data of a type under the control of a type manager module. For example, if we wanted many stacks ± rather than the single one pro- vided by the S St ta ac ck k module above ± we could define a stack manager with an interface like this: n na am me es sp pa ac ce e S St ta ac ck k { s st tr ru uc ct t R Re ep p; / / definition of stack layout is elsewhere t ty yp pe ed de ef f R Re ep p& s st ta ac ck k; s st ta ac ck k c cr re ea at te e() ; / / make a new stack v vo oi id d d de es st tr ro oy y(s st ta ac ck k s s) ; / / delete s v vo oi id d p pu us sh h(s st ta ac ck k s s, c ch ha ar r c c) ; / / push c onto s c ch ha ar r p po op p(s st ta ac ck k s s) ; / / pop s } The declaration s st tr ru uc ct t R Re ep p; says that R Re ep p is the name of a type, but it leaves the type to be defined later (§5.7). The declaration t ty yp pe ed de ef f R Re ep p& s st ta ac ck k; gives the name s st ta ac ck k to a ‘‘reference to R Re ep p’’ (details in §5.5). The idea is that a stack is identified by its S St ta ac ck k: :s st ta ac ck k and that further details are hidden from users. A S St ta ac ck k: :s st ta ac ck k acts much like a variable of a built-in type: s st tr ru uc ct t B Ba ad d_ _p po op p { }; v vo oi id d f f() { S St ta ac ck k: :s st ta ac ck k s s1 1 = S St ta ac ck k: :c cr re ea at te e() ; / / make a new stack S St ta ac ck k: :s st ta ac ck k s s2 2 = S St ta ac ck k: :c cr re ea at te e() ; / / make another new stack S St ta ac ck k: :p pu us sh h(s s1 1,´c c´) ; S St ta ac ck k: :p pu us sh h(s s2 2,´k k´) ; i if f (S St ta ac ck k: :p po op p(s s1 1) != ´c c´) t th hr ro ow w B Ba ad d_ _p po op p() ; i if f (S St ta ac ck k: :p po op p(s s2 2) != ´k k´) t th hr ro ow w B Ba ad d_ _p po op p() ; S St ta ac ck k: :d de es st tr ro oy y(s s1 1) ; S St ta ac ck k: :d de es st tr ro oy y(s s2 2) ; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 2.5.1 Modules Defining Types 31 We could implement this S St ta ac ck k in several ways. It is important that a user doesn’t need to know how we do it. As long as we keep the interface unchanged, a user will not be affected if we decide to re-implement S St ta ac ck k. An implementation might preallocate a few stack representations and let S St ta ac ck k: :c cr re ea at te e() hand out a reference to an unused one. S St ta ac ck k: :d de es st tr ro oy y() could then mark a representation ‘‘unused’’ so that S St ta ac ck k: :c cr re ea at te e() can recycle it: n na am me es sp pa ac ce e S St ta ac ck k { / / representation c co on ns st t i in nt t m ma ax x_ _s si iz ze e = 2 20 00 0; s st tr ru uc ct t R Re ep p { c ch ha ar r v v[m ma ax x_ _s si iz ze e] ; i in nt t t to op p; }; c co on ns st t i in nt t m ma ax x = 1 16 6; / / maximum number of stacks R Re ep p s st ta ac ck ks s[m ma ax x] ; / / preallocated stack representations b bo oo ol l u us se ed d[m ma ax x] ; / / used[i] is true if stacks[i] is in use } v vo oi id d S St ta ac ck k: :p pu us sh h(s st ta ac ck k s s, c ch ha ar r c c) { /* check s for overflow and push c */ } c ch ha ar r S St ta ac ck k: :p po op p(s st ta ac ck k s s) { /* check s for underflow and pop */ } S St ta ac ck k: :s st ta ac ck k S St ta ac ck k: :c cr re ea at te e() { / / pick an unused Rep, mark it used, initialize it, and return a reference to it } v vo oi id d S St ta ac ck k: :d de es st tr ro oy y(s st ta ac ck k s s) { /* mark s unused */ } What we have done is to wrap a set of interface functions around the representation type. How the resulting ‘‘stack type’’ behaves depends partly on how we defined these interface functions, partly on how we presented the representation type to the users of S St ta ac ck ks, and partly on the design of the representation type itself. This is often less than ideal. A significant problem is that the presentation of such ‘‘fake types’’ to the users can vary greatly depending on the details of the representation type ± and users ought to be insulated from knowledge of the representation type. For example, had we chosen to use a more elaborate data structure to identify a stack, the rules for assignment and initialization of S St ta ac ck k: :s st ta ac ck ks would have changed dramatically. This may indeed be desirable at times. How- ever, it shows that we have simply moved the problem of providing convenient S St ta ac ck ks from the S St ta ac ck k module to the S St ta ac ck k: :s st ta ac ck k representation type. More fundamentally, user-defined types implemented through a module providing access to an implementation type don’t behave like built-in types and receive less and different support than do built-in types. For example, the time that a S St ta ac ck k: :R Re ep p can be used is controlled through S St ta ac ck k: :c cr re ea at te e() and S St ta ac ck k: :d de es st tr ro oy y() rather than by the usual language rules. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.32 A Tour of C++ Chapter 2 2.5.2 User-Defined Types [tour.udt] C++ attacks this problem by allowing a user to directly define types that behave in (nearly) the same way as built-in types. Such a type is often called an abstract data type. I prefer the term user-defined type. A more reasonable definition of abstract data type would require a mathemati- cal ‘‘abstract’’ specification. Given such a specification, what are called types here would be con- crete examples of such truly abstract entities. The programming paradigm becomes: Decide which types you want; provide a full set of operations for each type. Where there is no need for more than one object of a type, the data-hiding programming style using modules suffices. Arithmetic types such as rational and complex numbers are common examples of user-defined types. Consider: c cl la as ss s c co om mp pl le ex x { d do ou ub bl le e r re e, i im m; p pu ub bl li ic c: c co om mp pl le ex x(d do ou ub bl le e r r, d do ou ub bl le e i i) { r re e=r r; i im m=i i; } / / construct complex from two scalars c co om mp pl le ex x(d do ou ub bl le e r r) { r re e=r r; i im m=0 0; } / / construct complex from one scalar c co om mp pl le ex x() { r re e = i im m = 0 0; } / / default complex: (0,0) f fr ri ie en nd d c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x, c co om mp pl le ex x) ; f fr ri ie en nd d c co om mp pl le ex x o op pe er ra at to or r-(c co om mp pl le ex x, c co om mp pl le ex x) ; / / binary f fr ri ie en nd d c co om mp pl le ex x o op pe er ra at to or r-(c co om mp pl le ex x) ; / / unary f fr ri ie en nd d c co om mp pl le ex x o op pe er ra at to or r*(c co om mp pl le ex x, c co om mp pl le ex x) ; f fr ri ie en nd d c co om mp pl le ex x o op pe er ra at to or r/(c co om mp pl le ex x, c co om mp pl le ex x) ; f fr ri ie en nd d b bo oo ol l o op pe er ra at to or r==(c co om mp pl le ex x, c co om mp pl le ex x) ; / / equal f fr ri ie en nd d b bo oo ol l o op pe er ra at to or r!=(c co om mp pl le ex x, c co om mp pl le ex x) ; / / not equal / / ... }; The declaration of class (that is, user-defined type) c co om mp pl le ex x specifies the representation of a com- plex number and the set of operations on a complex number. The representation is private; that is, r re e and i im m are accessible only to the functions specified in the declaration of class c co om mp pl le ex x. Such functions can be defined like this: c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x a a1 1, c co om mp pl le ex x a a2 2) { r re et tu ur rn n c co om mp pl le ex x(a a1 1.r re e+a a2 2.r re e,a a1 1.i im m+a a2 2.i im m) ; } A member function with the same name as its class is called a constructor. A constructor defines a way to initialize an object of its class. Class c co om mp pl le ex x provides three constructors. One makes a c co om mp pl le ex x from a d do ou ub bl le e, another takes a pair of d do ou ub bl le es, and the third makes a c co om mp pl le ex x with a default value. Class c co om mp pl le ex x can be used like this: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 2.5.2 User-Defined Types 33 v vo oi id d f f(c co om mp pl le ex x z z) { c co om mp pl le ex x a a = 2 2.3 3; c co om mp pl le ex x b b = 1 1/a a; c co om mp pl le ex x c c = a a+b b*c co om mp pl le ex x(1 1,2 2.3 3) ; / / ... i if f (c c != b b) c c = -(b b/a a)+2 2*b b; } The compiler converts operators involving c co om mp pl le ex x numbers into appropriate function calls. For example, c c!=b b means o op pe er ra at to or r!=(c c,b b) and 1 1/a a means o op pe er ra at to or r/(c co om mp pl le ex x(1 1) ,a a). Most, but not all, modules are better expressed as user-defined types. 2.5.3 Concrete Types [tour.concrete] User-defined types can be designed to meet a wide variety of needs. Consider a user-defined S St ta ac ck k type along the lines of the c co om mp pl le ex x type. To make the example a bit more realistic, this S St ta ac ck k type is defined to take its number of elements as an argument: c cl la as ss s S St ta ac ck k { c ch ha ar r* v v; i in nt t t to op p; i in nt t m ma ax x_ _s si iz ze e; p pu ub bl li ic c: c cl la as ss s U Un nd de er rf fl lo ow w { }; / / used as exception c cl la as ss s O Ov ve er rf fl lo ow w { }; / / used as exception c cl la as ss s B Ba ad d_ _s si iz ze e { }; / / used as exception S St ta ac ck k(i in nt t s s) ; / / constructor ~S St ta ac ck k() ; / / destructor v vo oi id d p pu us sh h(c ch ha ar r c c) ; c ch ha ar r p po op p() ; }; The constructor S St ta ac ck k(i in nt t) will be called whenever an object of the class is created. This takes care of initialization. If any cleanup is needed when an object of the class goes out of scope, a com- plement to the constructor ± called the destructor ± can be declared: S St ta ac ck k: :S St ta ac ck k(i in nt t s s) / / constructor { t to op p = 0 0; i if f (1 10 00 00 00 0p pu us sh h(´d d´) ; / / ... } This S St ta ac ck k type obeys the same rules for naming, scope, allocation, lifetime, copying, etc., as does a built-in type such as i in nt t and c ch ha ar r. Naturally, the p pu us sh h() and p po op p() member functions must also be defined somewhere: v vo oi id d S St ta ac ck k: :p pu us sh h(c ch ha ar r c c) { i if f (t to op p == m ma ax x_ _s si iz ze e) t th hr ro ow w O Ov ve er rf fl lo ow w() ; v v[t to op p] = c c; t to op p = t to op p + 1 1; } c ch ha ar r S St ta ac ck k: :p po op p() { i if f (t to op p == 0 0) t th hr ro ow w U Un nd de er rf fl lo ow w() ; t to op p = t to op p - 1 1; r re et tu ur rn n v v[t to op p] ; } Types such as c co om mp pl le ex x and S St ta ac ck k are called concrete types, in contrast to abstract types, where the interface more completely insulates a user from implementation details. 2.5.4 Abstract Types [tour.abstract] One property was lost in the transition from S St ta ac ck k as a ‘‘fake type’’ implemented by a module (§2.5.1) to a proper type (§2.5.3). The representation is not decoupled from the user interface; rather, it is a part of what would be included in a program fragment using S St ta ac ck ks. The representa- tion is private, and therefore accessible only through the member functions, but it is present. If it changes in any significant way, a user must recompile. This is the price to pay for having concrete types behave exactly like built-in types. In particular, we cannot have genuine local variables of a type without knowing the size of the type’s representation. For types that don’t change often, and where local variables provide much-needed clarity and efficiency, this is acceptable and often ideal. However, if we want to completely isolate users of a The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 2.5.4 Abstract Types 35 stack from changes to its implementation, this last S St ta ac ck k is insufficient. Then, the solution is to decouple the interface from the representation and give up genuine local variables. First, we define the interface: c cl la as ss s S St ta ac ck k { p pu ub bl li ic c: c cl la as ss s U Un nd de er rf fl lo ow w { }; / / used as exception c cl la as ss s O Ov ve er rf fl lo ow w { }; / / used as exception v vi ir rt tu ua al l v vo oi id d p pu us sh h(c ch ha ar r c c) = 0 0; v vi ir rt tu ua al l c ch ha ar r p po op p() = 0 0; }; The word v vi ir rt tu ua al l means ‘‘may be redefined later in a class derived from this one’’ in Simula and C++. A class derived from S St ta ac ck k provides an implementation for the S St ta ac ck k interface. The curious =0 0 syntax says that some class derived from S St ta ac ck kmust define the function. Thus, this S St ta ac ck k can serve as the interface to any class that implements its p pu us sh h() and p po op p() functions. This S St ta ac ck k could be used like this: v vo oi id d f f(S St ta ac ck k& s s_ _r re ef f) { s s_ _r re ef f.p pu us sh h(´c c´) ; i if f (s s_ _r re ef f.p po op p() != ´c c´) t th hr ro ow w b ba ad d_ _s st ta ac ck k() ; } Note how f f() uses the S St ta ac ck k interface in complete ignorance of implementation details. A class that provides the interface to a variety of other classes is often called a polymorphic type. Not surprisingly, the implementation could consist of everything from the concrete class S St ta ac ck k that we left out of the interface S St ta ac ck k: c cl la as ss s A Ar rr ra ay y_ _s st ta ac ck k : p pu ub bl li ic c S St ta ac ck k { / / Array_stack implements Stack c ch ha ar r* p p; i in nt t m ma ax x_ _s si iz ze e; i in nt t t to op p; p pu ub bl li ic c: A Ar rr ra ay y_ _s st ta ac ck k(i in nt t s s) ; ~A Ar rr ra ay y_ _s st ta ac ck k() ; v vo oi id d p pu us sh h(c ch ha ar r c c) ; c ch ha ar r p po op p() ; }; The ‘‘:p pu ub bl li ic c’’ can be read as ‘‘is derived from,’’ ‘‘implements,’’ and ‘‘is a subtype of.’’ For a function like f f() to use a S St ta ac ck k in complete ignorance of implementation details, some other function will have to make an object on which it can operate. For example: v vo oi id d g g() { A Ar rr ra ay y_ _s st ta ac ck k a as s(2 20 00 0) ; f f(a as s) ; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.36 A Tour of C++ Chapter 2 Since f f() doesn’t know about A Ar rr ra ay y_ _s st ta ac ck ks but only knows the S St ta ac ck k interface, it will work just as well for a different implementation of a S St ta ac ck k. For example: c cl la as ss s L Li is st t_ _s st ta ac ck k : p pu ub bl li ic c S St ta ac ck k { / / List_stack implements Stack l li is st t l lc c; / / (standard library) list of characters (§3.7.3) p pu ub bl li ic c: L Li is st t_ _s st ta ac ck k() { } v vo oi id d p pu us sh h(c ch ha ar r c c) { l lc c.p pu us sh h_ _f fr ro on nt t(c c) ; } c ch ha ar r p po op p() ; }; c ch ha ar r L Li is st t_ _s st ta ac ck k: :p po op p() { c ch ha ar r x x = l lc c.f fr ro on nt t() ; / / get first element l lc c.p po op p_ _f fr ro on nt t() ; / / remove first element r re et tu ur rn n x x; } Here, the representation is a list of characters. The l lc c.p pu us sh h_ _f fr ro on nt t(c c) adds c c as the first element of l lc c, the call l lc c.p po op p_ _f fr ro on nt t() removes the first element, and l lc c.f fr ro on nt t() denotes l lc c’s first element. A function can create a L Li is st t_ _s st ta ac ck k and have f f() use it: v vo oi id d h h() { L Li is st t_ _s st ta ac ck k l ls s; f f(l ls s) ; } 2.5.5 Virtual Functions [tour.virtual] How is the call s s_ _s se et t.p po op p() in f f() resolved to the right function definition? When f f() is called from h h(), L Li is st t_ _s st ta ac ck k: :p po op p() must be called. When f f() is called from g g(), A Ar rr ra ay y_ _s st ta ac ck k: :p po op p() must be called. To achieve this resolution, a S St ta ac ck k object must contain information to indicate the function to be called at run-time. A common implementation technique is for the compiler to convert the name of a v vi ir rt tu ua al l function into an index into a table of pointers to functions. That table is usually called ‘‘a virtual function table’’ or simply, a v vt tb bl l. Each class with virtual functions has its own v vt tb bl l identifying its virtual functions. This can be represented graphi- cally like this: p p m ma ax x_ _s si iz ze e t to op p . . A Ar rr ra ay y_ _s st ta ac ck k::p pu us sh h() A Ar rr ra ay y_ _s st ta ac ck k::p po op p() v vt tb bl l: : A Ar rr ra ay y_ _s st ta ac ck k o ob bj je ec ct t: : .. l lc c . . L Li is st t_ _s st ta ac ck k::p pu us sh h() L Li is st t_ _s st ta ac ck k::p po op p() v vt tb bl l: : L Li is st t_ _s st ta ac ck k o ob bj je ec ct t: : .. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 2.5.5 Virtual Functions 37 The functions in the v vt tb bl l allow the object to be used correctly even when the size of the object and the layout of its data are unknown to the caller. All the caller needs to know is the location of the v vt tb bl l in a S St ta ac ck k and the index used for each virtual function. This virtual call mechanism can be made essentially as efficient as the ‘‘normal function call’’ mechanism. Its space overhead is one pointer in each object of a class with virtual functions plus one v vt tb bl l for each such class. 2.6 Object-Oriented Programming [tour.oop] Data abstraction is fundamental to good design and will remain a focus of design throughout this book. However, user-defined types by themselves are not flexible enough to serve our needs. This section first demonstrates a problem with simple user-defined data types and then shows how to overcome that problem by using class hierarchies. 2.6.1 Problems with Concrete Types [tour.problems] A concrete type, like a ‘‘fake type’’ defined through a module, defines a sort of black box. Once the black box has been defined, it does not really interact with the rest of the program. There is no way of adapting it to new uses except by modifying its definition. This situation can be ideal, but it can also lead to severe inflexibility. Consider defining a type S Sh ha ap pe e for use in a graphics system. Assume for the moment that the system has to support circles, triangles, and squares. Assume also that we have c cl la as ss s P Po oi in nt t{ /* ... */ }; c cl la as ss s C Co ol lo or r{ /* ... */ }; The /* and */ specify the beginning and end, respectively, of a comment. This comment notation can be used for multi-line comments and comments that end before the end of a line. We might define a shape like this: e en nu um m K Ki in nd d { c ci ir rc cl le e, t tr ri ia an ng gl le e, s sq qu ua ar re e }; / / enumeration (§4.8) c cl la as ss s S Sh ha ap pe e { K Ki in nd d k k; / / type field P Po oi in nt t c ce en nt te er r; C Co ol lo or r c co ol l; / / ... p pu ub bl li ic c: v vo oi id d d dr ra aw w() ; v vo oi id d r ro ot ta at te e(i in nt t) ; / / ... }; The ‘‘type field’’ k k is necessary to allow operations such as d dr ra aw w() and r ro ot ta at te e() to determine what kind of shape they are dealing with (in a Pascal-like language, one might use a variant record with tag k k). The function d dr ra aw w() might be defined like this: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.38 A Tour of C++ Chapter 2 v vo oi id d S Sh ha ap pe e: :d dr ra aw w() { s sw wi it tc ch h (k k) { c ca as se e c ci ir rc cl le e: / / draw a circle b br re ea ak k; c ca as se e t tr ri ia an ng gl le e: / / draw a triangle b br re ea ak k; c ca as se e s sq qu ua ar re e: / / draw a square b br re ea ak k; } } This is a mess. Functions such as d dr ra aw w() must ‘‘know about’’ all the kinds of shapes there are. Therefore, the code for any such function grows each time a new shape is added to the system. If we define a new shape, every operation on a shape must be examined and (possibly) modified. We are not able to add a new shape to a system unless we have access to the source code for every operation. Because adding a new shape involves ‘‘touching’’ the code of every important operation on shapes, doing so requires great skill and potentially introduces bugs into the code that handles other (older) shapes. The choice of representation of particular shapes can get severely cramped by the requirement that (at least some of) their representation must fit into the typically fixed-sized framework presented by the definition of the general type S Sh ha ap pe e. 2.6.2 Class Hierarchies [tour.hierarchies] The problem is that there is no distinction between the general properties of every shape (that is, a shape has a color, it can be drawn, etc.) and the properties of a specific kind of shape (a circle is a shape that has a radius, is drawn by a circle-drawing function, etc.). Expressing this distinction and taking advantage of it defines object-oriented programming. Languages with constructs that allow this distinction to be expressed and used support object-oriented programming. Other languages don’t. The inheritance mechanism (borrowed for C++ from Simula) provides a solution. First, we specify a class that defines the general properties of all shapes: c cl la as ss s S Sh ha ap pe e { P Po oi in nt t c ce en nt te er r; C Co ol lo or r c co ol l; / / ... p pu ub bl li ic c: P Po oi in nt t w wh he er re e() { r re et tu ur rn n c ce en nt te er r; } v vo oi id d m mo ov ve e(P Po oi in nt t t to o) { c ce en nt te er r = t to o; /* ... */ d dr ra aw w() ; } v vi ir rt tu ua al l v vo oi id d d dr ra aw w() = 0 0; v vi ir rt tu ua al l v vo oi id d r ro ot ta at te e(i in nt t a an ng gl le e) = 0 0; / / ... }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 2.6.2 Class Hierarchies 39 As in the abstract type S St ta ac ck k in §2.5.4, the functions for which the calling interface can be defined ± but where the implementation cannot be defined yet ± are v vi ir rt tu ua al l. In particular, the functions d dr ra aw w() and r ro ot ta at te e() can be defined only for specific shapes, so they are declared v vi ir rt tu ua al l. Given this definition, we can write general functions manipulating vectors of pointers to shapes: v vo oi id d r ro ot ta at te e_ _a al ll l(v ve ec ct to or r& v v, i in nt t a an ng gl le e) / / rotate v’s elements angle degrees { f fo or r (i in nt t i i = 0 0; i ir ro ot ta at te e(a an ng gl le e) ; } To define a particular shape, we must say that it is a shape and specify its particular properties (including the virtual functions): c cl la as ss s C Ci ir rc cl le e : p pu ub bl li ic c S Sh ha ap pe e { i in nt t r ra ad di iu us s; p pu ub bl li ic c: v vo oi id d d dr ra aw w() { /* ... */ } v vo oi id d r ro ot ta at te e(i in nt t) {} / / yes, the null function }; In C++, class C Ci ir rc cl le e is said to be derived from class S Sh ha ap pe e, and class S Sh ha ap pe e is said to be a base of class C Ci ir rc cl le e. An alternative terminology calls C Ci ir rc cl le e and S Sh ha ap pe e subclass and superclass, respec- tively. The derived class is said to inherit members from its base class, so the use of base and derived classes is commonly referred to as inheritance. The programming paradigm is: Decide which classes you want; provide a full set of operations for each class; make commonality explicit by using inheritance. Where there is no such commonality, data abstraction suffices. The amount of commonality between types that can be exploited by using inheritance and virtual functions is the litmus test of the applicability of object-oriented programming to a problem. In some areas, such as interactive graphics, there is clearly enormous scope for object-oriented programming. In other areas, such as classical arithmetic types and computations based on them, there appears to be hardly any scope for more than data abstraction, and the facilities needed for the support of object-oriented programming seem unnecessary. Finding commonality among types in a system is not a trivial process. The amount of common- ality to be exploited is affected by the way the system is designed. When a system is designed ± and even when the requirements for the system are written ± commonality must be actively sought. Classes can be designed specifically as building blocks for other types, and existing classes can be examined to see if they exhibit similarities that can be exploited in a common base class. For attempts to explain what object-oriented programming is without recourse to specific pro- gramming language constructs, see [Kerr,1987] and [Booch,1994] in §23.6. Class hierarchies and abstract classes (§2.5.4) complement each other instead of being mutually exclusive (§12.5). In general, the paradigms listed here tend to be complementary and often The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.40 A Tour of C++ Chapter 2 mutually supportive. For example, classes and modules contain functions, while modules contain classes and functions. The experienced designer applies a variety of paradigms as need dictates. 2.7 Generic Programming [tour.generic] Someone who wants a stack is unlikely always to want a stack of characters. A stack is a general concept, independent of the notion of a character. Consequently, it ought to be represented inde- pendently. More generally, if an algorithm can be expressed independently of representation details and if it can be done so affordably and without logical contortions, it ought to be done so. The programming paradigm is: Decide which algorithms you want; parameterize them so that they work for a variety of suitable types and data structures. 2.7.1 Containers [tour.containers] We can generalize a stack-of-characters type to a stack-of-anything type by making it a template and replacing the specific type c ch ha ar r with a template parameter. For example: t te em mp pl la at te e c cl la as ss s S St ta ac ck k { T T* v v; i in nt t m ma ax x_ _s si iz ze e; i in nt t t to op p; p pu ub bl li ic c: c cl la as ss s U Un nd de er rf fl lo ow w { }; c cl la as ss s O Ov ve er rf fl lo ow w { }; S St ta ac ck k(i in nt t s s) ; / / constructor ~S St ta ac ck k() ; / / destructor v vo oi id d p pu us sh h(T T) ; T T p po op p() ; }; The t te em mp pl la at te e prefix makes T T a parameter of the declaration it prefixes. The member functions might be defined similarly: t te em mp pl la at te e v vo oi id d S St ta ac ck k: :p pu us sh h(T T c c) { i if f (t to op p == m ma ax x_ _s si iz ze e) t th hr ro ow w O Ov ve er rf fl lo ow w() ; v v[t to op p] = c c; t to op p = t to op p + 1 1; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 2.7.1 Containers 41 t te em mp pl la at te e T T S St ta ac ck k: :p po op p() { i if f (t to op p == 0 0) t th hr ro ow w U Un nd de er rf fl lo ow w() ; t to op p = t to op p - 1 1; r re et tu ur rn n v v[t to op p] ; } Given these definitions, we can use stacks like this: S St ta ac ck k s sc c; / / stack of characters S St ta ac ck k s sc cp pl lx x; / / stack of complex numbers S St ta ac ck k< l li is st t > s sl li i; / / stack of list of integers v vo oi id d f f() { s sc c.p pu us sh h(´c c´) ; i if f (s sc c.p po op p() != ´c c´) t th hr ro ow w B Ba ad d_ _p po op p() ; s sc cp pl lx x.p pu us sh h(c co om mp pl le ex x(1 1,2 2)) ; i if f (s sc cp pl lx x.p po op p() != c co om mp pl le ex x(1 1,2 2)) t th hr ro ow w B Ba ad d_ _p po op p() ; } Similarly, we can define lists, vectors, maps (that is, associative arrays), etc., as templates. A class holding a collection of elements of some type is commonly called a container class, or simply a container. Templates are a compile-time mechanism so that their use incurs no run-time overhead com- pared to ‘‘hand-written code.’’ 2.7.2 Generic Algorithms [tour.algorithms] The C++ standard library provides a variety of containers, and users can write their own (Chapter 3, Chapter 17, Chapter 18). Thus, we find that we can apply the generic programming paradigm once more to parameterize algorithms by containers. For example, we want to sort, copy, and search v ve ec ct to or rs, l li is st ts, and arrays without having to write s so or rt t(), c co op py y(), and s se ea ar rc ch h() functions for each container. We also don’t want to convert to a specific data structure accepted by a single sort func- tion. Therefore, we must find a generalized way of defining our containers that allows us to manip- ulate one without knowing exactly which kind of container it is. One approach, the approach taken for the containers and non-numerical algorithms in the C++ standard library (§3.8, Chapter 18) is to focus on the notion of a sequence and manipulate sequences through iterators. Here is a graphical representation of the notion of a sequence: begin end ... . . . . . ..... . . . . . .....elements: A sequence has a beginning and an end. An iterator refers to an element, and provides an operation that makes the iterator refer to the next element of the sequence. The end of a sequence is an The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.42 A Tour of C++ Chapter 2 iterator that refers one beyond the last element of the sequence. The physical representation of ‘‘the end’’ may be a sentinel element, but it doesn’t have to be. In fact, the point is that this notion of sequences covers a wide variety of representations, including lists and arrays. We need some standard notation for operations such as ‘‘access an element through an iterator’’ and ‘‘make the iterator refer to the next element.’’ The obvious choices (once you get the idea) are to use the dereference operator * to mean ‘‘access an element through an iterator’’ and the incre- ment operator ++ to mean ‘‘make the iterator refer to the next element.’’ Given that, we can write code like this: t te em mp pl la at te e v vo oi id d c co op py y(I In n f fr ro om m, I In n t to oo o_ _f fa ar r, O Ou ut t t to o) { w wh hi il le e (f fr ro om m != t to oo o_ _f fa ar r) { *t to o = *f fr ro om m; / / copy element pointed to ++t to o; / / next input ++f fr ro om m; / / next output } } This copies any container for which we can define iterators with the right syntax and semantics. C++’s built-in, low-level array and pointer types have the right operations for that, so we can write c ch ha ar r v vc c1 1[2 20 00 0] ; / / array of 200 characters c ch ha ar r v vc c2 2[5 50 00 0] ; / / array of 500 characters v vo oi id d f f() { c co op py y(&v vc c1 1[0 0] ,&v vc c1 1[2 20 00 0] ,&v vc c2 2[0 0]) ; } This copies v vc c1 1 from its first element until its last into v vc c2 2 starting at v vc c2 2’s first element. All standard library containers (§16.3, Chapter 17) support this notion of iterators and sequences. Two template parameters I In n and O Ou ut t are used to indicate the types of the source and the target instead of a single argument. This was done because we often want to copy from one kind of con- tainer into another. For example: c co om mp pl le ex x a ac c[2 20 00 0] ; v vo oi id d g g(v ve ec ct to or r& v vc c, l li is st t& l lc c) { c co op py y(&a ac c[0 0] ,&a ac c[2 20 00 0] ,l lc c.b be eg gi in n()) ; c co op py y(l lc c.b be eg gi in n() ,l lc c.e en nd d() ,v vc c.b be eg gi in n()) ; } This copies the array to the l li is st t and the l li is st t to the v ve ec ct to or r. For a standard container, b be eg gi in n() is an iterator pointing to the first element. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 2.8 Postscript 43 2.8 Postscript [tour.post] No programming language is perfect. Fortunately, a programming language does not have to be perfect to be a good tool for building great systems. In fact, a general-purpose programming lan- guage cannot be perfect for all of the many tasks to which it is put. What is perfect for one task is often seriously flawed for another because perfection in one area implies specialization. Thus, C++ was designed to be a good tool for building a wide variety of systems and to allow a wide variety of ideas to be expressed directly. Not everything can be expressed directly using the built-in features of a language. In fact, that isn’t even the ideal. Language features exist to support a variety of programming styles and tech- niques. Consequently, the task of learning a language should focus on mastering the native and natural styles for that language ± not on the understanding of every little detail of all the language features. In practical programming, there is little advantage in knowing the most obscure language fea- tures or for using the largest number of features. A single language feature in isolation is of little interest. Only in the context provided by techniques and by other features does the feature acquire meaning and interest. Thus, when reading the following chapters, please remember that the real purpose of examining the details of C++ is to be able to use them in concert to support good pro- gramming style in the context of sound designs. 2.9 Advice [tour.advice] [1] Don’t panic! All will become clear in time; §2.1. [2] You don’t have to know every detail of C++ to write good programs; §1.7. [3] Focus on programming techniques, not on language features; §2.1. . The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.44 A Tour of C++ Chapter 2 The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 3 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ A Tour of the Standard Library Why waste time learning when ignorance is instantaneous? ± Hobbes Standard libraries Ð output Ð strings Ð input Ð vectors Ð range checking Ð lists Ð maps Ð container overview Ð algorithms Ð iterators Ð I/O iterators Ð traversals and predicates Ð algorithms using member functions Ð algorithm overview Ð complex numbers Ð vector arithmeticÐ standard library overview Ð advice. 3.1 Introduction [tour2.lib] No significant program is written in just a bare programming language. First, a set of supporting libraries are developed. These then form the basis for further work. Continuing Chapter 2, this chapter gives a quick tour of key library facilities to give you an idea what can be done using C++ and its standard library. Useful library types, such as s st tr ri in ng g, v ve ec ct to or r, l li is st t, and m ma ap p, are presented as well as the most common ways of using them. Doing this allows me to give better examples and to set better exercises in the following chapters. As in Chapter 2, you are strongly encouraged not to be distracted or discouraged by an incomplete understanding of details. The purpose of this chapter is to give you a taste of what is to come and to convey an understanding of the simplest uses of the most useful library facilities. A more detailed introduc- tion to the standard library is given in §16.1.2. The standard library facilities described in this book are part of every complete C++ implemen- tation. In addition to the standard C++ library, most implementations offer ‘‘graphical user inter- face’’ systems, often referred to as GUIs or window systems, for interaction between a user and a program. Similarly, most application development environments provide ‘‘foundation libraries’’ that support corporate or industrial ‘‘standard’’ development and/or execution environments. I do not describe such systems and libraries. The intent is to provide a self-contained description of C++ The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.46 A Tour of the Standard Library Chapter 3 as defined by the standard and to keep the examples portable, except where specifically noted. Nat- urally, a programmer is encouraged to explore the more extensive facilities available on most sys- tems, but that is left to exercises. 3.2 Hello, world! [tour2.hello] The minimal C++ program is i in nt t m ma ai in n() { } It defines a function called m ma ai in n, which takes no arguments and does nothing. Every C++ program must have a function named m ma ai in n(). The program starts by executing that function. The i in nt t value returned by m ma ai in n(), if any, is the program’s return value to ‘‘the system.’’ If no value is returned, the system will receive a value indicating successful completion. A nonzero value from m ma ai in n() indicates failure. Typically, a program produces some output. Here is a program that writes out H He el ll lo o, w wo or rl ld d!: #i in nc cl lu ud de e i in nt t m ma ai in n() { s st td d: :c co ou ut t << "H He el ll lo o, w wo or rl ld d!\ \n n"; } The line #i in nc cl lu ud de e instructs the compiler to include the declarations of the standard stream I/O facilities as found in i io os st tr re ea am m. Without these declarations, the expression s st td d: :c co ou ut t << "H He el ll lo o, w wo or rl ld d!\ \n n" would make no sense. The operator << (‘‘put to’’) writes its second argument onto its first. In this case, the string literal "H He el ll lo o, w wo or rl ld d!\ \n n" is written onto the standard output stream s st td d: :c co ou ut t. A string literal is a sequence of characters surrounded by double quotes. In a string literal, the back- slash character \ \ followed by another character denotes a single special character. In this case, \ \n n is the newline character, so that the characters written are H He el ll lo o, w wo or rl ld d! followed by a newline. 3.3 The Standard Library Namespace [tour2.name] The standard library is defined in a namespace (§2.4, §8.2) called s st td d. That is why I wrote s st td d: :c co ou ut t rather than plain c co ou ut t. I was being explicit about using the s st ta an nd da ar rd d c co ou ut t, rather than some other c co ou ut t. Every standard library facility is provided through some standard header similar to . For example: #i in nc cl lu ud de e #i in nc cl lu ud de e This makes the standard s st tr ri in ng g and l li is st t available. To use them, the s st td d: : prefix can be used: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 3.3 The Standard Library Namespace 47 s st td d: :s st tr ri in ng g s s = "F Fo ou ur r l le eg gs s G Go oo od d; t tw wo o l le eg gs s B Ba aa aa ad d!"; s st td d: :l li is st t s sl lo og ga an ns s; For simplicity, I will rarely use the s st td d: : prefix explicitly in examples. Neither will I always #i in nc cl lu ud de e the necessary headers explicitly. To compile and run the program fragments here, you must #i in nc cl lu ud de e the appropriate headers (as listed in §3.7.5, §3.8.6, and Chapter 16). In addition, you must either use the s st td d: : prefix or make every name from s st td d global (§8.2.3). For example: #i in nc cl lu ud de e / / make the standard string facilities accessible u us si in ng g n na am me es sp pa ac ce e s st td d; / / make std names available without std:: prefix s st tr ri in ng g s s = "I Ig gn no or ra an nc ce e i is s b bl li is ss s!"; / / ok: string is std::string It is generally in poor taste to dump every name from a namespace into the global namespace. However, to keep short the program fragments used to illustrate language and library features, I omit repetitive #i in nc cl lu ud de es and s st td d: : qualifications. In this book, I use the standard library almost exclusively, so if a name from the standard library is used, it either is a use of what the standard offers or part of an explanation of how the standard facility might be defined. 3.4 Output [tour2.ostream] The iostream library defines output for every built-in type. Further, it is easy to define output of a user-defined type. By default, values output to c co ou ut t are converted to a sequence of characters. For example, v vo oi id d f f() { c co ou ut t << 1 10 0; } will place the character 1 1 followed by the character 0 0 on the standard output stream. So will v vo oi id d g g() { i in nt t i i = 1 10 0; c co ou ut t << i i; } Output of different types can be combined in the obvious way: v vo oi id d h h(i in nt t i i) { c co ou ut t << "t th he e v va al lu ue e o of f i i i is s "; c co ou ut t << i i; c co ou ut t << ´\ \n n´; } If i i has the value 1 10 0, the output will be t th he e v va al lu ue e o of f i i i is s 1 10 0 The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.48 A Tour of the Standard Library Chapter 3 A character constant is a character enclosed in single quotes. Note that a character constant is out- put as a character rather than as a numerical value. For example, v vo oi id d k k() { c co ou ut t << ´a a´; c co ou ut t << ´b b´; c co ou ut t << ´c c´; } will output a ab bc c. People soon tire of repeating the name of the output stream when outputting several related items. Fortunately, the result of an output expression can itself be used for further output. For example: v vo oi id d h h2 2(i in nt t i i) { c co ou ut t << "t th he e v va al lu ue e o of f i i i is s " << i i << ´\ \n n´; } This is equivalent to h h(). Streams are explained in more detail in Chapter 21. 3.5 Strings [tour2.string] The standard library provides a s st tr ri in ng g type to complement the string literals used earlier. The s st tr ri in ng g type provides a variety of useful string operations, such as concatenation. For example: s st tr ri in ng g s s1 1 = "H He el ll lo o"; s st tr ri in ng g s s2 2 = "w wo or rl ld d"; v vo oi id d m m1 1() { s st tr ri in ng g s s3 3 = s s1 1 + ", " + s s2 2 + "!\ \n n"; c co ou ut t << s s3 3; } Here, s s3 3 is initialized to the character sequence H He el ll lo o, w wo or rl ld d! followed by a newline. Addition of strings means concatenation. You can add strings, string liter- als, and characters to a string. In many applications, the most common form of concatenation is adding something to the end of a string. This is directly supported by the += operation. For example: v vo oi id d m m2 2(s st tr ri in ng g& s s1 1, s st tr ri in ng g& s s2 2) { s s1 1 = s s1 1 + ´\ \n n´; / / append newline s s2 2 += ´\ \n n´; / / append newline } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 3.5 Strings 49 The two ways of adding to the end of a string are semantically equivalent, but I prefer the latter because it is more concise and likely to be more efficiently implemented. Naturally, s st tr ri in ng gs can be compared against each other and against string literals. For example: s st tr ri in ng g i in nc ca an nt ta at ti io on n; v vo oi id d r re es sp po on nd d(c co on ns st t s st tr ri in ng g& a an ns sw we er r) { i if f (a an ns sw we er r == i in nc ca an nt ta at ti io on n) { / / perform magic } e el ls se e i if f (a an ns sw we er r == "y ye es s") { / / ... } / / ... } The standard library string class is described in Chapter 20. Among other useful features, it pro- vides the ability to manipulate substrings. For example: s st tr ri in ng g n na am me e = "N Ni ie el ls s S St tr ro ou us st tr ru up p"; v vo oi id d m m3 3() { s st tr ri in ng g s s = n na am me e.s su ub bs st tr r(6 6,1 10 0) ; / / s = "Stroustrup" n na am me e.r re ep pl la ac ce e(0 0,5 5,"N Ni ic ch ho ol la as s") ; / / name becomes "Nicholas Stroustrup" } The s su ub bs st tr r() operation returns a string that is a copy of the substring indicated by its arguments. The first argument is an index into the string (a position), and the second argument is the length of the desired substring. Since indexing starts from 0 0, s s gets the value S St tr ro ou us st tr ru up p. The r re ep pl la ac ce e() operation replaces a substring with a value. In this case, the substring starting at 0 0 with length 5 5 is N Ni ie el ls s; it is replaced by N Ni ic ch ho ol la as s. Thus, the final value of n na am me e is N Ni ic ch ho ol la as s S St tr ro ou us st tr ru up p. Note that the replacement string need not be the same size as the substring that it is replacing. 3.5.1 C-Style Strings [tour2.cstring] A C-style string is a zero-terminated array of characters (§5.2.2). As shown, we can easily enter a C-style string into a s st tr ri in ng g. To call functions that take C-style strings, we need to be able to extract the value of a s st tr ri in ng g in the form of a C-style string. The c c_ _s st tr r() function does that (§20.4.1). For example, we can print the n na am me e using the C output function p pr ri in nt tf f() (§21.8) like this: v vo oi id d f f() { p pr ri in nt tf f("n na am me e: %s s\ \n n",n na am me e.c c_ _s st tr r()) ; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.50 A Tour of the Standard Library Chapter 3 3.6 Input [tour2.istream] The standard library offers i is st tr re ea am ms for input. Like o os st tr re ea am ms, i is st tr re ea am ms deal with character string representations of built-in types and can easily be extended to cope with user-defined types. The operator >> (‘‘get from’’) is used as an input operator; c ci in n is the standard input stream. The type of the right-hand operand of >> determines what input is accepted and what is the target of the input operation. For example, v vo oi id d f f() { i in nt t i i; c ci in n >> i i; / / read an integer into i d do ou ub bl le e d d; c ci in n >> d d; / / read a double-precision, floating-point number into d } reads a number, such as 1 12 23 34 4, from the standard input into the integer variable i i and a floating- point number, such as 1 12 2.3 34 4e e5 5, into the double-precision, floating-point variable d d. Here is an example that performs inch-to-centimeter and centimeter-to-inch conversions. You input a number followed by a character indicating the unit: centimeters or inches. The program then outputs the corresponding value in the other unit: i in nt t m ma ai in n() { c co on ns st t f fl lo oa at t f fa ac ct to or r = 2 2.5 54 4; / / 1 inch equals 2.54 cm f fl lo oa at t x x, i in n, c cm m; c ch ha ar r c ch h = 0 0; c co ou ut t << "e en nt te er r l le en ng gt th h: "; c ci in n >> x x; / / read a floating-point number c ci in n >> c ch h; / / read a suffix s sw wi it tc ch h (c ch h) { c ca as se e ´i i´: / / inch i in n = x x; c cm m = x x*f fa ac ct to or r; b br re ea ak k; c ca as se e ´c c´: / / cm i in n = x x/f fa ac ct to or r; c cm m = x x; b br re ea ak k; d de ef fa au ul lt t: i in n = c cm m = 0 0; b br re ea ak k; } c co ou ut t << i in n << " i in n = " << c cm m << " c cm m\ \n n"; } The switch-statement tests a value against a set of constants. The break-statements are used to exit The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 3.6 Input 51 the switch-statement. The case constants must be distinct. If the value tested does not match any of them, the d de ef fa au ul lt t is chosen. The programmer need not provide a d de ef fa au ul lt t. Often, we want to read a sequence of characters. A convenient way of doing that is to read into a s st tr ri in ng g. For example: i in nt t m ma ai in n() { s st tr ri in ng g s st tr r; c co ou ut t << "P Pl le ea as se e e en nt te er r y yo ou ur r n na am me e\ \n n"; c ci in n >> s st tr r; c co ou ut t << "H He el ll lo o, " << s st tr r << "!\ \n n"; } If you type in E Er ri ic c the response is H He el ll lo o, E Er ri ic c! By default, a whitespace character (§5.2.2) such as a space terminates the read, so if you enter E Er ri ic c B Bl lo oo od da ax xe e pretending to be the ill-fated king of York, the response is still H He el ll lo o, E Er ri ic c! You can read a whole line using the g ge et tl li in ne e() function. For example: i in nt t m ma ai in n() { s st tr ri in ng g s st tr r; c co ou ut t << "P Pl le ea as se e e en nt te er r y yo ou ur r n na am me e\ \n n"; g ge et tl li in ne e(c ci in n,s st tr r) ; c co ou ut t << "H He el ll lo o, " << s st tr r << "!\ \n n"; } With this program, the input E Er ri ic c B Bl lo oo od da ax xe e yields the desired output: H He el ll lo o, E Er ri ic c B Bl lo oo od da ax xe e! The standard strings have the nice property of expanding to hold what you put in them, so if you enter a couple of megabytes of semicolons, the program will echo pages of semicolons back at you ± unless your machine or operating system runs out of some critical resource first. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.52 A Tour of the Standard Library Chapter 3 3.7 Containers [tour2.stl] Much computing involves creating collections of various forms of objects and then manipulating such collections. Reading characters into a string and printing out the string is a simple example. A class with the main purpose of holding objects is commonly called a container. Providing suit- able containers for a given task and supporting them with useful fundamental operations are impor- tant steps in the construction of any program. To illustrate the standard library’s most useful containers, consider a simple program for keep- ing names and telephone numbers. This is the kind of program for which different approaches appear ‘‘simple and obvious’’ to people of different backgrounds. 3.7.1 Vector [tour2.vector] For many C programmers, a built-in array of (name,number) pairs would seem to be a suitable starting point: s st tr ru uc ct t E En nt tr ry y { s st tr ri in ng g n na am me e; i in nt t n nu um mb be er r; }; E En nt tr ry y p ph ho on ne e_ _b bo oo ok k[1 10 00 00 0] ; v vo oi id d p pr ri in nt t_ _e en nt tr ry y(i in nt t i i) / / simple use { c co ou ut t << p ph ho on ne e_ _b bo oo ok k[i i].n na am me e << ´ ´ << p ph ho on ne e_ _b bo oo ok k[i i].n nu um mb be er r << ´\ \n n´; } However, a built-in array has a fixed size. If we choose a large size, we waste space; if we choose a smaller size, the array will overflow. In either case, we will have to write low-level memory- management code. The standard library provides a v ve ec ct to or r (§16.3) that takes care of that: v ve ec ct to or r p ph ho on ne e_ _b bo oo ok k(1 10 00 00 0) ; v vo oi id d p pr ri in nt t_ _e en nt tr ry y(i in nt t i i) / / simple use, exactly as for array { c co ou ut t << p ph ho on ne e_ _b bo oo ok k[i i].n na am me e << ´ ´ << p ph ho on ne e_ _b bo oo ok k[i i].n nu um mb be er r << ´\ \n n´; } v vo oi id d a ad dd d_ _e en nt tr ri ie es s(i in nt t n n) / / increase size by n { p ph ho on ne e_ _b bo oo ok k.r re es si iz ze e(p ph ho on ne e_ _b bo oo ok k.s si iz ze e()+n n) ; } The v ve ec ct to or r member function s si iz ze e() gives the number of elements. Note the use of parentheses in the definition of p ph ho on ne e_ _b bo oo ok k. We made a single object of type v ve ec ct to or r and supplied its initial size as an initializer. This is very different from declaring a built-in array: v ve ec ct to or r b bo oo ok k(1 10 00 00 0) ; / / vector of 1000 elements v ve ec ct to or r b bo oo ok ks s[1 10 00 00 0] ; / / 1000 empty vectors The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 3.7.1 Vector 53 Should you make the mistake of using [] where you meant () when declaring a v ve ec ct to or r, your com- piler will almost certainly catch the mistake and issue an error message when you try to use the v ve ec ct to or r. A v ve ec ct to or r is a single object that can be assigned. For example: v vo oi id d f f(v ve ec ct to or r& v v) { v ve ec ct to or r v v2 2 = p ph ho on ne e_ _b bo oo ok k; v v = v v2 2; / / ... } Assigning a v ve ec ct to or r involves copying its elements. Thus, after the initialization and assignment in f f(), v v and v v2 2 each holds a separate copy of every E En nt tr ry y in the phone book. When a v ve ec ct to or r holds many elements, such innocent-looking assignments and initializations can be prohibitively expen- sive. Where copying is undesirable, references or pointers should be used. 3.7.2 Range Checking [tour2.range] The standard library v ve ec ct to or r does not provide range checking by default (§16.3.3). For example: v vo oi id d f f() { i in nt t i i = p ph ho on ne e_ _b bo oo ok k[1 10 00 01 1].n nu um mb be er r; / / 1001 is out of range / / ... } The initialization is likely to place some random value in i i rather than giving an error. This is undesirable, so I will use a simple range-checking adaptation of v ve ec ct to or r, called V Ve ec c, in the following chapters. A V Ve ec c is like a v ve ec ct to or r, except that it throws an exception of type o ou ut t_ _o of f_ _r ra an ng ge e if a sub- script is out of range. Techniques for implementing types such as V Ve ec c and for using exceptions effectively are dis- cussed in §11.12, §8.3, and Chapter 14. However, the definition here is sufficient for the examples in this book: t te em mp pl la at te e c cl la as ss s V Ve ec c : p pu ub bl li ic c v ve ec ct to or r { p pu ub bl li ic c: V Ve ec c() : v ve ec ct to or r() { } V Ve ec c(i in nt t s s) : v ve ec ct to or r(s s) { } T T& o op pe er ra at to or r[](i in nt t i i) { r re et tu ur rn n a at t(i i) ; } / / range-checked c co on ns st t T T& o op pe er ra at to or r[](i in nt t i i) c co on ns st t { r re et tu ur rn n a at t(i i) ; } / / range-checked }; The a at t() operation is a v ve ec ct to or r subscript operation that throws an exception of type o ou ut t_ _o of f_ _r ra an ng ge e if its argument is out of the v ve ec ct to or r’s range (§16.3.3). Returning to the problem of keeping names and telephone numbers, we can now use a V Ve ec c to ensure that out-of-range accesses are caught. For example: V Ve ec c p ph ho on ne e_ _b bo oo ok k(1 10 00 00 0) ; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.54 A Tour of the Standard Library Chapter 3 v vo oi id d p pr ri in nt t_ _e en nt tr ry y(i in nt t i i) / / simple use, exactly as for vector { c co ou ut t << p ph ho on ne e_ _b bo oo ok k[i i].n na am me e << ´ ´ << p ph ho on ne e_ _b bo oo ok k[i i].n nu um mb be er r << ´\ \n n´; } An out-of-range access will throw an exception that the user can catch. For example: v vo oi id d f f() { t tr ry y { f fo or r (i in nt t i i = 0 0; i i<1 10 00 00 00 0; i i++) p pr ri in nt t_ _e en nt tr ry y(i i) ; } c ca at tc ch h (o ou ut t_ _o of f_ _r ra an ng ge e) { c co ou ut t << "r ra an ng ge e e er rr ro or r\ \n n"; } } The exception will be thrown, and then caught, when p ph ho on ne e_ _b bo oo ok k[i i] is tried with i i==1 10 00 00 0. If the user doesn’t catch this kind of exception, the program will terminate in a well-defined manner rather than proceeding or failing in an undefined manner. One way to minimize surprises from exceptions is to use a m ma ai in n() with a try-block as its body: i in nt t m ma ai in n() t tr ry y { / / your code } c ca at tc ch h (o ou ut t_ _o of f_ _r ra an ng ge e) { c ce er rr r << "r ra an ng ge e e er rr ro or r\ \n n"; } c ca at tc ch h (...) { c ce er rr r << "u un nk kn no ow wn n e ex xc ce ep pt ti io on n t th hr ro ow wn n\ \n n"; } This provides default exception handlers so that if we fail to catch some exception, an error mes- sage is printed on the standard error-diagnostic output stream c ce er rr r (§21.2.1). 3.7.3 List [tour2.list] Insertion and deletion of phone book entries could be common. Therefore, a list could be more appropriate than a vector for representing a simple phone book. For example: l li is st t p ph ho on ne e_ _b bo oo ok k; When we use a list, we tend not to access elements using subscripting the way we commonly do for vectors. Instead, we might search the list looking for an element with a given value. To do this, we take advantage of the fact that a l li is st t is a sequence as described in §3.8: v vo oi id d p pr ri in nt t_ _e en nt tr ry y(c co on ns st t s st tr ri in ng g& s s) { t ty yp pe ed de ef f l li is st t: :c co on ns st t_ _i it te er ra at to or r L LI I; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 3.7.3 List 55 f fo or r (L LI I i i = p ph ho on ne e_ _b bo oo ok k.b be eg gi in n() ; i i != p ph ho on ne e_ _b bo oo ok k.e en nd d() ; ++i i) { E En nt tr ry y& e e = *i i; / / reference used as shorthand i if f (s s == e e.n na am me e) c co ou ut t << e e.n na am me e << ´ ´ << e e.n nu um mb be er r << ´\ \n n´; } } The search for s s starts at the beginning of the list and proceeds until either s s is found or the end is reached. Every standard library container provides the functions b be eg gi in n() and e en nd d(), which return an iterator to the first and to one-past-the-last element, respectively (§16.3.2). Given an iterator i i, the next element is ++i i. Given an iterator i i, the element it refers to is *i i. A user need not know the exact type of the iterator for a standard container. That iterator type is part of the definition of the container and can be referred to by name. When we don’t need to mod- ify an element of the container, c co on ns st t_ _i it te er ra at to or r is the type we want. Otherwise, we use the plain i it te er ra at to or r type (§16.3.1). Adding elements to a l li is st t is easy: v vo oi id d a ad dd d_ _e en nt tr ry y(E En nt tr ry y& e e, l li is st t: :i it te er ra at to or r i i) { p ph ho on ne e_ _b bo oo ok k.p pu us sh h_ _f fr ro on nt t(e e) ; / / add at beginning p ph ho on ne e_ _b bo oo ok k.p pu us sh h_ _b ba ac ck k(e e) ; / / add at end p ph ho on ne e_ _b bo oo ok k.i in ns se er rt t(i i,e e) ; / / add before the element ‘i’ refers to } 3.7.4 Map [tour2.map] Writing code to look up a name in a list of (name,number) pairs is really quite tedious. In addition, a linear search is quite inefficient for all but the shortest lists. Other data structures directly support insertion, deletion, and searching based on values. In particular, the standard library provides the m ma ap p type (§17.4.1). A m ma ap p is a container of pairs of values. For example: m ma ap p p ph ho on ne e_ _b bo oo ok k; In other contexts, a m ma ap p is known as an associative array or a dictionary. When indexed by a value of its first type (called the key) a m ma ap p returns the corresponding value of the second type (called the value or the mapped type). For example: v vo oi id d p pr ri in nt t_ _e en nt tr ry y(c co on ns st t s st tr ri in ng g& s s) { i if f (i in nt t i i = p ph ho on ne e_ _b bo oo ok k[s s]) c co ou ut t << s s << ´ ´ << i i << ´\ \n n´; } If no match was found for the key s s, a default value is returned from the p ph ho on ne e_ _b bo oo ok k. The default value for an integer type in a m ma ap p is 0 0. Here, I assume that 0 0 isn’t a valid telephone number. 3.7.5 Standard Containers [tour2.stdcontainer] A m ma ap p, a l li is st t, and a v ve ec ct to or r can each be used to represent a phone book. However, each has strengths and weaknesses. For example, subscripting a v ve ec ct to or r is cheap and easy. On the other hand, inserting an element between two elements tends to be expensive. A l li is st t has exactly the The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.56 A Tour of the Standard Library Chapter 3 opposite properties. A m ma ap p resembles a l li is st t of (key,value) pairs except that it is optimized for find- ing values based on keys. The standard library provides some of the most general and useful container types to allow the programmer to select a container that best serves the needs of an application:_ ________________________________________________________________ Standard Container Summary_ _________________________________________________________________ ________________________________________________________________ v ve ec ct to or r< > A variable-sized vector (§16.3) l li is st t< > A doubly-linked list (§17.2.2) q qu ue eu ue e< > A queue (§17.3.2) s st ta ac ck k< > A stack (§17.3.1) d de eq qu ue e< > A double-ended queue (§17.2.3) p pr ri io or ri it ty y_ _q qu ue eu ue e< > A queue sorted by value (§17.3.3) s se et t< > A set (§17.4.3) m mu ul lt ti is se et t< > A set in which a value can occur many times (§17.4.4) m ma ap p< > An associative array (§17.4.1) m mu ul lt ti im ma ap p< > A map in which a key can occur many times (§17.4.2)_ ________________________________________________________________                           The standard containers are presented in §16.2, §16.3, and Chapter 17. The containers are defined in namespace s st td d and presented in headers , , , etc. (§16.2). The standard containers and their basic operations are designed to be similar from a notational point of view. Furthermore, the meanings of the operations are equivalent for the various contain- ers. In general, basic operations apply to every kind of container. For example, p pu us sh h_ _b ba ac ck k() can be used (reasonably efficiently) to add elements to the end of a v ve ec ct to or r as well as for a l li is st t, and every container has a s si iz ze e() member function that returns its number of elements. This notational and semantic uniformity enables programmers to provide new container types that can be used in a very similar manner to the standard ones. The range-checked vector, V Ve ec c (§3.7.2), is an example of that. Chapter 17 demonstrates how a h ha as sh h_ _m ma ap p can be added to the framework. The uniformity of container interfaces also allows us to specify algorithms indepen- dently of individual container types. 3.8 Algorithms [tour2.algorithms] A data structure, such as a list or a vector, is not very useful on its own. To use one, we need oper- ations for basic access such as adding and removing elements. Furthermore, we rarely just store objects in a container. We sort them, print them, extract subsets, remove elements, search for objects, etc. Consequently, the standard library provides the most common algorithms for contain- ers in addition to providing the most common container types. For example, the following sorts a v ve ec ct to or r and places a copy of each unique v ve ec ct to or r element on a l li is st t: v vo oi id d f f(v ve ec ct to or r& v ve e, l li is st t& l le e) { s so or rt t(v ve e.b be eg gi in n() ,v ve e.e en nd d()) ; u un ni iq qu ue e_ _c co op py y(v ve e.b be eg gi in n() ,v ve e.e en nd d() ,l le e.b be eg gi in n()) ; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 3.8 Algorithms 57 The standard algorithms are described in Chapter 18. They are expressed in terms of sequences of elements (§2.7.2). A sequence is represented by a pair of iterators specifying the first element and the one-beyond-the-last element. In the example, s so or rt t() sorts the sequence from v ve e.b be eg gi in n() to v ve e.e en nd d() ± which just happens to be all the elements of a v ve ec ct to or r. For writing, you need only to specify the first element to be written. If more than one element is written, the elements following that initial element will be overwritten. If we wanted to add the new elements to the end of a container, we could have written: v vo oi id d f f(v ve ec ct to or r& v ve e, l li is st t& l le e) { s so or rt t(v ve e.b be eg gi in n() ,v ve e.e en nd d()) ; u un ni iq qu ue e_ _c co op py y(v ve e.b be eg gi in n() ,v ve e.e en nd d() ,b ba ac ck k_ _i in ns se er rt te er r(l le e)) ; / / append to le } A b ba ac ck k_ _i in ns se er rt te er r() adds elements at the end of a container, extending the container to make room for them (§19.2.4). C programmers will appreciate that the standard containers plus b ba ac ck k_ _i in ns se er rt te er r()s eliminate the need to use error-prone, explicit C-style memory management using r re ea al ll lo oc c() (§16.3.5). Forgetting to use a b ba ac ck k_ _i in ns se er rt te er r() when appending can lead to errors. For example: v vo oi id d f f(l li is st t& v ve e, v ve ec ct to or r& l le e) { c co op py y(v ve e.b be eg gi in n() ,v ve e.e en nd d() ,l le e) ; / / error: le not an iterator c co op py y(v ve e.b be eg gi in n() ,v ve e.e en nd d() ,l le e.e en nd d()) ; / / bad: writes beyond the end c co op py y(v ve e.b be eg gi in n() ,v ve e.e en nd d() ,l le e.b be eg gi in n()) ; / / overwrite elements } 3.8.1 Use of Iterators [tour2.iteruse] When you first encounter a container, a few iterators referring to useful elements can be obtained; b be eg gi in n() and e en nd d() are the best examples of this. In addition, many algorithms return iterators. For example, the standard algorithm f fi in nd d looks for a value in a sequence and returns an iterator to the element found. Using f fi in nd d, we can write a function that counts the number of occurrences of a character in a s st tr ri in ng g: i in nt t c co ou un nt t(c co on ns st t s st tr ri in ng g& s s, c ch ha ar r c c) { s st tr ri in ng g: :c co on ns st t_ _i it te er ra at to or r i i = f fi in nd d(s s.b be eg gi in n() ,s s.e en nd d() ,c c) ; i in nt t n n = 0 0; w wh hi il le e (i i != s s.e en nd d()) { ++n n; i i = f fi in nd d(i i+1 1,s s.e en nd d() ,c c) ; } r re et tu ur rn n n n; } The f fi in nd d algorithm returns an iterator to the first occurrence of a value in a sequence or the one- past-the-end iterator. Consider what happens for a simple call of c co ou un nt t: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.58 A Tour of the Standard Library Chapter 3 v vo oi id d f f() { s st tr ri in ng g m m = "M Ma ar ry y h ha ad d a a l li it tt tl le e l la am mb b"; i in nt t a a_ _c co ou un nt t = c co ou un nt t(m m,´a a´) ; } The first call to f fi in nd d() finds the ´a a´ in M Ma ar ry y. Thus, the iterator points to that character and not to s s.e en nd d(), so we enter the loop. In the loop, we start the search at i i+1 1; that is, we start one past where we found the ´a a´. We then loop finding the other three ´a a´s. That done, f fi in nd d() reaches the end and returns s s.e en nd d() so that the condition i i!=s s.e en nd d() fails and we exit the loop. That call of c co ou un nt t() could be graphically represented like this: M a r y h a d a l i t t l e l a m b . . . . . ..... . . . . . ..... The arrows indicate the initial, intermediate, and final values of the iterator i i. Naturally, the f fi in nd d algorithm will work equivalently on every standard container. Conse- quently, we could generalize the c co ou un nt t() function in the same way: t te em mp pl la at te e i in nt t c co ou un nt t(c co on ns st t C C& v v, T T v va al l) { t ty yp pe en na am me e C C: :c co on ns st t_ _i it te er ra at to or r i i = f fi in nd d(v v.b be eg gi in n() ,v v.e en nd d() ,v va al l) ; / / "typename;" see §C.13.5 i in nt t n n = 0 0; w wh hi il le e (i i != v v.e en nd d()) { ++n n; ++i i; / / skip past the element we just found i i = f fi in nd d(i i,v v.e en nd d() ,v va al l) ; } r re et tu ur rn n n n; } This works, so we can say: v vo oi id d f f(l li is st t& l lc c, v ve ec ct to or r& v vc c, s st tr ri in ng g s s) { i in nt t i i1 1 = c co ou un nt t(l lc c,c co om mp pl le ex x(1 1,3 3)) ; i in nt t i i2 2 = c co ou un nt t(v vc c,"C Ch hr ry ys si ip pp pu us s") ; i in nt t i i3 3 = c co ou un nt t(s s,´x x´) ; } However, we don’t have to define a c co ou un nt t template. Counting occurrences of an element is so gen- erally useful that the standard library provides that algorithm. To be fully general, the standard library c co ou un nt t takes a sequence as its argument, rather than a container, so we would say: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 3.8.1 Use of Iterators 59 v vo oi id d f f(l li is st t& l lc c, v ve ec ct to or r& v vs s, s st tr ri in ng g s s) { i in nt t i i1 1 = c co ou un nt t(l lc c.b be eg gi in n() ,l lc c.e en nd d() ,c co om mp pl le ex x(1 1,3 3)) ; i in nt t i i2 2 = c co ou un nt t(v vs s.b be eg gi in n() ,v vs s.e en nd d() ,"D Di io og ge en ne es s") ; i in nt t i i3 3 = c co ou un nt t(s s.b be eg gi in n() ,s s.e en nd d() ,´x x´) ; } The use of a sequence allows us to use c co ou un nt t for a built-in array and also to count parts of a con- tainer. For example: v vo oi id d g g(c ch ha ar r c cs s[] , i in nt t s sz z) { i in nt t i i1 1 = c co ou un nt t(&c cs s[0 0] ,&c cs s[s sz z] ,´z z´) ; / / ’z’s in array i in nt t i i2 2 = c co ou un nt t(&c cs s[0 0] ,&c cs s[s sz z/2 2] ,´z z´) ; / / ’z’s in first half of array } 3.8.2 Iterator Types [tour2.iter] What are iterators really? Any particular iterator is an object of some type. There are, however, many different iterator types because an iterator needs to hold the information necessary for doing its job for a particular container type. These iterator types can be as different as the containers and the specialized needs they serve. For example, a v ve ec ct to or r’s iterator is most likely an ordinary pointer because a pointer is quite a reasonable way of referring to an element of a v ve ec ct to or r: P i e t H e i n vector: p iterator: Alternatively, a v ve ec ct to or r iterator could be implemented as a pointer to the v ve ec ct to or r plus an index: P i e t H e i n vector: (start == p, position == 3) iterator: . . . . . . . . . . . . . Using such an iterator would allow range checking (§19.3). A list iterator must be something more complicated than a simple pointer to an element because an element of a list in general does not know where the next element of that list is. Thus, a list iter- ator might be a pointer to a link: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.60 A Tour of the Standard Library Chapter 3 link link link link ... list: p iterator: P i e t elements: What is common for all iterators is their semantics and the naming of their operations. For exam- ple, applying ++ to any iterator yields an iterator that refers to the next element. Similarly, * yields the element to which the iterator refers. In fact, any object that obeys a few simple rules like these is an iterator (§19.2.1). Furthermore, users rarely need to know the type of a specific iterator; each container ‘‘knows’’ its iterator types and makes them available under the conventional names i it te er ra a- - t to or r and c co on ns st t_ _i it te er ra at to or r. For example, l li is st t: :i it te er ra at to or r is the general iterator type for l li is st t. I rarely have to worry about the details of how that type is defined. 3.8.3 Iterators and I/O [tour2.ioiterators] Iterators are a general and useful concept for dealing with sequences of elements in containers. However, containers are not the only place where we find sequences of elements. For example, an input stream produces a sequence of values and we write a sequence of values to an output stream. Consequently, the notion of iterators can be usefully applied to input and output. To make an o os st tr re ea am m_ _i it te er ra at to or r, we need to specify which stream will be used and the type of objects written to it. For example, we can define an iterator that refers to the standard output stream, c co ou ut t: o os st tr re ea am m_ _i it te er ra at to or r o oo o(c co ou ut t) ; The effect of assigning to *o oo o is to write the assigned value to c co ou ut t. For example: i in nt t m ma ai in n() { *o oo o = "H He el ll lo o, "; / / meaning cout << "Hello, " ++o oo o; *o oo o = "w wo or rl ld d!\ \n n"; / / meaning cout << "world!\n" } This is yet another way of writing the canonical message to standard output. The ++o oo o is done to mimic writing into an array through a pointer. This way wouldn’t be my first choice for that simple task, but the utility of treating output as a write-only container will soon be obvious ± if it isn’t already. Similarly, an i is st tr re ea am m_ _i it te er ra at to or r is something that allows us to treat an input stream as a read- only container. Again, we must specify the stream to be used and the type of values expected: i is st tr re ea am m_ _i it te er ra at to or r i ii i(c ci in n) ; Because input iterators invariably appear in pairs representing a sequence, we must provide an The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 3.8.3 Iterators and I/O 61 i is st tr re ea am m_ _i it te er ra at to or r to indicate the end of input. This is the default i is st tr re ea am m_ _i it te er ra at to or r: i is st tr re ea am m_ _i it te er ra at to or r e eo os s; We could now read H He el ll lo o, w wo or rl ld d! from input and write it out again like this: i in nt t m ma ai in n() { s st tr ri in ng g s s1 1 = *i ii i; ++i ii i; s st tr ri in ng g s s2 2 = *i ii i; c co ou ut t << s s1 1 << ´ ´ << s s2 2 << ´\ \n n´; } Actually, i is st tr re ea am m_ _i it te er ra at to or rs and o os st tr re ea am m_ _i it te er ra at to or rs are not meant to be used directly. Instead, they are typically provided as arguments to algorithms. For example, we can write a simple program to read a file, sort the words read, eliminate duplicates, and write the result to another file: i in nt t m ma ai in n() { s st tr ri in ng g f fr ro om m, t to o; c ci in n >> f fr ro om m >> t to o; / / get source and target file names i if fs st tr re ea am m i is s(f fr ro om m.c c_ _s st tr r()) ; / / input stream (c_str(); see §3.5) i is st tr re ea am m_ _i it te er ra at to or r i ii i(i is s) ; / / input iterator for stream i is st tr re ea am m_ _i it te er ra at to or r e eo os s; / / input sentinel v ve ec ct to or r b b(i ii i,e eo os s) ; / / b is a vector initialized from input s so or rt t(b b.b be eg gi in n() ,b b.e en nd d()) ; / / sort the buffer o of fs st tr re ea am m o os s(t to o.c c_ _s st tr r()) ; / / output stream o os st tr re ea am m_ _i it te er ra at to or r o oo o(o os s,"\ \n n") ; / / output iterator for stream u un ni iq qu ue e_ _c co op py y(b b.b be eg gi in n() ,b b.e en nd d() ,o oo o) ; / / copy buffer to output, / / discard replicated values r re et tu ur rn n !i is s.e eo of f() && !o os s; / / return error state (§3.2, §21.3.3) } An i if fs st tr re ea am m is an i is st tr re ea am m that can be attached to a file, and an o of fs st tr re ea am m is an o os st tr re ea am m that can be attached to a file. The o os st tr re ea am m_ _i it te er ra at to or r’s second argument is used to delimit output values. 3.8.4 Traversals and Predicates [tour2.traverse] Iterators allow us to write loops to iterate through a sequence. However, writing loops can be tedious, so the standard library provides ways for a function to be called for each element of a sequence. Consider writing a program that reads words from input and records the frequency of their occurrence. The obvious representation of the strings and their associated frequencies is a m ma ap p: m ma ap p h hi is st to og gr ra am m; The obvious action to be taken for each string to record its frequency is: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.62 A Tour of the Standard Library Chapter 3 v vo oi id d r re ec co or rd d(c co on ns st t s st tr ri in ng g& s s) { h hi is st to og gr ra am m[s s]++; / / record frequency of ‘‘s’’ } Once the input has been read, we would like to output the data we have gathered. The m ma ap p consists of a sequence of (string,int) pairs. Consequently, we would like to call v vo oi id d p pr ri in nt t(c co on ns st t p pa ai ir r& r r) { c co ou ut t << r r.f fi ir rs st t << ´ ´ << r r.s se ec co on nd d << ´\ \n n´; } for each element in the map (the first element of a p pa ai ir r is called f fi ir rs st t, and the second element is called s se ec co on nd d). The first element of the p pa ai ir r is a c co on ns st t s st tr ri in ng g rather than a plain s st tr ri in ng g because all m ma ap p keys are constants. Thus, the main program becomes: i in nt t m ma ai in n() { i is st tr re ea am m_ _i it te er ra at to or r i ii i(c ci in n) ; i is st tr re ea am m_ _i it te er ra at to or r e eo os s; f fo or r_ _e ea ac ch h(i ii i,e eo os s,r re ec co or rd d) ; f fo or r_ _e ea ac ch h(h hi is st to og gr ra am m.b be eg gi in n() ,h hi is st to og gr ra am m.e en nd d() ,p pr ri in nt t) ; } Note that we don’t need to sort the m ma ap p to get the output in order. A m ma ap p keeps its elements ordered so that an iteration traverses the m ma ap p in (increasing) order. Many programming tasks involve looking for something in a container rather than simply doing something to every element. For example, the f fi in nd d algorithm (§18.5.2) provides a convenient way of looking for a specific value. A more general variant of this idea looks for an element that fulfills a specific requirement. For example, we might want to search a m ma ap p for the first value larger than 4 42 2. A m ma ap p is a sequence of (key,value) pairs, so we search that list for a p pa ai ir r where the i in nt t is greater than 4 42 2: b bo oo ol l g gt t_ _4 42 2(c co on ns st t p pa ai ir r& r r) { r re et tu ur rn n r r.s se ec co on nd d>4 42 2; } v vo oi id d f f(m ma ap p& m m) { t ty yp pe ed de ef f m ma ap p: :c co on ns st t_ _i it te er ra at to or r M MI I; M MI I i i = f fi in nd d_ _i if f(m m.b be eg gi in n() ,m m.e en nd d() ,g gt t_ _4 42 2) ; / / ... } Alternatively, we could count the number of words with a frequency higher than 42: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 3.8.4 Traversals and Predicates 63 v vo oi id d g g(c co on ns st t m ma ap p& m m) { i in nt t c c4 42 2 = c co ou un nt t_ _i if f(m m.b be eg gi in n() ,m m.e en nd d() ,g gt t_ _4 42 2) ; / / ... } A function, such as g gt t_ _4 42 2(), that is used to control the algorithm is called a predicate. A predicate is called for each element and returns a Boolean value, which the algorithm uses to perform its intended action. For example, f fi in nd d_ _i if f() searches until its predicate returns t tr ru ue e to indicate that an element of interest has been found. Similarly, c co ou un nt t_ _i if f() counts the number of times its predicate is t tr ru ue e. The standard library provides a few useful predicates and some templates that are useful for cre- ating more (§18.4.2). 3.8.5 Algorithms Using Member Functions [tour2.memp] Many algorithms apply a function to elements of a sequence. For example, in §3.8.4 f fo or r_ _e ea ac ch h(i ii i,e eo os s,r re ec co or rd d) ; calls r re ec co or rd d() to read strings from input. Often, we deal with containers of pointers and we really would like to call a member function of the object pointed to, rather than a global function on the pointer. For example, we might want to call the member function S Sh ha ap pe e: :d dr ra aw w() for each element of a l li is st t. To handle this specific example, we simply write a nonmember function that invokes the member function. For example: v vo oi id d d dr ra aw w(S Sh ha ap pe e* p p) { p p->d dr ra aw w() ; } v vo oi id d f f(l li is st t& s sh h) { f fo or r_ _e ea ac ch h(s sh h.b be eg gi in n() ,s sh h.e en nd d() ,d dr ra aw w) ; } By generalizing this technique, we can write the example like this: v vo oi id d g g(l li is st t& s sh h) { f fo or r_ _e ea ac ch h(s sh h.b be eg gi in n() ,s sh h.e en nd d() ,m me em m_ _f fu un n(&S Sh ha ap pe e: :d dr ra aw w)) ; } The standard library m me em m_ _f fu un n() template (§18.4.4.2) takes a pointer to a member function (§15.5) as its argument and produces something that can be called for a pointer to the member’s class. The result of m me em m_ _f fu un n(&S Sh ha ap pe e: :d dr ra aw w) takes a S Sh ha ap pe e* argument and returns whatever S Sh ha ap pe e: :d dr ra aw w() returns. The m me em m_ _f fu un n() mechanism is important because it allows the standard algorithms to be used for containers of polymorphic objects. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.64 A Tour of the Standard Library Chapter 3 3.8.6 Standard Library Algorithms [tour2.algolist] What is an algorithm? A general definition of an algorithm is ‘‘a finite set of rules which gives a sequence of operations for solving a specific set of problems [and] has five important features: Finiteness ... Definiteness ... Input ... Output ... Effectiveness’’ [Knuth,1968,§1.1]. In the context of the C++ standard library, an algorithm is a set of templates operating on sequences of elements. The standard library provides dozens of algorithms. The algorithms are defined in namespace s st td d and presented in the header. Here are a few I have found particularly useful:_ _____________________________________________________________________ Selected Standard Algorithms_ ______________________________________________________________________ _____________________________________________________________________ f fo or r_ _e ea ac ch h( () ) Invoke function for each element (§18.5.1) f fi in nd d( () ) Find first occurrence of arguments (§18.5.2) f fi in nd d_ _i if f( () ) Find first match of predicate (§18.5.2) c co ou un nt t( () ) Count occurrences of element (§18.5.3) c co ou un nt t_ _i if f( () ) Count matches of predicate (§18.5.3) r re ep pl la ac ce e( () ) Replace element with new value (§18.6.4) r re ep pl la ac ce e_ _i if f( () ) Replace element that matches predicate with new value (§18.6.4) c co op py y( () ) Copy elements (§18.6.1) u un ni iq qu ue e_ _c co op py y( () ) Copy elements that are not duplicates (§18.6.1) s so or rt t( () ) Sort elements (§18.7.1) e eq qu ua al l_ _r ra an ng ge e( () ) Find all elements with equivalent values (§18.7.2) m me er rg ge e( () ) Merge sorted sequences (§18.7.3)_ _____________________________________________________________________                                 These algorithms, and many more (see Chapter 18), can be applied to elements of containers, s st tr ri in ng gs, and built-in arrays. 3.9 Math [tour2.math] Like C, C++ wasn’t designed primarily with numerical computation in mind. However, a lot of numerical work is done in C++, and the standard library reflects that. 3.9.1 Complex Numbers [tour2.complex] The standard library supports a family of complex number types along the lines of the c co om mp pl le ex x class described in §2.5.2. To support complex numbers where the scalars are single-precision, floating-point numbers (f fl lo oa at ts), double precision numbers (d do ou ub bl le es), etc., the standard library c co om m- - p pl le ex x is a template: t te em mp pl la at te e c cl la as ss s c co om mp pl le ex x { p pu ub bl li ic c: c co om mp pl le ex x(s sc ca al la ar r r re e, s sc ca al la ar r i im m) ; / / ... }; The usual arithmetic operations and the most common mathematical functions are supported for complex numbers. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 3.9.1 Complex Numbers 65 / / standard exponentiation function from : t te em mp pl la at te e c co om mp pl le ex x p po ow w(c co on ns st t c co om mp pl le ex x&, i in nt t) ; v vo oi id d f f(c co om mp pl le ex x f fl l, c co om mp pl le ex x d db b) { c co om mp pl le ex x l ld d = f fl l+s sq qr rt t(d db b) ; d db b += f fl l*3 3; f fl l = p po ow w(1 1/f fl l,2 2) ; / / ... } For more details, see §22.5. 3.9.2 Vector Arithmetic [tour2.valarray] The v ve ec ct to or r described in §3.7.1 was designed to be a general mechanism for holding values, to be flexible, and to fit into the architecture of containers, iterators, and algorithms. However, it does not support mathematical vector operations. Adding such operations to v ve ec ct to or r would be easy, but its generality and flexibility precludes optimizations that are often considered essential for serious numerical work. Consequently, the standard library provides a vector, called v va al la ar rr ra ay y, that is less general and more amenable to optimization for numerical computation: t te em mp pl la at te e c cl la as ss s v va al la ar rr ra ay y { / / ... T T& o op pe er ra at to or r[](s si iz ze e_ _t t) ; / / ... }; The type s si iz ze e_ _t t is the unsigned integer type that the implementation uses for array indices. The usual arithmetic operations and the most common mathematical functions are supported for v va al la ar rr ra ay ys. For example: / / standard absolute value function from : t te em mp pl la at te e v va al la ar rr ra ay y a ab bs s(c co on ns st t v va al la ar rr ra ay y&) ; v vo oi id d f f(v va al la ar rr ra ay y& a a1 1, v va al la ar rr ra ay y& a a2 2) { v va al la ar rr ra ay y a a = a a1 1*3 3.1 14 4+a a2 2/a a1 1; a a2 2 += a a1 1*3 3.1 14 4; a a = a ab bs s(a a) ; d do ou ub bl le e d d = a a2 2[7 7] ; / / ... } For more details, see §22.4. 3.9.3 Basic Numeric Support [tour2.basicnum] Naturally, the standard library contains the most common mathematical functions ± such as l lo og g(), p po ow w(), and c co os s() ± for floating-point types; see §22.3. In addition, classes that describe the properties of built-in types ± such as the maximum exponent of a f fl lo oa at t ± are provided; see §22.2. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.66 A Tour of the Standard Library Chapter 3 3.10 Standard Library Facilities [tour2.post] The facilities provided by the standard library can be classified like this: [1] Basic run-time language support (e.g., for allocation and run-time type information); see §16.1.3. [2] The C standard library (with very minor modifications to minimize violations of the type system); see §16.1.2. [3] Strings and I/O streams (with support for international character sets and localization); see Chapter 20 and Chapter 21. [4] A framework of containers (such as v ve ec ct to or r, l li is st t, and m ma ap p) and algorithms using containers (such as general traversals, sorts, and merges); see Chapter 16, Chapter 17, Chapter 18, and Chapter 19. [5] Support for numerical computation (complex numbers plus vectors with arithmetic opera- tions, BLAS-like and generalized slices, and semantics designed to ease optimization); see Chapter 22. The main criterion for including a class in the library was that it would somehow be used by almost every C++ programmer (both novices and experts), that it could be provided in a general form that did not add significant overhead compared to a simpler version of the same facility, and that simple uses should be easy to learn. Essentially, the C++ standard library provides the most common fun- damental data structures together with the fundamental algorithms used on them. Every algorithm works with every container without the use of conversions. This framework, conventionally called the STL [Stepanov,1994], is extensible in the sense that users can easily pro- vide containers and algorithms in addition to the ones provided as part of the standard and have these work directly with the standard containers and algorithms. 3.11 Advice [tour2.advice] [1] Don’t reinvent the wheel; use libraries. [2] Don’t believe in magic; understand what your libraries do, how they do it, and at what cost they do it. [3] When you have a choice, prefer the standard library to other libraries. [4] Do not think that the standard library is ideal for everything. [5] Remember to #i in nc cl lu ud de e the headers for the facilities you use; §3.3. [6] Remember that standard library facilities are defined in namespace s st td d; §3.3. [7] Use s st tr ri in ng g rather than c ch ha ar r*; §3.5, §3.6. [8] If in doubt use a range-checked vector (such as V Ve ec c); §3.7.2. [9] Prefer v ve ec ct to or r, l li is st t, and m ma ap p to T T[]; §3.7.1, §3.7.3, §3.7.4. [10] When adding elements to a container, use p pu us sh h_ _b ba ac ck k() or b ba ac ck k_ _i in ns se er rt te er r(); §3.7.3, §3.8. [11] Use p pu us sh h_ _b ba ac ck k() on a v ve ec ct to or r rather than r re ea al ll lo oc c() on an array; §3.8. [12] Catch common exceptions in m ma ai in n(); §3.7.2. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Part I Basic Facilities This part describes C++’s built-in types and the basic facilities for constructing pro- grams out of them. The C subset of C++ is presented together with C++’s additional support for traditional styles of programming. It also discusses the basic facilities for composing a C++ program out of logical and physical parts. Chapters 4 Types and Declarations 5 Pointers, Arrays, and Structures 6 Expressions and Statements 7 Functions 8 Namespaces and Exceptions 9 Source Files and Programs The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.68 Basic Facilities Part I The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 4 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Types and Declarations Accept nothing short of perfection! ± anon Perfection is achieved only on the point of collapse. ± C. N. Parkinson Types Ð fundamental types Ð Booleans Ð characters Ð character literals Ð integers Ð integer literals Ð floating-point types Ð floating-point literals Ð sizes Ð v vo oi id d Ð enumerations Ð declarations Ð names Ð scope Ð initialization Ð objects Ð t ty yp pe ed de ef fs Ð advice Ð exercises. 4.1 Types [dcl.type] Consider x x = y y+f f(2 2) ; For this to make sense in a C++ program, the names x x, y y, and f f must be suitably declared. That is, the programmer must specify that entities named x x, y y, and f f exist and that they are of types for which = (assignment), + (addition), and () (function call), respectively, are meaningful. Every name (identifier) in a C++ program has a type associated with it. This type determines what operations can be applied to the name (that is, to the entity referred to by the name) and how such operations are interpreted. For example, the declarations f fl lo oa at t x x; / / x is a floating-point variable i in nt t y y = 7 7; / / y is an integer variable with the initial value 7 f fl lo oa at t f f(i in nt t) ; / / f is a function taking an argument of type int and returning a floating-point number The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.70 Types and Declarations Chapter 4 would make the example meaningful. Because y y is declared to be an i in nt t, it can be assigned to, used in arithmetic expressions, etc. On the other hand, f f is declared to be a function that takes an i in nt t as its argument, so it can be called given a suitable argument. This chapter presents fundamental types (§4.1.1) and declarations (§4.9). Its examples just demonstrate language features; they are not intended to do anything useful. More extensive and realistic examples are saved for later chapters after more of C++ has been described. This chapter simply provides the most basic elements from which C++ programs are constructed. You must know these elements, plus the terminology and simple syntax that goes with them, in order to com- plete a real project in C++ and especially to read code written by others. However, a thorough understanding of every detail mentioned in this chapter is not a requirement for understanding the following chapters. Consequently, you may prefer to skim through this chapter, observing the major concepts, and return later as the need for understanding of more details arises. 4.1.1 Fundamental Types [dcl.fundamental] C++ has a set of fundamental types corresponding to the most common basic storage units of a computer and the most common ways of using them to hold data: §4.2 A Boolean type (b bo oo ol l) §4.3 Character types (such as c ch ha ar r) §4.4 Integer types (such as i in nt t) §4.5 Floating-point types (such as d do ou ub bl le e) In addition, a user can define §4.8 Enumeration types for representing specific sets of values (e en nu um m) There also is §4.7 A type, v vo oi id d, used to signify the absence of information From these types, we can construct other types: §5.1 Pointer types (such as i in nt t*) §5.2 Array types (such as c ch ha ar r[]) §5.5 Reference types (such as d do ou ub bl le e&) §5.7 Data structures and classes (Chapter 10) The Boolean, character, and integer types are collectively called integral types. The integral and floating-point types are collectively called arithmetic types. Enumerations and classes (Chapter 10) are called user-defined types because they must be defined by users rather than being available for use without previous declaration, the way fundamental types are. In contrast, other types are called built-in types. The integral and floating-point types are provided in a variety of sizes to give the programmer a choice of the amount of storage consumed, the precision, and the range available for computations (§4.6). The assumption is that a computer provides bytes for holding characters, words for holding and computing integer values, some entity most suitable for floating-point computation, and addresses for referring to those entities. The C++ fundamental types together with pointers and arrays present these machine-level notions to the programmer in a reasonably implementation- independent manner. For most applications, one could simply use b bo oo ol l for logical values, c ch ha ar r for characters, i in nt t for integer values, and d do ou ub bl le e for floating-point values. The remaining fundamental types are The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 4.1.1 Fundamental Types 71 variations for optimizations and special needs that are best ignored until such needs arise. They must be known, however, to read old C and C++ code. 4.2 Booleans [dcl.bool] A Boolean, b bo oo ol l, can have one of the two values t tr ru ue e or f fa al ls se e. A Boolean is used to express the results of logical operations. For example: v vo oi id d f f(i in nt t a a, i in nt t b b) { b bo oo ol l b b1 1 = a a==b b; / / = is assignment, == is equality / / ... } If a a and b b have the same value, b b1 1 becomes t tr ru ue e; otherwise, b b1 1 becomes f fa al ls se e. A common use of b bo oo ol l is as the type of the result of a function that tests some condition (a predicate). For example: b bo oo ol l i is s_ _o op pe en n(F Fi il le e*) ; b bo oo ol l g gr re ea at te er r(i in nt t a a, i in nt t b b) { r re et tu ur rn n a a>b b; } By definition, t tr ru ue e has the value 1 1 when converted to an integer and f fa al ls se e has the value 0 0. Con- versely, integers can be implicitly converted to b bo oo ol l values: nonzero integers convert to t tr ru ue e and 0 0 converts to f fa al ls se e. For example: b bo oo ol l b b = 7 7; / / bool(7) is true, so b becomes true i in nt t i i = t tr ru ue e; / / int(true) is 1, so i becomes 1 In arithmetic and logical expressions, b bo oo ol ls are converted to i in nt ts; integer arithmetic and logical operations are performed on the converted values. If the result is converted back to b bo oo ol l, a 0 0 is converted to f fa al ls se e and a nonzero value is converted to t tr ru ue e. v vo oi id d g g() { b bo oo ol l a a = t tr ru ue e; b bo oo ol l b b = t tr ru ue e; b bo oo ol l x x = a a+b b; / / a+b is 2, so x becomes true b bo oo ol l y y = a a|b b; / / ab is 1, so y becomes true } A pointer can be implicitly converted to a b bo oo ol l (§C.6.2.5). A nonzero pointer converts to t tr ru ue e; zero-valued pointers convert to f fa al ls se e. 4.3 Character Types [dcl.char] A variable of type c ch ha ar r can hold a character of the implementation’s character set. For example: c ch ha ar r c ch h = ´a a´; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.72 Types and Declarations Chapter 4 Almost universally, a c ch ha ar r has 8 bits so that it can hold one of 256 different values. Typically, the character set is a variant of ISO-646, for example ASCII, thus providing the characters appearing on your keyboard. Many problems arise from the fact that this set of characters is only partially standardized (§C.3). Serious variations occur between character sets supporting different natural languages and also between different character sets supporting the same natural language in different ways. However, here we are interested only in how such differences affect the rules of C++. The larger and more interesting issue of how to program in a multi-lingual, multi-character-set environment is beyond the scope of this book, although it is alluded to in several places (§20.2, §21.7, §C.3.3). It is safe to assume that the implementation character set includes the decimal digits, the 26 alphabetic characters of English, and some of the basic punctuation characters. It is not safe to assume that there are no more than 127 characters in an 8-bit character set (e.g., some sets provide 255 characters), that there are no more alphabetic characters than English provides (most European languages provide more), that the alphabetic characters are contiguous (EBCDIC leaves a gap between ´i i´ and ´j j´), or that every character used to write C++ is available (e.g., some national character sets do not provide { } [ ] | \ \; §C.3.1). Whenever possible, we should avoid making assumptions about the representation of objects. This general rule applies even to characters. Each character constant has an integer value. For example, the value of ´b b´ is 9 98 8 in the ASCII character set. Here is a small program that will tell you the integer value of any character you care to input: #i in nc cl lu ud de e i in nt t m ma ai in n() { c ch ha ar r c c; s st td d: :c ci in n >> c c; s st td d: :c co ou ut t << "t th he e v va al lu ue e o of f ´" << c c << "´ i is s " << i in nt t(c c) << ´\ \n n´; } The notation i in nt t(c c) gives the integer value for a character c c. The possibility of converting a c ch ha ar r to an integer raises the question: is a c ch ha ar r signed or unsigned? The 256 values represented by an 8-bit byte can be interpreted as the values 0 0 to 2 25 55 5 or as the values -1 12 27 7 to 1 12 27 7. Unfortunately, which choice is made for a plain c ch ha ar r is implementation-defined (§C.1, §C.3.4). C++ provides two types for which the answer is definite; s si ig gn ne ed d c ch ha ar r, which can hold at least the values -1 12 27 7 to 1 12 27 7, and u un ns si ig gn ne ed d c ch ha ar r, which can hold at least the values 0 0 to 2 25 55 5. Fortunately, the difference matters only for values outside the 0 0 to 1 12 27 7 range, and the most common characters are within that range. Values outside that range stored in a plain c ch ha ar r can lead to subtle portability problems. See §C.3.4 if you need to use more than one type of c ch ha ar r or if you store integers in c ch ha ar r variables. A type w wc ch ha ar r_ _t t is provided to hold characters of a larger character set such as Unicode. It is a distinct type. The size of w wc ch ha ar r_ _t t is implementation-defined and large enough to hold the largest character set supported by the implementation’s locale (see §21.7, §C.3.3). The strange name is a leftover from C. In C, w wc ch ha ar r_ _t t is a t ty yp pe ed de ef f (§4.9.7) rather than a built-in type. The suffix _ _t t was added to distinguish standard t ty yp pe ed de ef fs. Note that the character types are integral types (§4.1.1) so that arithmetic and logical operations (§6.2) apply. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 4.3.1 Character Literals 73 4.3.1 Character Literals [dcl.char.lit] A character literal, often called a character constant, is a character enclosed in single quotes, for example, ´a a´ and ´0 0´. The type of a character literal is c ch ha ar r. Such character literals are really symbolic constants for the integer value of the characters in the character set of the machine on which the C++ program is to run. For example, if you are running on a machine using the ASCII character set, the value of ´0 0´ is 4 48 8. The use of character literals rather than decimal notation makes programs more portable. A few characters also have standard names that use the backslash \ \ as an escape character. For example, \ \n n is a newline and \ \t t is a horizontal tab. See §C.3.2 for details about escape characters. Wide character literals are of the form L L´a ab b´, where the number of characters between the quotes and their meanings is implementation-defined to match the w wc ch ha ar r_ _t t type. A wide character literal has type w wc ch ha ar r_ _t t. 4.4 Integer Types [dcl.int] Like c ch ha ar r, each integer type comes in three forms: ‘‘plain’’ i in nt t, s si ig gn ne ed d i in nt t, and u un ns si ig gn ne ed d i in nt t. In addition, integers come in three sizes: s sh ho or rt t i in nt t, ‘‘plain’’ i in nt t, and l lo on ng g i in nt t. A l lo on ng g i in nt t can be referred to as plain l lo on ng g. Similarly, s sh ho or rt t is a synonym for s sh ho or rt t i in nt t, u un ns si ig gn ne ed d for u un ns si ig gn ne ed d i in nt t, and s si ig gn ne ed d for s si ig gn ne ed d i in nt t. The u un ns si ig gn ne ed d integer types are ideal for uses that treat storage as a bit array. Using an u un ns si ig gn ne ed d instead of an i in nt t to gain one more bit to represent positive integers is almost never a good idea. Attempts to ensure that some values are positive by declaring variables u un ns si ig gn ne ed d will typi- cally be defeated by the implicit conversion rules (§C.6.1, §C.6.2.1). Unlike plain c ch ha ar rs, plain i in nt ts are always signed. The signed i in nt t types are simply more explicit synonyms for their plain i in nt t counterparts. 4.4.1 Integer Literals [dcl.int.lit] Integer literals come in four guises: decimal, octal, hexadecimal, and character literals. Decimal lit- erals are the most commonly used and look as you would expect them to: 0 0 1 12 23 34 4 9 97 76 6 1 12 23 34 45 56 67 78 89 90 01 12 23 34 45 56 67 78 89 90 0 The compiler ought to warn about literals that are too long to represent. A literal starting with zero followed by x x (0 0x x) is a hexadecimal (base 16) number. A literal starting with zero followed by a digit is an octal (base 8) number. For example: d de ec ci im ma al l: 0 0 2 2 6 63 3 8 83 3 o oc ct ta al l: 0 00 0 0 02 2 0 07 77 7 0 01 12 23 3 h he ex xa ad de ec ci im ma al l: 0 0x x0 0 0 0x x2 2 0 0x x3 3f f 0 0x x5 53 3 The letters a a, b b, c c, d d, e e, and f f, or their uppercase equivalents, are used to represent 1 10 0, 1 11 1, 1 12 2, 1 13 3, 1 14 4, and 1 15 5, respectively. Octal and hexadecimal notations are most useful for expressing bit pat- terns. Using these notations to express genuine numbers can lead to surprises. For example, on a machine on which an i in nt t is represented as a two’s complement 16-bit integer, 0 0x xf ff ff ff f is the negative decimal number -1 1. Had more bits been used to represent an integer, it would have been 6 65 55 53 35 5. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.74 Types and Declarations Chapter 4 The suffix U U can be used to write explicitly u un ns si ig gn ne ed d literals. Similarly, the suffix L L can be used to write explicitly l lo on ng g literals. For example, 3 3 is an i in nt t, 3U is an u un ns si ig gn ne ed d i in nt t, and 3 3L L is a l lo on ng g i in nt t. If no suffix is provided, the compiler gives an integer literal a suitable type based on its value and the implementation’s integer sizes (§C.4). It is a good idea to limit the use of nonobvious constants to a few well-commented c co on ns st t (§5.4) or enumerator (§4.8) initializers. 4.5 Floating-Point Types [dcl.float] The floating-point types represent floating-point numbers. Like integers, floating-point types come in three sizes: f fl lo oa at t (single-precision), d do ou ub bl le e (double-precision), and l lo on ng g d do ou ub bl le e (extended- precision). The exact meaning of single-, double-, and extended-precision is implementation-defined. Choosing the right precision for a problem where the choice matters requires significant under- standing of floating-point computation. If you don’t have that understanding, get advice, take the time to learn, or use d do ou ub bl le e and hope for the best. 4.5.1 Floating-Point Literals [dcl.fp.lit] By default, a floating-point literal is of type d do ou ub bl le e. Again, a compiler ought to warn about floating-point literals that are too large to be represented. Here are some floating-point literals: 1 1.2 23 3 .2 23 3 0 0.2 23 3 1 1. 1 1.0 0 1 1.2 2e e1 10 0 1 1.2 23 3e e-1 15 5 Note that a space cannot occur in the middle of a floating-point literal. For example, 6 65 5.4 43 3 e e-2 21 1 is not a floating-point literal but rather four separate lexical tokens (causing a syntax error): 6 65 5.4 43 3 e e - 2 21 1 If you want a floating-point literal of type f fl lo oa at t, you can define one using the suffix f f or F F: 3 3.1 14 41 15 59 92 26 65 5f f 2 2.0 0f f 2 2.9 99 97 79 92 25 5F F 4.6 Sizes [dcl.size] Some of the aspects of C++’s fundamental types, such as the size of an i in nt t, are implementation- defined (§C.2). I point out these dependencies and often recommend avoiding them or taking steps to minimize their impact. Why should you bother? People who program on a variety of systems or use a variety of compilers care a lot because if they don’t, they are forced to waste time finding and fixing obscure bugs. People who claim they don’t care about portability usually do so because they use only a single system and feel they can afford the attitude that ‘‘the language is what my com- piler implements.’’ This is a narrow and shortsighted view. If your program is a success, it is likely to be ported, so someone will have to find and fix problems related to implementation- dependent features. In addition, programs often need to be compiled with other compilers for the same system, and even a future release of your favorite compiler may do some things differently from the current one. It is far easier to know and limit the impact of implementation dependencies The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 4.6 Sizes 75 when a program is written than to try to untangle the mess afterwards. It is relatively easy to limit the impact of implementation-dependent language features. Limit- ing the impact of system-dependent library facilities is far harder. Using standard library facilities wherever feasible is one approach. The reason for providing more than one integer type, more than one unsigned type, and more than one floating-point type is to allow the programmer to take advantage of hardware characteris- tics. On many machines, there are significant differences in memory requirements, memory access times, and computation speed between the different varieties of fundamental types. If you know a machine, it is usually easy to choose, for example, the appropriate integer type for a particular vari- able. Writing truly portable low-level code is harder. Sizes of C++ objects are expressed in terms of multiples of the size of a c ch ha ar r, so by definition the size of a c ch ha ar r is 1 1. The size of an object or type can be obtained using the s si iz ze eo of f operator (§6.2). This is what is guaranteed about sizes of fundamental types: 1 ≡ sizeof(char) ≤ sizeof(short) ≤ sizeof(int) ≤ sizeof(long) 1 ≤ sizeof(bool) ≤ sizeof(long) sizeof(char) ≤ sizeof(wchar_t) ≤ sizeof(long) sizeof(float) ≤ sizeof(double) ≤ sizeof(long double) sizeof(N) ≡ sizeof(signed N) ≡ sizeof(unsigned N) where N N can be c ch ha ar r, s sh ho or rt t i in nt t, i in nt t, or l lo on ng g i in nt t. In addition, it is guaranteed that a c ch ha ar r has at least 8 bits, a s sh ho or rt t at least 16 bits, and a l lo on ng g at least 32 bits. A c ch ha ar r can hold a character of the machine’s character set. Here is a graphical representation of a plausible set of fundamental types and a sample string: ’a’ 1 756 100000000 &c1 1234567e34 Hello, world!\0 char: bool: short: int: int*: double: char[14]: On the same scale (.2 inch to a byte), a megabyte of memory would stretch about three miles (five km) to the right. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.76 Types and Declarations Chapter 4 The c ch ha ar r type is supposed to be chosen by the implementation to be the most suitable type for holding and manipulating characters on a given computer; it is typically an 8-bit byte. Similarly, the i in nt t type is supposed to be chosen to be the most suitable for holding and manipulating integers on a given computer; it is typically a 4-byte (32-bit) word. It is unwise to assume more. For exam- ple, there are machines with 32 bit c ch ha ar rs. When needed, implementation-dependent aspects about an implementation can be found in (§22.2). For example: #i in nc cl lu ud de e i in nt t m ma ai in n() { c co ou ut t << "l la ar rg ge es st t f fl lo oa at t == " << n nu um me er ri ic c_ _l li im mi it ts s: :m ma ax x() << ", c ch ha ar r i is s s si ig gn ne ed d == " << n nu um me er ri ic c_ _l li im mi it ts s: :i is s_ _s si ig gn ne ed d << ´\ \n n´; } The fundamental types can be mixed freely in assignments and expressions. Wherever possible, values are converted so as not to lose information (§C.6). If a value v v can be represented exactly in a variable of type T T, a conversion of v v to T T is value- preserving and no problem. The cases where conversions are not value-preserving are best avoided (§C.6.2.6). You need to understand implicit conversion in some detail in order to complete a major project and especially to understand real code written by others. However, such understanding is not required to read the following chapters. 4.7 Void [dcl.void] The type v vo oi id d is syntactically a fundamental type. It can, however, be used only as part of a more complicated type; there are no objects of type v vo oi id d. It is used either to specify that a function does not return a value or as the base type for pointers to objects of unknown type. For example: v vo oi id d x x; / / error: there are no void objects v vo oi id d f f() ; / / function f does not return a value (§7.3) v vo oi id d* p pv v; / / pointer to object of unknown type (§5.6) When declaring a function, you must specify the type of the value returned. Logically, you would expect to be able to indicate that a function didn’t return a value by omitting the return type. How- ever, that would make the grammar (Appendix A) less regular and clash with C usage. Conse- quently, v vo oi id d is used as a ‘‘pseudo return type’’ to indicate that a function doesn’t return a value. 4.8 Enumerations [dcl.enum] An enumeration is a type that can hold a set of values specified by the user. Once defined, an enu- meration is used very much like an integer type. Named integer constants can be defined as members of an enumeration. For example, e en nu um m { A AS SM M, A AU UT TO O, B BR RE EA AK K }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 4.8 Enumerations 77 defines three integer constants, called enumerators, and assigns values to them. By default, enu- merator values are assigned increasing from 0 0, so A AS SM M==0 0, A AU UT TO O==1 1, and B BR RE EA AK K==2 2. An enu- meration can be named. For example: e en nu um m k ke ey yw wo or rd d { A AS SM M, A AU UT TO O, B BR RE EA AK K }; Each enumeration is a distinct type. The type of an enumerator is its enumeration. For example, A AU UT TO O is of type k ke ey yw wo or rd d. Declaring a variable k ke ey yw wo or rd d instead of plain i in nt t can give both the user and the compiler a hint as to the intended use. For example: v vo oi id d f f(k ke ey yw wo or rd d k ke ey y) { s sw wi it tc ch h (k ke ey y) { c ca as se e A AS SM M: / / do something b br re ea ak k; c ca as se e B BR RE EA AK K: / / do something b br re ea ak k; } } A compiler can issue a warning because only two out of three k ke ey yw wo or rd d values are handled. An enumerator can be initialized by a constant-expression (§C.5) of integral type (§4.1.1). The range of an enumeration holds all the enumeration’s enumerator values rounded up to the nearest larger binary power minus 1 1. The range goes down to 0 0 if the smallest enumerator is non-negative and to the nearest lesser negative binary power if the smallest enumerator is negative. This defines the smallest bit-field capable of holding the enumerator values. For example: e en nu um m e e1 1 { d da ar rk k, l li ig gh ht t }; / / range 0:1 e en nu um m e e2 2 { a a = 3 3, b b = 9 9 }; / / range 0:15 e en nu um m e e3 3 { m mi in n = -1 10 0, m ma ax x = 1 10 00 00 00 00 00 0 }; / / range -1048576:1048575 A value of integral type may be explicitly converted to an enumeration type. The result of such a conversion is undefined unless the value is within the range of the enumeration. For example: e en nu um m f fl la ag g { x x=1 1, y y=2 2, z z=4 4, e e=8 8 }; / / range 0:15 f fl la ag g f f1 1 = 5 5; / / type error: 5 is not of type flag f fl la ag g f f2 2 = f fl la ag g(5 5) ; / / ok: flag(5) is of type flag and within the range of flag f fl la ag g f f3 3 = f fl la ag g(z z|e e) ; / / ok: flag(12) is of type flag and within the range of flag f fl la ag g f f4 4 = f fl la ag g(9 99 9) ; / / undefined: 99 is not within the range of flag The last assignment shows why there is no implicit conversion from an integer to an enumeration; most integer values do not have a representation in a particular enumeration. The notion of a range of values for an enumeration differs from the enumeration notion in the Pascal family of languages. However, bit-manipulation examples that require values outside the set of enumerators to be well-defined have a long history in C and C++. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.78 Types and Declarations Chapter 4 The s si iz ze eo of f an enumeration is the s si iz ze eo of f some integral type that can hold its range and not larger than s si iz ze eo of f(i in nt t), unless an enumerator cannot be represented as an i in nt t or as an u un ns si ig gn ne ed d i in nt t. For example, s si iz ze eo of f(e e1 1) could be 1 1 or maybe 4 4 but not 8 8 on a machine where s si iz ze eo of f(i in nt t)==4 4. By default, enumerations are converted to integers for arithmetic operations (§6.2). An enumer- ation is a user-defined type, so users can define their own operations, such as ++ and << for an enu- meration (§11.2.3). 4.9 Declarations [dcl.dcl] Before a name (identifier) can be used in a C++ program, it must be declared. That is, its type must be specified to inform the compiler to what kind of entity the name refers. Here are some examples illustrating the diversity of declarations: c ch ha ar r c ch h; s st tr ri in ng g s s; i in nt t c co ou un nt t = 1 1; c co on ns st t d do ou ub bl le e p pi i = 3 3.1 14 41 15 59 92 26 65 53 35 58 89 97 79 93 32 23 38 85 5; e ex xt te er rn n i in nt t e er rr ro or r_ _n nu um mb be er r; c ch ha ar r* n na am me e = "N Nj ja al l"; c ch ha ar r* s se ea as so on n[] = { "s sp pr ri in ng g", "s su um mm me er r", "f fa al ll l", "w wi in nt te er r" }; s st tr ru uc ct t D Da at te e { i in nt t d d, m m, y y; }; i in nt t d da ay y(D Da at te e* p p) { r re et tu ur rn n p p->d d; } d do ou ub bl le e s sq qr rt t(d do ou ub bl le e) ; t te em mp pl la at te e T T a ab bs s(T T a a) { r re et tu ur rn n a a<0 0 ? -a a : a a; } t ty yp pe ed de ef f c co om mp pl le ex x P Po oi in nt t; s st tr ru uc ct t U Us se er r; e en nu um m B Be ee er r { C Ca ar rl ls sb be er rg g, T Tu ub bo or rg g, T Th ho or r }; n na am me es sp pa ac ce e N NS S { i in nt t a a; } As can be seen from these examples, a declaration can do more than simply associate a type with a name. Most of these declarations are also definitions; that is, they also define an entity for the name to which they refer. For c ch h, that entity is the appropriate amount of memory to be used as a variable ± that memory will be allocated. For d da ay y, it is the specified function. For the constant p pi i, it is the value 3 3.1 14 41 15 59 92 26 65 53 35 58 89 97 79 93 32 23 38 85 5. For D Da at te e, that entity is a new type. For P Po oi in nt t, it is the type c co om mp pl le ex x so that P Po oi in nt t becomes a synonym for c co om mp pl le ex x. Of the declarations above, only d do ou ub bl le e s sq qr rt t(d do ou ub bl le e) ; e ex xt te er rn n i in nt t e er rr ro or r_ _n nu um mb be er r; s st tr ru uc ct t U Us se er r; are not also definitions; that is, the entity they refer to must be defined elsewhere. The code (body) for the function s sq qr rt t must be specified by some other declaration, the memory for the i in nt t variable e er rr ro or r_ _n nu um mb be er r must be allocated by some other declaration of e er rr ro or r_ _n nu um mb be er r, and some other declaration of the type U Us se er r must define what that type looks like. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 4.9 Declarations 79 d do ou ub bl le e s sq qr rt t(d do ou ub bl le e d d) { /* ... */ } i in nt t e er rr ro or r_ _n nu um mb be er r = 1 1; s st tr ru uc ct t U Us se er r { /* ... */ }; There must always be exactly one definition for each name in a C++ program (for the effects of #i in nc cl lu ud de e, see §9.2.3). However, there can be many declarations. All declarations of an entity must agree on the type of the entity referred to. So, this fragment has two errors: i in nt t c co ou un nt t; i in nt t c co ou un nt t; / / error: redefinition e ex xt te er rn n i in nt t e er rr ro or r_ _n nu um mb be er r; e ex xt te er rn n s sh ho or rt t e er rr ro or r_ _n nu um mb be er r; / / error: type mismatch and this has none (for the use of e ex xt te er rn n see §9.2): e ex xt te er rn n i in nt t e er rr ro or r_ _n nu um mb be er r; e ex xt te er rn n i in nt t e er rr ro or r_ _n nu um mb be er r; Some definitions specify a ‘‘value’’ for the entities they define. For example: s st tr ru uc ct t D Da at te e { i in nt t d d, m m, y y; }; t ty yp pe ed de ef f c co om mp pl le ex x P Po oi in nt t; i in nt t d da ay y(D Da at te e* p p) { r re et tu ur rn n p p->d d; } c co on ns st t d do ou ub bl le e p pi i = 3 3.1 14 41 15 59 92 26 65 53 35 58 89 97 79 93 32 23 38 85 5; For types, templates, functions, and constants, the ‘‘value’’ is permanent. For nonconstant data types, the initial value may be changed later. For example: v vo oi id d f f() { i in nt t c co ou un nt t = 1 1; c ch ha ar r* n na am me e = "B Bj ja ar rn ne e"; / / ... c co ou un nt t = 2 2; n na am me e = "M Ma ar ri ia an n"; } Of the definitions, only c ch ha ar r c ch h; s st tr ri in ng g s s; do not specify values. See §4.9.5 and §10.4.2 for explanations of how and when a variable is assigned a default value. Any declaration that specifies a value is a definition. 4.9.1 The Structure of a Declaration [dcl.parts] A declaration consists of four parts: an optional ‘‘specifier,’’ a base type, a declarator, and an optional initializer. Except for function and namespace definitions, a declaration is terminated by a semicolon. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.80 Types and Declarations Chapter 4 c ch ha ar r* k ki in ng gs s[] = { "A An nt ti ig go on nu us s", "S Se el le eu uc cu us s", "P Pt to ol le em my y" }; Here, the base type is c ch ha ar r, the declarator is *k ki in ng gs s[], and the initializer is ={...}. A specifier is an initial keyword, such as v vi ir rt tu ua al l (§2.5.5, §12.2.6) and e ex xt te er rn n (§9.2), that speci- fies some non-type attribute of what is being declared. A declarator is composed of a name and optionally some declarator operators. The most com- mon declarator operators are (§A.7.1): * p po oi in nt te er r p pr re ef fi ix x *c co on ns st t c co on ns st ta an nt t p po oi in nt te er r p pr re ef fi ix x & r re ef fe er re en nc ce e p pr re ef fi ix x [] a ar rr ra ay y p po os st tf fi ix x () f fu un nc ct ti io on n p po os st tf fi ix x Their use would be simple if they were all either prefix or postfix. However, *, [], and () were designed to mirror their use in expressions (§6.2). Thus, * is prefix and [] and () are postfix. The postfix declarator operators bind tighter than the prefix ones. Consequently, *k ki in ng gs s[] is a vector of pointers to something, and we have to use parentheses to express types such as ‘‘pointer to function;’’ see examples in §5.1. For full details, see the grammar in Appendix A. Note that the type cannot be left out of a declaration. For example: c co on ns st t c c = 7 7; / / error: no type g gt t(i in nt t a a, i in nt t b b) { r re et tu ur rn n (a a>b b) ? a a : b b; } / / error: no return type u un ns si ig gn ne ed d u ui i; / / ok: ‘unsigned’ is the type ‘unsigned int’ l lo on ng g l li i; / / ok: ‘long’ is the type ‘long int’ In this, standard C++ differs from earlier versions of C and C++ that allowed the first two examples by considering i in nt t to be the type when none were specified (§B.2). This ‘‘implicit i in nt t’’ rule was a source of subtle errors and confusion. 4.9.2 Declaring Multiple Names [dcl.multi] It is possible to declare several names in a single declaration. The declaration simply contains a list of comma-separated declarators. For example, we can declare two integers like this: i in nt t x x, y y; / / int x; int y; Note that operators apply to individual names only ± and not to any subsequent names in the same declaration. For example: i in nt t* p p, y y; / / int* p; int y; NOT int* y; i in nt t x x, *q q; / / int x; int* q; i in nt t v v[1 10 0] , *p pv v; / / int v[10]; int* pv; Such constructs make a program less readable and should be avoided. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 4.9.3 Names 81 4.9.3 Names [dcl.name] A name (identifier) consists of a sequence of letters and digits. The first character must be a letter. The underscore character _ _ is considered a letter. C++ imposes no limit on the number of charac- ters in a name. However, some parts of an implementation are not under the control of the com- piler writer (in particular, the linker), and those parts, unfortunately, sometimes do impose limits. Some run-time environments also make it necessary to extend or restrict the set of characters accepted in an identifier. Extensions (e.g., allowing the character $ in a name) yield nonportable programs. A C++ keyword (Appendix A), such as n ne ew w and i in nt t, cannot be used as a name of a user-defined entity. Examples of names are: h he el ll lo o t th hi is s_ _i is s_ _a a_ _m mo os st t_ _u un nu us su ua al ll ly y_ _l lo on ng g_ _n na am me e D DE EF FI IN NE ED D f fo oO O b bA Ar r u u_ _n na am me e H Ho or rs se eS Se en ns se e v va ar r0 0 v va ar r1 1 C CL LA AS SS S _ _c cl la as ss s _ __ __ _ Examples of character sequences that cannot be used as identifiers are: 0 01 12 2 a a f fo oo ol l $s sy ys s c cl la as ss s 3 3v va ar r p pa ay y.d du ue e f fo oo o~b ba ar r .n na am me e i if f Names starting with an underscore are reserved for special facilities in the implementation and the run-time environment, so such names should not be used in application programs. When reading a program, the compiler always looks for the longest string of characters that could make up a name. Hence, v va ar r1 10 0 is a single name, not the name v va ar r followed by the number 1 10 0. Also, e el ls se ei if f is a single name, not the keyword e el ls se e followed by the keyword i if f. Uppercase and lowercase letters are distinct, so C Co ou un nt t and c co ou un nt t are different names, but it is unwise to choose names that differ only by capitalization. In general, it is best to avoid names that differ only in subtle ways. For example, the uppercase o (O O) and zero (0 0) can be hard to tell apart, as can the lowercase L (l l) and one (1 1). Consequently, l l0 0, l lO O, l l1 1, and l ll l are poor choices for identi- fier names. Names from a large scope ought to have relatively long and reasonably obvious names, such as v ve ec ct to or r, W Wi in nd do ow w_ _w wi it th h_ _b bo or rd de er r, and D De ep pa ar rt tm me en nt t_ _n nu um mb be er r. However, code is clearer if names used only in a small scope have short, conventional names such as x x, i i, and p p. Classes (Chapter 10) and namespaces (§8.2) can be used to keep scopes small. It is often useful to keep frequently used names relatively short and reserve really long names for infrequently used entities. Choose names to reflect the meaning of an entity rather than its implementation. For example, p ph ho on ne e_ _b bo oo ok k is bet- ter than n nu um mb be er r_ _l li is st t even if the phone numbers happen to be stored in a l li is st t (§3.7). Choosing good names is an art. Try to maintain a consistent naming style. For example, capitalize nonstandard library user- defined types and start nontypes with a lowercase letter (for example, S Sh ha ap pe e and c cu ur rr re en nt t_ _t to ok ke en n). Also, use all capitals for macros (if you must use macros; for example, H HA AC CK K) and use underscores to separate words in an identifier. However, consistency is hard to achieve because programs are typically composed of fragments from different sources and several different reasonable styles are in use. Be consistent in your use of abbreviations and acronyms. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.82 Types and Declarations Chapter 4 4.9.4 Scope [dcl.scope] A declaration introduces a name into a scope; that is, a name can be used only in a specific part of the program text. For a name declared in a function (often called a local name), that scope extends from its point of declaration to the end of the block in which its declaration occurs. A block is a section of code delimited by a { } pair. A name is called global if it is defined outside any function, class (Chapter 10), or namespace (§8.2). The scope of a global name extends from the point of declaration to the end of the file in which its declaration occurs. A declaration of a name in a block can hide a declaration in an enclosing block or a global name. That is, a name can be redefined to refer to a different entity within a block. After exit from the block, the name resumes its previous meaning. For example: i in nt t x x; / / global x v vo oi id d f f() { i in nt t x x; / / local x hides global x x x = 1 1; / / assign to local x { i in nt t x x; / / hides first local x x x = 2 2; / / assign to second local x } x x = 3 3; / / assign to first local x } i in nt t* p p = &x x; / / take address of global x Hiding names is unavoidable when writing large programs. However, a human reader can easily fail to notice that a name has been hidden. Because such errors are relatively rare, they can be very difficult to find. Consequently, name hiding should be minimized. Using names such as i i and x x for global variables or for local variables in a large function is asking for trouble. A hidden global name can be referred to using the scope resolution operator : :. For example: i in nt t x x; v vo oi id d f f2 2() { i in nt t x x = 1 1; / / hide global x : :x x = 2 2; / / assign to global x x x = 2 2; / / assign to local x / / ... } There is no way to use a hidden local name. The scope of a name starts at its point of declaration; that is, after the complete declarator and before the initializer. This implies that a name can be used even to specify its own initial value. For example: i in nt t x x; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 4.9.4 Scope 83 v vo oi id d f f3 3() { i in nt t x x = x x; / / perverse: initialize x with its own (uninitialized) value } This is not illegal, just silly. A good compiler will warn if a variable is used before it has been set (see also §5.9[9]). It is possible to use a single name to refer to two different objects in a block without using the : : operator. For example: i in nt t x x = 1 11 1; v vo oi id d f f4 4() / / perverse: { i in nt t y y = x x; / / use global x: y = 11 i in nt t x x = 2 22 2; y y = x x; / / use local x: y = 22 } Function argument names are considered declared in the outermost block of a function, so v vo oi id d f f5 5(i in nt t x x) { i in nt t x x; / / error } is an error because x x is defined twice in the same scope. Having this be an error allows a not uncommon, subtle mistake to be caught. 4.9.5 Initialization [dcl.init] If an initializer is specified for an object, that initializer determines the initial value of an object. If no initializer is specified, a global (§4.9.4), namespace (§8.2), or local static object (§7.1.2, §10.2.4) (collectively called static objects) is initialized to 0 0 of the appropriate type. For example: i in nt t a a; / / means ‘‘int a = 0;’’ d do ou ub bl le e d d; / / means ‘‘double d = 0.0;’’ Local variables (sometimes called automatic objects) and objects created on the free store (some- times called dynamic objects or heap objects) are not initialized by default. For example: v vo oi id d f f() { i in nt t x x; / / x does not have a well-defined value / / ... } Members of arrays and structures are default initialized or not depending on whether the array or structure is static. User-defined types may have default initialization defined (§10.4.2). More complicated objects require more than one value as an initializer. This is handled by ini- tializer lists delimited by { and } for C-style initialization of arrays (§5.2.1) and structures (§5.7). For user-defined types with constructors, function-style argument lists are used (§2.5.2, §10.2.3). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.84 Types and Declarations Chapter 4 Note that an empty pair of parentheses () in a declaration always means ‘‘function’’ (§7.1). For example: i in nt t a a[] = { 1 1, 2 2 }; / / array initializer P Po oi in nt t z z(1 1,2 2) ; / / function-style initializer (initialization by constructor) i in nt t f f() ; / / function declaration 4.9.6 Objects and Lvalues [dcl.objects] We can allocate and use ‘‘variables’’ that do not have names, and it is possible to assign to strange-looking expressions (e.g., *p p[a a+1 10 0]=7 7). Consequently, there is a need for a name for ‘‘something in memory.’’ This is the simplest and most fundamental notion of an object. That is, an object is a contiguous region of storage; an lvalue is an expression that refers to an object. The word lvalue was originally coined to mean ‘‘something that can be on the left-hand side of an assignment.’’ However, not every lvalue may be used on the left-hand side of an assignment; an lvalue can refer to a constant (§5.5). An lvalue that has not been declared c co on ns st t is often called a modifiable lvalue. This simple and low-level notion of an object should not be confused with the notions of class object and object of polymorphic type (§15.4.3). Unless the programmer specifies otherwise (§7.1.2, §10.4.8), an object declared in a function is created when its definition is encountered and destroyed when its name goes out of scope (§10.4.4). Such objects are called automatic objects. Objects declared in global or namespace scope and s st ta at t- - i ic cs declared in functions or classes are created and initialized once (only) and ‘‘live’’ until the pro- gram terminates (§10.4.9). Such objects are called static objects. Array elements and nonstatic structure or class members have their lifetimes determined by the object of which they are part. Using the n ne ew w and d de el le et te e operators, you can create objects whose lifetimes are controlled directly (§6.2.6). 4.9.7 Typedef [dcl.typedef] A declaration prefixed by the keyword t ty yp pe ed de ef f declares a new name for the type rather than a new variable of the given type. For example: t ty yp pe ed de ef f c ch ha ar r* P Pc ch ha ar r; P Pc ch ha ar r p p1 1, p p2 2; / / p1 and p2 are char*s c ch ha ar r* p p3 3 = p p1 1; A name defined like this, usually called a ‘‘ t ty yp pe ed de ef f,’’ can be a convenient shorthand for a type with an unwieldy name. For example, u un ns si ig gn ne ed d c ch ha ar r is too long for really frequent use, so we could define a synonym, u uc ch ha ar r: t ty yp pe ed de ef f u un ns si ig gn ne ed d c ch ha ar r u uc ch ha ar r; Another use of a t ty yp pe ed de ef f is to limit the direct reference to a type to one place. For example: t ty yp pe ed de ef f i in nt t i in nt t3 32 2; t ty yp pe ed de ef f s sh ho or rt t i in nt t1 16 6; If we now use i in nt t3 32 2 wherever we need a potentially large integer, we can port our program to a machine on which s si iz ze eo of f(i in nt t) is 2 2 by redefining the single occurrence of i in nt t in our code: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 4.9.7 Typedef 85 t ty yp pe ed de ef f l lo on ng g i in nt t3 32 2; For good and bad, t ty yp pe ed de ef fs are synonyms for other types rather than distinct types. Consequently, t ty yp pe ed de ef fs mix freely with the types for which they are synonyms. People who would like to have distinct types with identical semantics or identical representation should look at enumerations (§4.8) or classes (Chapter 10). 4.10 Advice [dcl.advice] [1] Keep scopes small; §4.9.4. [2] Don’t use the same name in both a scope and an enclosing scope; §4.9.4. [3] Declare one name (only) per declaration; §4.9.2. [4] Keep common and local names short, and keep uncommon and nonlocal names longer; §4.9.3. [5] Avoid similar-looking names; §4.9.3. [6] Maintain a consistent naming style; §4.9.3. [7] Choose names carefully to reflect meaning rather than implementation; §4.9.3. [8] Use a t ty yp pe ed de ef f to define a meaningful name for a built-in type in cases in which the built-in type used to represent a value might change; §4.9.7. [9] Use t ty yp pe ed de ef fs to define synonyms for types; use enumerations and classes to define new types; §4.9.7. [10] Remember that every declaration must specify a type (there is no ‘‘implicit i in nt t’’); §4.9.1. [11] Avoid unnecessary assumptions about the numeric value of characters; §4.3.1, §C.6.2.1. [12] Avoid unnecessary assumptions about the size of integers; §4.6. [13] Avoid unnecessary assumptions about the range of floating-point types; §4.6. [14] Prefer a plain i in nt t over a s sh ho or rt t i in nt t or a l lo on ng g i in nt t; §4.6. [15] Prefer a d do ou ub bl le e over a f fl lo oa at t or a l lo on ng g d do ou ub bl le e; §4.5. [16] Prefer plain c ch ha ar r over s si ig gn ne ed d c ch ha ar r and u un ns si ig gn ne ed d c ch ha ar r; §C.3.4. [17] Avoid making unnecessary assumptions about the sizes of objects; §4.6. [18] Avoid unsigned arithmetic; §4.4. [19] View s si ig gn ne ed d to u un ns si ig gn ne ed d and u un ns si ig gn ne ed d to s si ig gn ne ed d conversions with suspicion; §C.6.2.6. [20] View floating-point to integer conversions with suspicion; §C.6.2.6. [21] View conversions to a smaller type, such as i in nt t to c ch ha ar r, with suspicion; §C.6.2.6. 4.11 Exercises [dcl.exercises] 1. (∗2) Get the ‘‘Hello, world!’’ program (§3.2) to run. If that program doesn’t compile as writ- ten, look at §B.3.1. 2. (∗1) For each declaration in §4.9, do the following: If the declaration is not a definition, write a definition for it. If the declaration is a definition, write a declaration for it that is not also a defi- nition. 3. (∗1.5) Write a program that prints the sizes of the fundamental types, a few pointer types, and a few enumerations of your choice. Use the s si iz ze eo of f operator. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.86 Types and Declarations Chapter 4 4. (∗1.5) Write a program that prints out the letters ´a a´..´z z´ and the digits ´0 0´..´9 9´ and their integer values. Do the same for other printable characters. Do the same again but use hexa- decimal notation. 5. (∗2) What, on your system, are the largest and the smallest values of the following types: c ch ha ar r, s sh ho or rt t, i in nt t, l lo on ng g, f fl lo oa at t, d do ou ub bl le e, l lo on ng g d do ou ub bl le e, and u un ns si ig gn ne ed d. 6. (∗1) What is the longest local name you can use in a C++ program on your system? What is the longest external name you can use in a C++ program on your system? Are there any restrictions on the characters you can use in a name? 7. (∗2) Draw a graph of the integer and fundamental types where a type points to another type if all values of the first can be represented as values of the second on every standards-conforming implementation. Draw the same graph for the types on your favorite implementation. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 5 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Pointers, Arrays, and Structures The sublime and the ridiculous are often so nearly related that it is difficult to class them separately. ± Tom Paine Pointers Ð zero Ð arrays Ð string literals Ð pointers into arrays Ð constants Ð point- ers and constants Ð references Ð v vo oi id d* Ð data structures Ð advice Ð exercises. 5.1 Pointers [ptr.ptr] For a type T T, T T* is the type ‘‘pointer to T T.’’ That is, a variable of type T T* can hold the address of an object of type T T. For example: c ch ha ar r c c = ´a a´; c ch ha ar r* p p = &c c; / / p holds the address of c or graphically: &c c . .’a a’ p p: c c: Unfortunately, pointers to arrays and pointers to functions need a more complicated notation: i in nt t* p pi i; / / pointer to int c ch ha ar r** p pp pc c; / / pointer to pointer to char i in nt t* a ap p[1 15 5] ; / / array of 15 pointers to ints i in nt t (*f fp p)(c ch ha ar r*) ; / / pointer to function taking a char* argument; returns an int i in nt t* f f(c ch ha ar r*) ; / / function taking a char* argument; returns a pointer to int See §4.9.1 for an explanation of the declaration syntax and Appendix A for the complete grammar. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.88 Pointers, Arrays, and Structures Chapter 5 The fundamental operation on a pointer is dereferencing, that is, referring to the object pointed to by the pointer. This operation is also called indirection. The dereferencing operator is (prefix) unary *. For example: c ch ha ar r c c = ´a a´; c ch ha ar r* p p = &c c; / / p holds the address of c c ch ha ar r c c2 2 = *p p; / / c2 == ’a’ The variable pointed to by p p is c c, and the value stored in c c is ´a a´, so the value of *p p assigned to c c2 2 is ´a a´. It is possible to perform some arithmetic operations on pointers to array elements (§5.3). Point- ers to functions can be extremely useful; they are discussed in §7.7. The implementation of pointers is intended to map directly to the addressing mechanisms of the machine on which the program runs. Most machines can address a byte. Those that can’t tend to have hardware to extract bytes from words. On the other hand, few machines can directly address an individual bit. Consequently, the smallest object that can be independently allocated and pointed to using a built-in pointer type is a c ch ha ar r. Note that a b bo oo ol l occupies at least as much space as a c ch ha ar r (§4.6). To store smaller values more compactly, you can use logical operations (§6.2.4) or bit fields in structures (§C.8.1). 5.1.1 Zero [ptr.zero] Zero (0 0) is an i in nt t. Because of standard conversions (§C.6.2.3), 0 0 can be used as a constant of any integral (§4.1.1), floating-point, pointer, or pointer-to-member type. The type of zero will be deter- mined by context. Zero will typically (but not necessarily) be represented by the bit pattern all- zeros of the appropriate size. No object is allocated with the address 0 0. Consequently, 0 0 acts as a pointer literal, indicating that a pointer doesn’t refer to an object. In C, it has been popular to define a macro N NU UL LL L to represent the zero pointer. Because of C++’s tighter type checking, the use of plain 0 0, rather than any suggested N NU UL LL L macro, leads to fewer problems. If you feel you must define N NU UL LL L, use c co on ns st t i in nt t N NU UL LL L = 0 0; The c co on ns st t qualifier (§5.4) prevents accidental redefinition of N NU UL LL L and ensures that N NU UL LL L can be used where a constant is required. 5.2 Arrays [ptr.array] For a type T T, T T[s si iz ze e] is the type ‘‘array of s si iz ze e elements of type T T.’’ The elements are indexed from 0 0 to s si iz ze e-1 1. For example: f fl lo oa at t v v[3 3] ; / / an array of three floats: v[0], v[1], v[2] c ch ha ar r* a a[3 32 2] ; / / an array of 32 pointers to char: a[0] .. a[31] The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 5.2 Arrays 89 The number of elements of the array, the array bound, must be a constant expression (§C.5). If you need variable bounds, use a v ve ec ct to or r (§3.7.1, §16.3). For example: v vo oi id d f f(i in nt t i i) { i in nt t v v1 1[i i] ; / / error: array size not a constant expression v ve ec ct to or r v v2 2(i i) ; / / ok } Multidimensional arrays are represented as arrays of arrays. For example: i in nt t d d2 2[1 10 0][2 20 0] ; / / d2 is an array of 10 arrays of 20 integers Using comma notation as used for array bounds in some other languages gives compile-time errors because comma (,) is a sequencing operator (§6.2.2) and is not allowed in constant expressions (§C.5). For example, try this: i in nt t b ba ad d[5 5,2 2] ; / / error: comma not allowed in a constant expression Multidimensional arrays are described in §C.7. They are best avoided outside low-level code. 5.2.1 Array Initializers [ptr.array.init] An array can be initialized by a list of values. For example: i in nt t v v1 1[] = { 1 1, 2 2, 3 3, 4 4 }; c ch ha ar r v v2 2[] = { ´a a´, ´b b´, ´c c´, 0 0 }; When an array is declared without a specific size, but with an initializer list, the size is calculated by counting the elements of the initializer list. Consequently, v v1 1 and v v2 2 are of type i in nt t[4 4] and c ch ha ar r[4 4], respectively. If a size is explicitly specified, it is an error to give surplus elements in an initializer list. For example: c ch ha ar r v v3 3[2 2] = { ´a a´, ´b b´, 0 0 }; / / error: too many initializers c ch ha ar r v v4 4[3 3] = { ´a a´, ´b b´, 0 0 }; / / ok If the initializer supplies too few elements, 0 0 is assumed for the remaining array elements. For example: i in nt t v v5 5[8 8] = { 1 1, 2 2, 3 3, 4 4 }; is equivalent to i in nt t v v5 5[] = { 1 1, 2 2, 3 3, 4 4 , 0 0, 0 0, 0 0, 0 0 }; Note that there is no array assignment to match the initialization: v vo oi id d f f() { v v4 4 = { ´c c´, ´d d´, 0 0 }; / / error: no array assignment } When you need such assignments, use a v ve ec ct to or r (§16.3) or a v va al la ar rr ra ay y (§22.4) instead. An array of characters can be conveniently initialized by a string literal (§5.2.2). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.90 Pointers, Arrays, and Structures Chapter 5 5.2.2 String Literals [ptr.string.literal] A string literal is a character sequence enclosed within double quotes: "t th hi is s i is s a a s st tr ri in ng g" A string literal contains one more character than it appears to have; it is terminated by the null char- acter ´\ \0 0´, with the value 0 0. For example: s si iz ze eo of f("B Bo oh hr r")==5 5 The type of a string literal is ‘‘array of the appropriate number of c co on ns st t characters,’’ so " "B Bo oh hr r" " is of type c co on ns st t c ch ha ar r[5 5]. A string literal can be assigned to a c ch ha ar r*. This is allowed because in previous definitions of C and C++ , the type of a string literal was c ch ha ar r*. Allowing the assignment of a string literal to a c ch ha ar r* ensures that millions of lines of C and C++ remain valid. It is, however, an error to try to modify a string literal through such a pointer: v vo oi id d f f() { c ch ha ar r* p p = "P Pl la at to o"; p p[4 4] = ´e e´; / / error: assignment to const; result is undefined } This kind of error cannot in general be caught until run-time, and implementations differ in their enforcement of this rule. Having string literals constant not only is obvious, but also allows imple- mentations to do significant optimizations in the way string literals are stored and accessed. If we want a string that we are guaranteed to be able to modify, we must copy the characters into an array: v vo oi id d f f() { c ch ha ar r p p[] = "Z Ze en no o"; / / p is an array of 5 char p p[0 0] = ´R R´; / / ok } A string literal is statically allocated so that it is safe to return one from a function. For example: c co on ns st t c ch ha ar r* e er rr ro or r_ _m me es ss sa ag ge e(i in nt t i i) { / / ... r re et tu ur rn n "r ra an ng ge e e er rr ro or r"; } The memory holding r ra an ng ge e e er rr ro or r will not go away after a call of e er rr ro or r_ _m me es ss sa ag ge e(). Whether two identical character literals are allocated as one is implementation-defined (§C.1). For example: c co on ns st t c ch ha ar r* p p = "H He er ra ac cl li it tu us s"; c co on ns st t c ch ha ar r* q q = "H He er ra ac cl li it tu us s"; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 5.2.2 String Literals 91 v vo oi id d g g() { i if f (p p == q q) c co ou ut t << "o on ne e!\ \n n"; / / result is implementation-defined / / ... } Note that == compares addresses (pointer values) when applied to pointers, and not the values pointed to. The empty string is written as a pair of adjacent double quotes, "", (and has the type c co on ns st t c ch ha ar r[1 1]). The backslash convention for representing nongraphic characters (§C.3.2) can also be used within a string. This makes it possible to represent the double quote (") and the escape character backslash ( \ \) within a string. The most common such character by far is the newline character, ´\ \n n´. For example: c co ou ut t<<"b be ee ep p a at t e en nd d o of f m me es ss sa ag ge e\ \a a\ \n n"; The escape character ´\ \a a´ is the ASCII character B BE EL L (also known as alert), which causes some kind of sound to be emitted. It is not possible to have a ‘‘real’’ newline in a string: "t th hi is s i is s n no ot t a a s st tr ri in ng g b bu ut t a a s sy yn nt ta ax x e er rr ro or r" Long strings can be broken by whitespace to make the program text neater. For example: c ch ha ar r a al lp ph ha a[] = "a ab bc cd de ef fg gh hi ij jk kl lm mn no op pq qr rs st tu uv vw wx xy yz z" "A AB BC CD DE EF FG GH HI IJ JK KL LM MN NO OP PQ QR RS ST TU UV VW WX XY YZ Z"; The compiler will concatenate adjacent strings, so a al lp ph ha a could equivalently have been initialized by the single string: "a ab bc cd de ef fg gh hi ij jk kl lm mn no op pq qr rs st tu uv vw wx xy yz zA AB BC CD DE EF FG GH HI IJ JK KL LM MN NO OP PQ QR RS ST TU UV VW WX XY YZ Z"; It is possible to have the null character in a string, but most programs will not suspect that there are characters after it. For example, the string " "J Je en ns s\ \0 00 00 0M Mu un nk k" " will be treated as " "J Je en ns s" " by stan- dard library functions such as s st tr rc cp py y() and s st tr rl le en n(); see §20.4.1. A string with the prefix L L, such as L L"a an ng gs st t", is a string of wide characters (§4.3, §C.3.3). Its type is c co on ns st t w wc ch ha ar r_ _t t[]. 5.3 Pointers into Arrays [ptr.into] In C++, pointers and arrays are closely related. The name of an array can be used as a pointer to its initial element. For example: i in nt t v v[] = { 1 1, 2 2, 3 3, 4 4 }; i in nt t* p p1 1 = v v; / / pointer to initial element (implicit conversion) i in nt t* p p2 2 = &v v[0 0] ; / / pointer to initial element i in nt t* p p3 3 = &v v[4 4] ; / / pointer to one beyond last element or graphically: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.92 Pointers, Arrays, and Structures Chapter 5 p p1 1 p p2 2 p p3 3 . . 1 1 . . 2 2 . . 3 3 . . 4 4 . .v v: Taking a pointer to the element one beyond the end of an array is guaranteed to work. This is important for many algorithms (§2.7.2, §18.3). However, since such a pointer does not in fact point to an element of the array, it may not be used for reading or writing. The result of taking the address of the element before the initial element is undefined and should be avoided. On some machine architectures, arrays are often allocated on machine addressing boundaries, so ‘‘one before the initial element’’ simply doesn’t make sense. The implicit conversion of an array name to a pointer to the initial element of the array is exten- sively used in function calls in C-style code. For example: e ex xt te er rn n "C C" i in nt t s st tr rl le en n(c co on ns st t c ch ha ar r*) ; / / from v vo oi id d f f() { c ch ha ar r v v[] = "A An nn ne em ma ar ri ie e"; c ch ha ar r* p p = v v; / / implicit conversion of char[] to char* s st tr rl le en n(p p) ; s st tr rl le en n(v v) ; / / implicit conversion of char[] to char* v v = p p; / / error: cannot assign to array } The same value is passed to the standard library function s st tr rl le en n() in both calls. The snag is that it is impossible to avoid the implicit conversion. In other words, there is no way of declaring a func- tion so that the array v v is copied when the function is called. Fortunately, there is no implicit or explicit conversion from a pointer to an array. The implicit conversion of the array argument to a pointer means that the size of the array is lost to the called function. However, the called function must somehow determine the size to perform a meaningful operation. Like other C standard library functions taking pointers to characters, s st tr rl le en n() relies on zero to indicate end-of-string; s st tr rl le en n(p p) returns the number of characters up to and not including the terminating 0 0. This is all pretty low-level. The standard library v ve ec ct to or r (§16.3) and s st tr ri in ng g (Chapter 20) don’t suffer from this problem. 5.3.1 Navigating Arrays [ptr.navigate] Efficient and elegant access to arrays (and similar data structures) is the key to many algorithms (see §3.8, Chapter 18). Access can be achieved either through a pointer to an array plus an index or through a pointer to an element. For example, traversing a character string using an index, v vo oi id d f fi i(c ch ha ar r v v[]) { f fo or r (i in nt t i i = 0 0; v v[i i]!=0 0; i i++) u us se e(v v[i i]) ; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 5.3.1 Navigating Arrays 93 is equivalent to a traversal using a pointer: v vo oi id d f fp p(c ch ha ar r v v[]) { f fo or r (c ch ha ar r* p p = v v; *p p!=0 0; p p++) u us se e(*p p) ; } The prefix * operator dereferences a pointer so that *p p is the character pointed to by p p,and ++ increments the pointer so that it refers to the next element of the array. There is no inherent reason why one version should be faster than the other. With modern com- pilers, identical code should be generated for both examples (see §5.9[8]). Programmers can choose between the versions on logical and aesthetic grounds. The result of applying the arithmetic operators +, -, ++, or -- to pointers depends on the type of the object pointed to. When an arithmetic operator is applied to a pointer p p of type T T*, p p is assumed to point to an element of an array of objects of type T T; p p+1 1 points to the next element of that array, and p p-1 1 points to the previous element. This implies that the integer value of p p+1 1 will be s si iz ze eo of f(T T) larger than the integer value of p p. For example, executing #i in nc cl lu ud de e i in nt t m ma ai in n () { i in nt t v vi i[1 10 0] ; s sh ho or rt t v vs s[1 10 0] ; s st td d: :c co ou ut t << &v vi i[0 0] << ´ ´ << &v vi i[1 1] << ´\ \n n´; s st td d: :c co ou ut t << &v vs s[0 0] << ´ ´ << &v vs s[1 1] << ´\ \n n´; } produced 0 0x x7 7f ff ff fa ae ef f0 0 0 0x x7 7f ff ff fa ae ef f4 4 0 0x x7 7f ff ff fa ae ed dc c 0 0x x7 7f ff ff fa ae ed de e using a default hexadecimal notation for pointer values. This shows that on my implementation, s si iz ze eo of f(s sh ho or rt t) is 2 2 and s si iz ze eo of f(i in nt t) is 4 4. Subtraction of pointers is defined only when both pointers point to elements of the same array (although the language has no fast way of ensuring that is the case). When subtracting one pointer from another, the result is the number of array elements between the two pointers (an integer). One can add an integer to a pointer or subtract an integer from a pointer; in both cases, the result is a pointer value. If that value does not point to an element of the same array as the original pointer or one beyond, the result of using that value is undefined. For example: v vo oi id d f f() { i in nt t v v1 1[1 10 0] ; i in nt t v v2 2[1 10 0] ; i in nt t i i1 1 = &v v1 1[5 5]-&v v1 1[3 3] ; / / i1 = 2 i in nt t i i2 2 = &v v1 1[5 5]-&v v2 2[3 3] ; / / result undefined The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.94 Pointers, Arrays, and Structures Chapter 5 i in nt t* p p1 1 = v v2 2+2 2; / / p1 = &v2[2] i in nt t* p p2 2 = v v2 2-2 2; / / *p2 undefined } Complicated pointer arithmetic is usually unnecessary and often best avoided. Addition of pointers makes no sense and is not allowed. Arrays are not self-describing because the number of elements of an array is not guaranteed to be stored with the array. This implies that to traverse an array that does not contain a terminator the way character strings do, we must somehow supply the number of elements. For example: v vo oi id d f fp p(c ch ha ar r v v[] , u un ns si ig gn ne ed d i in nt t s si iz ze e) { f fo or r (i in nt t i i=0 0; i i p pa ai ir rs s; d do ou ub bl le e& v va al lu ue e(c co on ns st t s st tr ri in ng g& s s) /* maintain a set of Pairs: search for s, return its value if found; otherwise make a new Pair and return the default value 0 */ { The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.100 Pointers, Arrays, and Structures Chapter 5 f fo or r (i in nt t i i = 0 0; i i < p pa ai ir rs s.s si iz ze e() ; i i++) i if f (s s == p pa ai ir rs s[i i].n na am me e) r re et tu ur rn n p pa ai ir rs s[i i].v va al l; P Pa ai ir r p p = { s s, 0 0 }; p pa ai ir rs s.p pu us sh h_ _b ba ac ck k(p p) ; / / add Pair at end (§3.7.3) r re et tu ur rn n p pa ai ir rs s[p pa ai ir rs s.s si iz ze e()-1 1].v va al l; } This function can be understood as an array of floating-point values indexed by character strings. For a given argument string, v va al lu ue e() finds the corresponding floating-point object (not the value of the corresponding floating-point object); it then returns a reference to it. For example: i in nt t m ma ai in n() / / count the number of occurrences of each word on input { s st tr ri in ng g b bu uf f; w wh hi il le e (c ci in n>>b bu uf f) v va al lu ue e(b bu uf f)++; f fo or r (v ve ec ct to or r

: :c co on ns st t_ _i it te er ra at to or r p p = p pa ai ir rs s.b be eg gi in n() ; p p!=p pa ai ir rs s.e en nd d() ; ++p p) c co ou ut t << p p->n na am me e << ": " << p p->v va al l << ´\ \n n´; } Each time around, the w wh hi il le e-loop reads one word from the standard input stream c ci in n into the string b bu uf f (§3.6) and then updates the counter associated with it. Finally, the resulting table of different words in the input, each with its number of occurrences, is printed. For example, given the input a aa a b bb b b bb b a aa a a aa a b bb b a aa a a aa a this program will produce: a aa a: 5 5 b bb b: 3 3 It is easy to refine this into a proper associative array type by using a template class with the selec- tion operator [] overloaded (§11.8). It is even easier just to use the standard library m ma ap p (§17.4.1). 5.6 Pointer to Void [ptr.ptrtovoid] A pointer of any type of object can be assigned to a variable of type v vo oi id d*, a v vo oi id d* can be assigned to another v vo oi id d*, v vo oi id d*s can be compared for equality and inequality, and a v vo oi id d* can be explicitly converted to another type. Other operations would be unsafe because the compiler cannot know what kind of object is really pointed to. Consequently, other operations result in compile-time errors. To use a v vo oi id d*, we must explicitly convert it to a pointer to a specific type. For example: v vo oi id d f f(i in nt t* p pi i) { v vo oi id d* p pv v = p pi i; / / ok: implicit conversion of int* to void* *p pv v; / / error: can’t dereference void* p pv v++; / / error: can’t increment void* (the size of the object pointed to is unknown) The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 5.6 Pointer to Void 101 i in nt t* p pi i2 2 = s st ta at ti ic c_ _c ca as st t(p pv v) ; / / explicit conversion back to int* d do ou ub bl le e* p pd d1 1 = p pv v; / / error d do ou ub bl le e* p pd d2 2 = p pi i; / / error d do ou ub bl le e* p pd d3 3 = s st ta at ti ic c_ _c ca as st t(p pv v) ; / / unsafe } In general, it is not safe to use a pointer that has been converted (‘‘cast’’) to a type that differs from the type the object pointed to. For example, a machine may assume that every d do ou ub bl le e is allocated on an 8-byte boundary. If so, strange behavior could arise if p pi i pointed to an i in nt t that wasn’t allo- cated that way. This form of explicit type conversion is inherently unsafe and ugly. Consequently, the notation used, s st ta at ti ic c_ _c ca as st t, was designed to be ugly. The primary use for v vo oi id d* is for passing pointers to functions that are not allowed to make assumptions about the type of the object and for returning untyped objects from functions. To use such an object, we must use explicit type conversion. Functions using v vo oi id d* pointers typically exist at the very lowest level of the system, where real hardware resources are manipulated. For example: v vo oi id d* m my y_ _a al ll lo oc c(s si iz ze e_ _t t n n) ; / / allocate n bytes from my special heap Occurrences of v vo oi id d*s at higher levels of the system should be viewed with suspicion because they are likely indicators of design errors. Where used for optimization, v vo oi id d* can be hidden behind a type-safe interface (§13.5, §24.4.2). Pointers to functions (§7.7) and pointers to members (§15.5) cannot be assigned to v vo oi id d*s. 5.7 Structures [ptr.struct] An array is an aggregate of elements of the same type. A s st tr ru uc ct t is an aggregate of elements of (nearly) arbitrary types. For example: s st tr ru uc ct t a ad dd dr re es ss s { c ch ha ar r* n na am me e; / / "Jim Dandy" l lo on ng g i in nt t n nu um mb be er r; / / 61 c ch ha ar r* s st tr re ee et t; / / "South St" c ch ha ar r* t to ow wn n; / / "New Providence" c ch ha ar r s st ta at te e[2 2] ; / / ’N’ ’J’ l lo on ng g z zi ip p; / / 7974 }; This defines a new type called a ad dd dr re es ss s consisting of the items you need in order to send mail to someone. Note the semicolon at the end. This is one of very few places in C++ where it is neces- sary to have a semicolon after a curly brace, so people are prone to forget it. Variables of type a ad dd dr re es ss s can be declared exactly as other variables, and the individual members can be accessed using the . (dot) operator. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.102 Pointers, Arrays, and Structures Chapter 5 v vo oi id d f f() { a ad dd dr re es ss s j jd d; j jd d.n na am me e = "J Ji im m D Da an nd dy y"; j jd d.n nu um mb be er r = 6 61 1; } The notation used for initializing arrays can also be used for initializing variables of structure types. For example: a ad dd dr re es ss s j jd d = { "J Ji im m D Da an nd dy y", 6 61 1, "S So ou ut th h S St t", "N Ne ew w P Pr ro ov vi id de en nc ce e", {´N N´,´J J´}, 7 79 97 74 4 }; Using a constructor (§10.2.3) is usually better, however. Note that j jd d.s st ta at te e could not be initialized by the string " "N NJ J" ". Strings are terminated by the character ´\ \0 0´. Hence, " "N NJ J" " has three characters ± one more than will fit into j jd d.s st ta at te e. Structure objects are often accessed through pointers using the -> (structure pointer derefer- ence) operator. For example: v vo oi id d p pr ri in nt t_ _a ad dd dr r(a ad dd dr re es ss s* p p) { c co ou ut t << p p->n na am me e << ´\ \n n´ << p p->n nu um mb be er r << ´ ´ << p p->s st tr re ee et t << ´\ \n n´ << p p->t to ow wn n << ´\ \n n´ << p p->s st ta at te e[0 0] << p p->s st ta at te e[1 1] << ´ ´ << p p->z zi ip p << ´\ \n n´; } When p p is a pointer, p p->m m is equivalent to (*p p).m m. Objects of structure types can be assigned, passed as function arguments, and returned as the result from a function. For example: a ad dd dr re es ss s c cu ur rr re en nt t; a ad dd dr re es ss s s se et t_ _c cu ur rr re en nt t(a ad dd dr re es ss s n ne ex xt t) { a ad dd dr re es ss s p pr re ev v = c cu ur rr re en nt t; c cu ur rr re en nt t = n ne ex xt t; r re et tu ur rn n p pr re ev v; } Other plausible operations, such as comparison (== and !=), are not defined. However, the user can define such operators (Chapter 11). The size of an object of a structure type is not necessarily the sum of the sizes of its members. This is because many machines require objects of certain types to be allocated on architecture- dependent boundaries or handle such objects much more efficiently if they are. For example, inte- gers are often allocated on word boundaries. On such machines, objects are said to have to be aligned properly. This leads to ‘‘holes’’ in the structures. For example, on many machines, The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 5.7 Structures 103 s si iz ze eo of f(a ad dd dr re es ss s) is 2 24 4, and not 2 22 2 as might be expected. You can minimize wasted space by sim- ply ordering members by size (largest member first). However, it is usually best to order members for readability and sort them by size only if there is a demonstrated need to optimize. The name of a type becomes available for use immediately after it has been encountered and not just after the complete declaration has been seen. For example: s st tr ru uc ct t L Li in nk k { L Li in nk k* p pr re ev vi io ou us s; L Li in nk k* s su uc cc ce es ss so or r; }; It is not possible to declare new objects of a structure type until the complete declaration has been seen. For example: s st tr ru uc ct t N No o_ _g go oo od d { N No o_ _g go oo od d m me em mb be er r; / / error: recursive definition }; This is an error because the compiler is not able to determine the size of N No o_ _g go oo od d. To allow two (or more) structure types to refer to each other, we can declare a name to be the name of a structure type. For example: s st tr ru uc ct t L Li is st t; / / to be defined later s st tr ru uc ct t L Li in nk k { L Li in nk k* p pr re e; L Li in nk k* s su uc c; L Li is st t* m me em mb be er r_ _o of f; }; s st tr ru uc ct t L Li is st t { L Li in nk k* h he ea ad d; }; Without the first declaration of L Li is st t, use of L Li is st t in the declaration of L Li in nk k would have caused a syn- tax error. The name of a structure type can be used before the type is defined as long as that use does not require the name of a member or the size of the structure to be known. For example: c cl la as ss s S S; / / ‘S’ is the name of some type e ex xt te er rn n S S a a; S S f f() ; v vo oi id d g g(S S) ; S S* h h(S S*) ; However, many such declarations cannot be used unless the type S S is defined: v vo oi id d k k(S S* p p) { S S a a; / / error: S not defined; size needed to allocate The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.104 Pointers, Arrays, and Structures Chapter 5 f f() ; / / error: S not defined; size needed to return value g g(a a) ; / / error: S not defined; size needed to pass argument p p->m m = 7 7; / / error: S not defined; member name not known S S* q q = h h(p p) ; / / ok: pointers can be allocated and passed q q->m m = 7 7; / / error: S not defined; member name not known } A s st tr ru uc ct t is a simple form of a c cl la as ss s (Chapter 10). For reasons that reach into the pre-history of C, it is possible to declare a s st tr ru uc ct t and a non- structure with the same name in the same scope. For example: s st tr ru uc ct t s st ta at t { /* ... */ }; i in nt t s st ta at t(c ch ha ar r* n na am me e, s st tr ru uc ct t s st ta at t* b bu uf f) ; In that case, the plain name (s st ta at t) is the name of the non-structure, and the structure must be referred to with the prefix s st tr ru uc ct t. Similarly, the keywords c cl la as ss s, u un ni io on n (§C.8.2), and e en nu um m (§4.8) can be used as prefixes for disambiguation. However, it is best not to overload names to make that necessary. 5.7.1 Type Equivalence [ptr.equiv] Two structures are different types even when they have the same members. For example, s st tr ru uc ct t S S1 1 { i in nt t a a; }; s st tr ru uc ct t S S2 2 { i in nt t a a; }; are two different types, so S S1 1 x x; S S2 2 y y = x x; / / error: type mismatch Structure types are also different from fundamental types, so S S1 1 x x; i in nt t i i = x x; / / error: type mismatch Every s st tr ru uc ct t must have a unique definition in a program (§9.2.3). 5.8 Advice [ptr.advice] [1] Avoid nontrivial pointer arithmetic; §5.3. [2] Take care not to write beyond the bounds of an array; §5.3.1. [3] Use 0 0 rather than N NU UL LL L; §5.1.1. [4] Use v ve ec ct to or r and v va al la ar rr ra ay y rather than built-in (C-style) arrays; §5.3.1. [5] Use s st tr ri in ng g rather than zero-terminated arrays of c ch ha ar r; §5.3. [6] Minimize use of plain reference arguments; §5.5. [7] Avoid v vo oi id d* except in low-level code; §5.6. [8] Avoid nontrivial literals (‘‘magic numbers’’) in code. Instead, define and use symbolic con- stants; §4.8, §5.4. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 5.9 Exercises 105 5.9 Exercises [ptr.exercises] 1. (∗1) Write declarations for the following: a pointer to a character, an array of 10 integers, a ref- erence to an array of 10 integers, a pointer to an array of character strings, a pointer to a pointer to a character, a constant integer, a pointer to a constant integer, and a constant pointer to an integer. Initialize each one. 2. (∗1.5) What, on your system, are the restrictions on the pointer types c ch ha ar r*, i in nt t*, and v vo oi id d*? For example, may an i in nt t* have an odd value? Hint: alignment. 3. (∗1) Use t ty yp pe ed de ef f to define the types u un ns si ig gn ne ed d c ch ha ar r, c co on ns st t u un ns si ig gn ne ed d c ch ha ar r, pointer to integer, pointer to pointer to c ch ha ar r, pointer to arrays of c ch ha ar r, array of 7 pointers to i in nt t, pointer to an array of 7 pointers to i in nt t, and array of 8 arrays of 7 pointers to i in nt t. 4. (∗1) Write a function that swaps (exchanges the values of) two integers. Use i in nt t* as the argu- ment type. Write another swap function using i in nt t& as the argument type. 5. (∗1.5) What is the size of the array s st tr r in the following example: c ch ha ar r s st tr r[] = "a a s sh ho or rt t s st tr ri in ng g"; What is the length of the string " "a a s sh ho or rt t s st tr ri in ng g" "? 6. (∗1) Define functions f f(c ch ha ar r), g g(c ch ha ar r&), and h h(c co on ns st t c ch ha ar r&). Call them with the arguments ´a a´, 4 49 9, 3 33 30 00 0, c c, u uc c, and s sc c, where c c is a c ch ha ar r, u uc c is an u un ns si ig gn ne ed d c ch ha ar r, and s sc c is a s si ig gn ne ed d c ch ha ar r. Which calls are legal? Which calls cause the compiler to introduce a temporary variable? 7. (∗1.5) Define a table of the names of months of the year and the number of days in each month. Write out that table. Do this twice; once using an array of c ch ha ar r for the names and an array for the number of days and once using an array of structures, with each structure holding the name of a month and the number of days in it. 8. (∗2) Run some tests to see if your compiler really generates equivalent code for iteration using pointers and iteration using indexing (§5.3.1). If different degrees of optimization can be requested, see if and how that affects the quality of the generated code. 9. (∗1.5) Find an example where it would make sense to use a name in its own initializer. 10. (∗1) Define an array of strings in which the strings contain the names of the months. Print those strings. Pass the array to a function that prints those strings. 11. (∗2) Read a sequence of words from input. Use Q Qu ui it t as a word that terminates the input. Print the words in the order they were entered. Don’t print a word twice. Modify the program to sort the words before printing them. 12. (∗2) Write a function that counts the number of occurrences of a pair of letters in a s st tr ri in ng g and another that does the same in a zero-terminated array of c ch ha ar r (a C-style string). For example, the pair "ab" appears twice in "xabaacbaxabb". 13. (∗1.5) Define a s st tr ru uc ct t D Da at te e to keep track of dates. Provide functions that read D Da at te es from input, write D Da at te es to output, and initialize a D Da at te e with a date. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.106 Pointers, Arrays, and Structures Chapter 5 . The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 6 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Expressions and Statements Premature optimization is the root of all evil. ± D. Knuth On the other hand, we cannot ignore efficiency. ± Jon Bentley Desk calculator example Ð input Ð command line arguments Ð expression summary Ð logical and relational operators Ð increment and decrement Ð free store Ð explicit type conversion Ð statement summary Ð declarations Ð selection statements Ð decla- rations in conditions Ð iteration statements Ð the infamous g go ot to o Ð comments and indentation Ð advice Ð exercises. 6.1 A Desk Calculator [expr.calculator] Statements and expressions are introduced by presenting a desk calculator program that provides the four standard arithmetic operations as infix operators on floating-point numbers. The user can also define variables. For example, given the input r r = 2 2.5 5 a ar re ea a = p pi i * r r * r r (pi is predefined) the calculator program will write 2 2.5 5 1 19 9.6 63 35 5 where 2 2.5 5 is the result of the first line of input and 1 19 9.6 63 35 5 is the result of the second. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.108 Expressions and Statements Chapter 6 The calculator consists of four main parts: a parser, an input function, a symbol table, and a driver. Actually, it is a miniature compiler in which the parser does the syntactic analysis, the input function handles input and lexical analysis, the symbol table holds permanent information, and the driver handles initialization, output, and errors. We could add many features to this calculator to make it more useful (§6.6[20]), but the code is long enough as it is, and most features would just add code without providing additional insight into the use of C++. 6.1.1 The Parser [expr.parser] Here is a grammar for the language accepted by the calculator: p pr ro og gr ra am m: E EN ND D / / END is end-of-input e ex xp pr r_ _l li is st t E EN ND D e ex xp pr r_ _l li is st t: e ex xp pr re es ss si io on n P PR RI IN NT T / / PRINT is semicolon e ex xp pr re es ss si io on n P PR RI IN NT T e ex xp pr r_ _l li is st t e ex xp pr re es ss si io on n: e ex xp pr re es ss si io on n + t te er rm m e ex xp pr re es ss si io on n - t te er rm m t te er rm m t te er rm m: t te er rm m / p pr ri im ma ar ry y t te er rm m * p pr ri im ma ar ry y p pr ri im ma ar ry y p pr ri im ma ar ry y: N NU UM MB BE ER R N NA AM ME E N NA AM ME E = e ex xp pr re es ss si io on n - p pr ri im ma ar ry y ( e ex xp pr re es ss si io on n ) In other words, a program is a sequence of expressions separated by semicolons. The basic units of an expression are numbers, names, and the operators *, /, +, - (both unary and binary), and =. Names need not be declared before use. The style of syntax analysis used is usually called recursive descent; it is a popular and straight- forward top-down technique. In a language such as C++, in which function calls are relatively cheap, it is also efficient. For each production in the grammar, there is a function that calls other functions. Terminal symbols (for example, E EN ND D, N NU UM MB BE ER R, +, and -) are recognized by the lexi- cal analyzer, g ge et t_ _t to ok ke en n(); and nonterminal symbols are recognized by the syntax analyzer func- tions, e ex xp pr r(), t te er rm m(), and p pr ri im m(). As soon as both operands of a (sub)expression are known, the expression is evaluated; in a real compiler, code could be generated at this point. The parser uses a function g ge et t_ _t to ok ke en n() to get input. The value of the most recent call of g ge et t_ _t to ok ke en n() can be found in the global variable c cu ur rr r_ _t to ok k. The type of c cu ur rr r_ _t to ok k is the enumera- tion T To ok ke en n_ _v va al lu ue e: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.1.1 The Parser 109 e en nu um m T To ok ke en n_ _v va al lu ue e { N NA AM ME E, N NU UM MB BE ER R, E EN ND D, P PL LU US S=´+´, M MI IN NU US S=´-´, M MU UL L=´*´, D DI IV V=´/´, P PR RI IN NT T=´;´, A AS SS SI IG GN N=´=´, L LP P=´(´, R RP P=´)´ }; T To ok ke en n_ _v va al lu ue e c cu ur rr r_ _t to ok k = P PR RI IN NT T; Representing each token by the integer value of its character is convenient and efficient and can be a help to people using debuggers. This works as long as no character used as input has a value used as an enumerator ± and no character set I know of has a printing character with a single-digit inte- ger value. I chose P PR RI IN NT T as the initial value for c cu ur rr r_ _t to ok k because that is the value it will have after the calculator has evaluated an expression and displayed its value. Thus, I ‘‘start the system’’ in a normal state to minimize the chance of errors and the need for special startup code. Each parser function takes a b bo oo ol l (§4.2) argument indicating whether the function needs to call g ge et t_ _t to ok ke en n() to get the next token. Each parser function evaluates ‘‘its’’ expression and returns the value. The function e ex xp pr r() handles addition and subtraction. It consists of a single loop that looks for terms to add or subtract: d do ou ub bl le e e ex xp pr r(b bo oo ol l g ge et t) / / add and subtract { d do ou ub bl le e l le ef ft t = t te er rm m(g ge et t) ; f fo or r (;;) / / ‘‘forever’’ s sw wi it tc ch h (c cu ur rr r_ _t to ok k) { c ca as se e P PL LU US S: l le ef ft t += t te er rm m(t tr ru ue e) ; b br re ea ak k; c ca as se e M MI IN NU US S: l le ef ft t -= t te er rm m(t tr ru ue e) ; b br re ea ak k; d de ef fa au ul lt t: r re et tu ur rn n l le ef ft t; } } This function really does not do much itself. In a manner typical of higher-level functions in a large program, it calls other functions to do the work. The switch-statement tests the value of its condition, which is supplied in parentheses after the s sw wi it tc ch h keyword, against a set of constants. The break-statements are used to exit the switch- statement. The constants following the c ca as se e labels must be distinct. If the value tested does not match any c ca as se e label, the d de ef fa au ul lt t is chosen. The programmer need not provide a d de ef fa au ul lt t. Note that an expression such as 2 2-3 3+4 4 is evaluated as (2 2-3 3)+4 4, as specified in the grammar. The curious notation f fo or r(;;) is the standard way to specify an infinite loop; you could pro- nounce it ‘‘forever.’’ It is a degenerate form of a for-statement (§6.3.3); w wh hi il le e(t tr ru ue e) is an alterna- tive. The switch-statement is executed repeatedly until something different from + and - is found, and then the return-statement in the default case is executed. The operators += and -= are used to handle the addition and subtraction; l le ef ft t=l le ef ft t+t te er rm m() and The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.110 Expressions and Statements Chapter 6 l le ef ft t=l le ef ft t-t te er rm m() could have been used without changing the meaning of the program. However, l le ef ft t+=t te er rm m() and l le ef ft t-=t te er rm m() not only are shorter but also express the intended operation directly. Each assignment operator is a separate lexical token, so a a + = 1 1; is a syntax error because of the space between the + and the =. Assignment operators are provided for the binary operators + - * / % & | ^ << >> so that the following assignment operators are possible = += -= *= /= %= &= |= ^= <<= >>= The % is the modulo, or remainder, operator; &, |, and ^ are the bitwise logical operators AND, OR, and exclusive OR; << and >> are the left shift and right shift operators; §6.2 summarizes the operators and their meanings. For a binary operator @ @ applied to operands of built-in types, an expression x x@ @= =y y means x x= =x x@ @y y, except that x x is evaluated once only. Chapter 8 and Chapter 9 discuss how to organize a program as a set of modules. With one exception, the declarations for this calculator example can be ordered so that everything is declared exactly once and before it is used. The exception is e ex xp pr r(), which calls t te er rm m(), which calls p pr ri im m(), which in turn calls e ex xp pr r(). This loop must be broken somehow. A declaration d do ou ub bl le e e ex xp pr r(b bo oo ol l) ; before the definition of p pr ri im m() will do nicely. Function t te er rm m() handles multiplication and division in the same way e ex xp pr r() handles addition and subtraction: d do ou ub bl le e t te er rm m(b bo oo ol l g ge et t) / / multiply and divide { d do ou ub bl le e l le ef ft t = p pr ri im m(g ge et t) ; f fo or r (;;) s sw wi it tc ch h (c cu ur rr r_ _t to ok k) { c ca as se e M MU UL L: l le ef ft t *= p pr ri im m(t tr ru ue e) ; b br re ea ak k; c ca as se e D DI IV V: i if f (d do ou ub bl le e d d = p pr ri im m(t tr ru ue e)) { l le ef ft t /= d d; b br re ea ak k; } r re et tu ur rn n e er rr ro or r("d di iv vi id de e b by y 0 0") ; d de ef fa au ul lt t: r re et tu ur rn n l le ef ft t; } } The result of dividing by zero is undefined and usually disastrous. We therefore test for 0 0 before dividing and call e er rr ro or r() if we detect a zero divisor. The function e er rr ro or r() is described in §6.1.4. The variable d d is introduced into the program exactly where it is needed and initialized immedi- ately. The scope of a name introduced in a condition is the statement controlled by that condition, The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.1.1 The Parser 111 and the resulting value is the value of the condition (§6.3.2.1). Consequently, the division and assignment l le ef ft t/=d d is done if and only if d d is nonzero. The function p pr ri im m() handling a primary is much like e ex xp pr r() and t te er rm m(), except that because we are getting lower in the call hierarchy a bit of real work is being done and no loop is necessary: d do ou ub bl le e n nu um mb be er r_ _v va al lu ue e; s st tr ri in ng g s st tr ri in ng g_ _v va al lu ue e; d do ou ub bl le e p pr ri im m(b bo oo ol l g ge et t) / / handle primaries { i if f (g ge et t) g ge et t_ _t to ok ke en n() ; s sw wi it tc ch h (c cu ur rr r_ _t to ok k) { c ca as se e N NU UM MB BE ER R: / / floating-point constant { d do ou ub bl le e v v = n nu um mb be er r_ _v va al lu ue e; g ge et t_ _t to ok ke en n() ; r re et tu ur rn n v v; } c ca as se e N NA AM ME E: { d do ou ub bl le e& v v = t ta ab bl le e[s st tr ri in ng g_ _v va al lu ue e] ; i if f (g ge et t_ _t to ok ke en n() == A AS SS SI IG GN N) v v = e ex xp pr r(t tr ru ue e) ; r re et tu ur rn n v v; } c ca as se e M MI IN NU US S: / / unary minus r re et tu ur rn n -p pr ri im m(t tr ru ue e) ; c ca as se e L LP P: { d do ou ub bl le e e e = e ex xp pr r(t tr ru ue e) ; i if f (c cu ur rr r_ _t to ok k != R RP P) r re et tu ur rn n e er rr ro or r(") e ex xp pe ec ct te ed d") ; g ge et t_ _t to ok ke en n() ; / / eat ’)’ r re et tu ur rn n e e; } d de ef fa au ul lt t: r re et tu ur rn n e er rr ro or r("p pr ri im ma ar ry y e ex xp pe ec ct te ed d") ; } } When a N NU UM MB BE ER R (that is, an integer or floating-point literal) is seen, its value is returned. The input routine g ge et t_ _t to ok ke en n() places the value in the global variable n nu um mb be er r_ _v va al lu ue e. Use of a global variable in a program often indicates that the structure is not quite clean ± that some sort of opti- mization has been applied. So it is here. Ideally, a lexical token consists of two parts: a value spec- ifying the kind of token (a T To ok ke en n_ _v va al lu ue e in this program) and (when needed) the value of the token. Here, there is only a single, simple variable, c cu ur rr r_ _t to ok k, so the global variable n nu um mb be er r_ _v va al lu ue e is needed to hold the value of the last N NU UM MB BE ER R read. Eliminating this spurious global variable is left as an exercise (§6.6[21]). Saving the value of n nu um mb be er r_ _v va al lu ue e in the local variable v v before calling g ge et t_ _t to ok ke en n() is not really necessary. For every legal input, the calculator always uses one number in the computation before reading another from input. However, saving the value and displaying it correctly after an error helps the user. In the same way that the value of the last N NU UM MB BE ER R is kept in n nu um mb be er r_ _v va al lu ue e, the character string representation of the last N NA AM ME E seen is kept in s st tr ri in ng g_ _v va al lu ue e. Before doing anything to a The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.112 Expressions and Statements Chapter 6 name, the calculator must first look ahead to see if it is being assigned to or simply read. In both cases, the symbol table is consulted. The symbol table is a m ma ap p (§3.7.4, §17.4.1): m ma ap p t ta ab bl le e; That is, when t ta ab bl le e is indexed by a s st tr ri in ng g, the resulting value is the d do ou ub bl le e corresponding to the s st tr ri in ng g. For example, if the user enters r ra ad di iu us s = 6 63 37 78 8.3 38 88 8; the calculator will execute d do ou ub bl le e& v v = t ta ab bl le e["r ra ad di iu us s"] ; / / ... expr() calculates the value to be assigned ... v v = 6 63 37 78 8.3 38 88 8; The reference v v is used to hold on to the d do ou ub bl le e associated with r ra ad di iu us s while e ex xp pr r() calculates the value 6 63 37 78 8.3 38 88 8 from the input characters. 6.1.2 The Input Function [expr.input] Reading input is often the messiest part of a program. This is because a program must communi- cate with a person, it must cope with that person’s whims, conventions, and seemingly random errors. Trying to force the person to behave in a manner more suitable for the machine is often (rightly) considered offensive. The task of a low-level input routine is to read characters and com- pose higher-level tokens from them. These tokens are then the units of input for higher-level rou- tines. Here, low-level input is done by g ge et t_ _t to ok ke en n(). Writing a low-level input routine need not be an everyday task. Many systems provide standard functions for this. I build g ge et t_ _t to ok ke en n() in two stages. First, I provide a deceptively simple version that imposes a burden on the user. Next, I modify it into a slightly less elegant, but much easier to use, version. The idea is to read a character, use that character to decide what kind of token needs to be com- posed, and then return the T To ok ke en n_ _v va al lu ue e representing the token read. The initial statements read the first non-whitespace character into c ch h and check that the read operation succeeded: T To ok ke en n_ _v va al lu ue e g ge et t_ _t to ok ke en n() { c ch ha ar r c ch h = 0 0; c ci in n>>c ch h; s sw wi it tc ch h (c ch h) { c ca as se e 0 0: r re et tu ur rn n c cu ur rr r_ _t to ok k=E EN ND D; / / assign and return By default, operator >> skips whitespace (that is, spaces, tabs, newlines, etc.) and leaves the value of c ch h unchanged if the input operation failed. Consequently, c ch h==0 0 indicates end of input. Assignment is an operator, and the result of the assignment is the value of the variable assigned to. This allows me to assign the value E EN ND D to c cu ur rr r_ _t to ok k and return it in the same statement. Hav- ing a single statement rather than two is useful in maintenance. If the assignment and the return became separated in the code, a programmer might update the one and forget to update to the other. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.1.2 The Input Function 113 Let us look at some of the cases separately before considering the complete function. The expression terminator ´;´, the parentheses, and the operators are handled simply by returning their values: c ca as se e ´;´: c ca as se e ´*´: c ca as se e ´/´: c ca as se e ´+´: c ca as se e ´-´: c ca as se e ´(´: c ca as se e ´)´: c ca as se e ´=´: r re et tu ur rn n c cu ur rr r_ _t to ok k=T To ok ke en n_ _v va al lu ue e(c ch h) ; Numbers are handled like this: c ca as se e ´0 0´: c ca as se e ´1 1´: c ca as se e ´2 2´: c ca as se e ´3 3´: c ca as se e ´4 4´: c ca as se e ´5 5´: c ca as se e ´6 6´: c ca as se e ´7 7´: c ca as se e ´8 8´: c ca as se e ´9 9´: c ca as se e ´.´: c ci in n.p pu ut tb ba ac ck k(c ch h) ; c ci in n >> n nu um mb be er r_ _v va al lu ue e; r re et tu ur rn n c cu ur rr r_ _t to ok k=N NU UM MB BE ER R; Stacking c ca as se e labels horizontally rather than vertically is generally not a good idea because this arrangement is harder to read. However, having one line for each digit is tedious. Because opera- tor >> is already defined for reading floating-point constants into a d do ou ub bl le e, the code is trivial. First the initial character (a digit or a dot) is put back into c ci in n. Then the constant can be read into n nu um mb be er r_ _v va al lu ue e. A name is handled similarly: d de ef fa au ul lt t: / / NAME, NAME =, or error i if f (i is sa al lp ph ha a(c ch h)) { c ci in n.p pu ut tb ba ac ck k(c ch h) ; c ci in n>>s st tr ri in ng g_ _v va al lu ue e; r re et tu ur rn n c cu ur rr r_ _t to ok k=N NA AM ME E; } e er rr ro or r("b ba ad d t to ok ke en n") ; r re et tu ur rn n c cu ur rr r_ _t to ok k=P PR RI IN NT T; The standard library function i is sa al lp ph ha a() (§20.4.2) is used to avoid listing every character as a sepa- rate c ca as se e label. Operator >> applied to a string (in this case, s st tr ri in ng g_ _v va al lu ue e) reads until it hits white- space. Consequently, a user must terminate a name by a space before an operator using the name as an operand. This is less than ideal, so we will return to this problem in §6.1.3. Here, finally, is the complete input function: T To ok ke en n_ _v va al lu ue e g ge et t_ _t to ok ke en n() { c ch ha ar r c ch h = 0 0; c ci in n>>c ch h; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.114 Expressions and Statements Chapter 6 s sw wi it tc ch h (c ch h) { c ca as se e 0 0: r re et tu ur rn n c cu ur rr r_ _t to ok k=E EN ND D; c ca as se e ´;´: c ca as se e ´*´: c ca as se e ´/´: c ca as se e ´+´: c ca as se e ´-´: c ca as se e ´(´: c ca as se e ´)´: c ca as se e ´=´: r re et tu ur rn n c cu ur rr r_ _t to ok k=T To ok ke en n_ _v va al lu ue e(c ch h) ; c ca as se e ´0 0´: c ca as se e ´1 1´: c ca as se e ´2 2´: c ca as se e ´3 3´: c ca as se e ´4 4´: c ca as se e ´5 5´: c ca as se e ´6 6´: c ca as se e ´7 7´: c ca as se e ´8 8´: c ca as se e ´9 9´: c ca as se e ´.´: c ci in n.p pu ut tb ba ac ck k(c ch h) ; c ci in n >> n nu um mb be er r_ _v va al lu ue e; r re et tu ur rn n c cu ur rr r_ _t to ok k=N NU UM MB BE ER R; d de ef fa au ul lt t: / / NAME, NAME =, or error i if f (i is sa al lp ph ha a(c ch h)) { c ci in n.p pu ut tb ba ac ck k(c ch h) ; c ci in n>>s st tr ri in ng g_ _v va al lu ue e; r re et tu ur rn n c cu ur rr r_ _t to ok k=N NA AM ME E; } e er rr ro or r("b ba ad d t to ok ke en n") ; r re et tu ur rn n c cu ur rr r_ _t to ok k=P PR RI IN NT T; } } The conversion of an operator to its token value is trivial because the T To ok ke en n_ _v va al lu ue e of an operator was defined as the integer value of the operator (§4.8). 6.1.3 Low-level Input [expr.low] Using the calculator as defined so far reveals a few inconveniences. It is tedious to remember to add a semicolon after an expression in order to get its value printed, and having a name terminated by whitespace only is a real nuisance. For example, x x=7 7 is an identifier ± rather than the identifier x x followed by the operator = and the number 7 7. Both problems are solved by replacing the type- oriented default input operations in g ge et t_ _t to ok ke en n() with code that reads individual characters. First, we’ll make a newline equivalent to the semicolon used to mark the end of expression: T To ok ke en n_ _v va al lu ue e g ge et t_ _t to ok ke en n() { c ch ha ar r c ch h; d do o { / / skip whitespace except ’\n’ i if f(!c ci in n.g ge et t(c ch h)) r re et tu ur rn n c cu ur rr r_ _t to ok k = E EN ND D; } w wh hi il le e (c ch h!=´\ \n n´ && i is ss sp pa ac ce e(c ch h)) ; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.1.3 Low-level Input 115 s sw wi it tc ch h (c ch h) { c ca as se e ´;´: c ca as se e ´\ \n n´: r re et tu ur rn n c cu ur rr r_ _t to ok k=P PR RI IN NT T; A do-statement is used; it is equivalent to a while-statement except that the controlled statement is always executed at least once. The call c ci in n.g ge et t(c ch h) reads a single character from the standard input stream into c ch h. By default, g ge et t() does not skip whitespace the way o op pe er ra at to or r >> does. The test i if f (!c ci in n.g ge et t(c ch h)) fails if no character can be read from c ci in n; in this case, E EN ND D is returned to terminate the calculator session. The operator ! (NOT) is used because g ge et t() returns t tr ru ue e in case of success. The standard library function i is ss sp pa ac ce e() provides the standard test for whitespace (§20.4.2); i is ss sp pa ac ce e(c c) returns a nonzero value if c c is a whitespace character and zero otherwise. The test is implemented as a table lookup, so using i is ss sp pa ac ce e() is much faster than testing for the individual whitespace characters. Similar functions test if a character is a digit ± i is sd di ig gi it t() ± a letter ± i is sa al l- - p ph ha a() ± or a digit or letter ± i is sa al ln nu um m(). After whitespace has been skipped, the next character is used to determine what kind of lexical token is coming. The problem caused by >> reading into a string until whitespace is encountered is solved by reading one character at a time until a character that is not a letter or a digit is found: d de ef fa au ul lt t: / / NAME, NAME=, or error i if f (i is sa al lp ph ha a(c ch h)) { s st tr ri in ng g_ _v va al lu ue e = c ch h; w wh hi il le e (c ci in n.g ge et t(c ch h) && i is sa al ln nu um m(c ch h)) s st tr ri in ng g_ _v va al lu ue e.p pu us sh h_ _b ba ac ck k(c ch h) ; c ci in n.p pu ut tb ba ac ck k(c ch h) ; r re et tu ur rn n c cu ur rr r_ _t to ok k=N NA AM ME E; } e er rr ro or r("b ba ad d t to ok ke en n") ; r re et tu ur rn n c cu ur rr r_ _t to ok k=P PR RI IN NT T; Fortunately, these two improvements could both be implemented by modifying a single local sec- tion of code. Constructing programs so that improvements can be implemented through local mod- ifications only is an important design aim. 6.1.4 Error Handling [expr.error] Because the program is so simple, error handling is not a major concern. The error function simply counts the errors, writes out an error message, and returns: i in nt t n no o_ _o of f_ _e er rr ro or rs s; d do ou ub bl le e e er rr ro or r(c co on ns st t s st tr ri in ng g& s s) { n no o_ _o of f_ _e er rr ro or rs s++; c ce er rr r << "e er rr ro or r: " << s s << ´\ \n n´; r re et tu ur rn n 1 1; } The stream c ce er rr r is an unbuffered output stream usually used to report errors (§21.2.1). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.116 Expressions and Statements Chapter 6 The reason for returning a value is that errors typically occur in the middle of the evaluation of an expression, so we should either abort that evaluation entirely or return a value that is unlikely to cause subsequent errors. The latter is adequate for this simple calculator. Had g ge et t_ _t to ok ke en n() kept track of the line numbers, e er rr ro or r() could have informed the user approximately where the error occurred. This would be useful when the calculator is used noninteractively (§6.6[19]). Often, a program must be terminated after an error has occurred because no sensible way of continuing has been devised. This can be done by calling e ex xi it t(), which first cleans up things like output streams and then terminates the program with its argument as the return value (§9.4.1.1). More stylized error-handling mechanisms can be implemented using exceptions (see §8.3, Chapter 14), but what we have here is quite suitable for a 150-line calculator. 6.1.5 The Driver [expr.driver] With all the pieces of the program in place, we need only a driver to start things. In this simple example, m ma ai in n() can do that: i in nt t m ma ai in n() { t ta ab bl le e["p pi i"] = 3 3.1 14 41 15 59 92 26 65 53 35 58 89 97 79 93 32 23 38 85 5; / / insert predefined names t ta ab bl le e["e e"] = 2 2.7 71 18 82 28 81 18 82 28 84 45 59 90 04 45 52 23 35 54 4; w wh hi il le e (c ci in n) { g ge et t_ _t to ok ke en n() ; i if f (c cu ur rr r_ _t to ok k == E EN ND D) b br re ea ak k; i if f (c cu ur rr r_ _t to ok k == P PR RI IN NT T) c co on nt ti in nu ue e; c co ou ut t << e ex xp pr r(f fa al ls se e) << ´\ \n n´; } r re et tu ur rn n n no o_ _o of f_ _e er rr ro or rs s; } Conventionally, m ma ai in n() should return zero if the program terminates normally and nonzero other- wise (§3.2). Returning the number of errors accomplishes this nicely. As it happens, the only initialization needed is to insert the predefined names into the symbol table. The primary task of the main loop is to read expressions and write out the answer. This is achieved by the line: c co ou ut t << e ex xp pr r(f fa al ls se e) << ´\ \n n´; The argument f fa al ls se e tells e ex xp pr r() that it does not need to call g ge et t_ _t to ok ke en n() to get a current token on which to work. Testing c ci in n each time around the loop ensures that the program terminates if something goes wrong with the input stream, and testing for E EN ND D ensures that the loop is correctly exited when g ge et t_ _t to ok ke en n() encounters end-of-file. A break-statement exits its nearest enclosing switch-statement or loop (that is, a for-statement, while-statement, or do-statement). Testing for P PR RI IN NT T (that is, for ´\ \n n´ and ´;´) relieves e ex xp pr r() of the responsibility for handling empty expressions. A continue- statement is equivalent to going to the very end of a loop, so in this case The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.1.5 The Driver 117 w wh hi il le e (c ci in n) { / / ... i if f (c cu ur rr r_ _t to ok k == P PR RI IN NT T) c co on nt ti in nu ue e; c co ou ut t << e ex xp pr r(f fa al ls se e) << ´\ \n n´; } is equivalent to w wh hi il le e (c ci in n) { / / ... i if f (c cu ur rr r_ _t to ok k != P PR RI IN NT T) c co ou ut t << e ex xp pr r(f fa al ls se e) << ´\ \n n´; } 6.1.6 Headers [expr.headers] The calculator uses standard library facilities. Therefore, appropriate headers must be #i in nc cl lu ud de ed to complete the program: #i in nc cl lu ud de e / / I/O #i in nc cl lu ud de e / / strings #i in nc cl lu ud de e / / map #i in nc cl lu ud de e / / isalpha(), etc. All of these headers provide facilities in the s st td d namespace, so to use the names they provide we must either use explicit qualification with s st td d: : or bring the names into the global namespace by u us si in ng g n na am me es sp pa ac ce e s st td d; To avoid confusing the discussion of expressions with modularity issues, I did the latter. Chapter 8 and Chapter 9 discuss ways of organizing this calculator into modules using namespaces and how to organize it into source files. On many systems, standard headers have equivalents with a .h h suf- fix that declare the classes, functions, etc., and place them in the global namespace (§9.2.1, §9.2.4, §B.3.1). 6.1.7 Command-Line Arguments [expr.command] After the program was written and tested, I found it a bother to first start the program, then type the expressions, and finally quit. My most common use was to evaluate a single expression. If that expression could be presented as a command-line argument, a few keystrokes could be avoided. A program starts by calling m ma ai in n() (§3.2, §9.4). When this is done, m ma ai in n() is given two arguments specifying the number of arguments, usually called a ar rg gc c, and an array of arguments, usually called a ar rg gv v. The arguments are character strings, so the type of a ar rg gv v is c ch ha ar r*[a ar rg gc c+1 1]. The name of the program (as it occurs on the command line) is passed as a ar rg gv v[0 0], so a ar rg gc c is always at least 1 1. The list of arguments is zero-terminated; that is, a ar rg gv v[a ar rg gc c]==0 0. For example, for the command d dc c 1 15 50 0/1 1.1 19 93 34 4 the arguments have these values: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.118 Expressions and Statements Chapter 6 2a ar rg gc c: a ar rg gv v: 0 0 . . "d dc c" "1 15 50 0/ /1 1. .1 19 93 34 4" Because the conventions for calling m ma ai in n() are shared with C, C-style arrays and strings are used. It is not difficult to get hold of a command-line argument. The problem is how to use it with minimal reprogramming. The idea is to read from the command string in the same way that we read from the input stream. A stream that reads from a string is unsurprisingly called an i is st tr ri in ng gs st tr re ea am m. Unfortunately, there is no elegant way of making c ci in n refer to an i is st tr ri in ng gs st tr re ea am m. Therefore, we must find a way of getting the calculator input functions to refer to an i is st tr ri in ng gs st tr re ea am m. Furthermore, we must find a way of getting the calculator input functions to refer to an i is st tr ri in ng gs st tr re ea am m or to c ci in n depending on what kind of command-line argument we supply. A simple solution is to introduce a global pointer i in np pu ut t that points to the input stream to be used and have every input routine use that: i is st tr re ea am m* i in np pu ut t; / / pointer to input stream i in nt t m ma ai in n(i in nt t a ar rg gc c, c ch ha ar r* a ar rg gv v[]) { s sw wi it tc ch h (a ar rg gc c) { c ca as se e 1 1: / / read from standard input i in np pu ut t = &c ci in n; b br re ea ak k; c ca as se e 2 2: / / read argument string i in np pu ut t = n ne ew w i is st tr ri in ng gs st tr re ea am m(a ar rg gv v[1 1]) ; b br re ea ak k; d de ef fa au ul lt t: e er rr ro or r("t to oo o m ma an ny y a ar rg gu um me en nt ts s") ; r re et tu ur rn n 1 1; } t ta ab bl le e["p pi i"] = 3 3.1 14 41 15 59 92 26 65 53 35 58 89 97 79 93 32 23 38 85 5; / / insert predefined names t ta ab bl le e["e e"] = 2 2.7 71 18 82 28 81 18 82 28 84 45 59 90 04 45 52 23 35 54 4; w wh hi il le e (*i in np pu ut t) { g ge et t_ _t to ok ke en n() ; i if f (c cu ur rr r_ _t to ok k == E EN ND D) b br re ea ak k; i if f (c cu ur rr r_ _t to ok k == P PR RI IN NT T) c co on nt ti in nu ue e; c co ou ut t << e ex xp pr r(f fa al ls se e) << ´\ \n n´; } i if f (i in np pu ut t != &c ci in n) d de el le et te e i in np pu ut t; r re et tu ur rn n n no o_ _o of f_ _e er rr ro or rs s; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.1.7 Command-Line Arguments 119 An i is st tr ri in ng gs st tr re ea am m is a kind of i is st tr re ea am m that reads from its character string argument (§21.5.3). Upon reaching the end of its string, an i is st tr ri in ng gs st tr re ea am m fails exactly like other streams do when they hit the end of input (§3.6, §21.3.3). To use an i is st tr ri in ng gs st tr re ea am m, you must include . It would be easy to modify m ma ai in n() to accept several command-line arguments, but this does not appear to be necessary, especially as several expressions can be passed as a single argument: d dc c "r ra at te e=1 1.1 19 93 34 4;1 15 50 0/r ra at te e;1 19 9.7 75 5/r ra at te e;2 21 17 7/r ra at te e" I use quotes because ; is the command separator on my UNIX systems. Other systems have differ- ent conventions for supplying arguments to a program on startup. It was inelegant to modify all of the input routines to use *i in np pu ut t rather than c ci in n to gain the flex- ibility to use alternative sources of input. The change could have been avoided had I shown fore- sight by introducing something like i in np pu ut t from the start. A more general and useful view is to note that the source of input really should be the parameter of a calculator module. That is, the funda- mental problem with this calculator example is that what I refer to as ‘‘the calculator’’ is only a col- lection of functions and data. There is no module (§2.4) or object (§2.5.2) that explicitly represents the calculator. Had I set out to design a calculator module or a calculator type, I would naturally have considered what its parameters should be (§8.5[3], §10.6[16]). 6.1.8 A Note on Style [expr.style] To programmers unacquainted with associative arrays, the use of the standard library m ma ap p as the symbol table seems almost like cheating. It is not. The standard library and other libraries are meant to be used. Often, a library has received more care in its design and implementation than a programmer could afford for a handcrafted piece of code to be used in just one program. Looking at the code for the calculator, especially at the first version, we can see that there isn’t much traditional C-style, low-level code presented. Many of the traditional tricky details have been replaced by uses of standard library classes such as o os st tr re ea am m, s st tr ri in ng g, and m ma ap p (§3.4, §3.5, §3.7.4, Chapter 17). Note the relative scarcity of arithmetic, loops, and even assignments. This is the way things ought to be in code that doesn’t manipulate hardware directly or implement low-level abstractions. 6.2 Operator Summary [expr.operators] This section presents a summary of expressions and some examples. Each operator is followed by one or more names commonly used for it and an example of its use. In these tables, a class_name is the name of a class, a member is a member name, an object is an expression yielding a class object, a pointer is an expression yielding a pointer, an expr is an expression, and an lvalue is an expression denoting a nonconstant object. A type can be a fully general type name (with *, (), etc.) only when it appears in parentheses; elsewhere, there are restrictions (§A.5). The syntax of expressions is independent of operand types. The meanings presented here apply when the operands are of built-in types (§4.1.1). In addition, you can define meanings for operators applied to operands of user-defined types (§2.5.2, Chapter 11). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.120 Expressions and Statements Chapter 6 _ ____________________________________________________________ Operator Summary_ _____________________________________________________________ ____________________________________________________________ scope resolution class_name :: member scope resolution namespace_name :: member global :: name global :: qualified-name_ ____________________________________________________________ member selection object . member member selection pointer -> member subscripting pointer [ expr ] function call expr ( expr_list ) value construction type ( expr_list ) post increment lvalue ++ post decrement lvalue -- type identification t ty yp pe ei id d ( type ) run-time type identification t ty yp pe ei id d ( expr ) run-time checked conversion d dy yn na am mi ic c_ _c ca as st t < type > ( expr ) compile-time checked conversion s st ta at ti ic c_ _c ca as st t < type > ( expr ) unchecked conversion r re ei in nt te er rp pr re et t_ _c ca as st t < type > ( expr ) c co on ns st t conversion c co on ns st t_ _c ca as st t < type > ( expr )_ ____________________________________________________________ size of object s si iz ze eo of fexpr size of type s si iz ze eo of f ( type ) pre increment ++ lvalue pre decrement -- lvalue complement ~ expr not ! expr unary minus - expr unary plus + expr address of & lvalue dereference ∗ expr create (allocate) n ne ew wtype create (allocate and initialize) n ne ew wtype ( expr-list ) create (place) n ne ew w ( expr-list ) type create (place and initialize) n ne ew w ( expr-list ) type ( expr-list ) destroy (de-allocate) d de el le et te epointer destroy array d de el le et te e[] pointer cast (type conversion) ( type ) expr_ ____________________________________________________________ member selection object .* pointer-to-member member selection pointer ->* pointer-to-member_ ____________________________________________________________ multiply expr ∗ expr divide expr / expr modulo (remainder) expr % expr_ ____________________________________________________________                                                                                                   The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.2 Operator Summary 121 _ _______________________________________ Operator Summary (continued)_ ________________________________________ _______________________________________ add (plus) expr + expr subtract (minus) expr - expr_ _______________________________________ shift left expr << expr shift right expr >> expr_ _______________________________________ less than expr < expr less than or equal expr <= expr greater than expr > expr greater than or equal expr >= expr_ _______________________________________ equal expr == expr not equal expr != expr_ _______________________________________ bitwise AND expr & expr_ _______________________________________ bitwise exclusive OR expr ^ expr_ _______________________________________ bitwise inclusive OR expr | expr_ _______________________________________ logical AND expr && expr_ _______________________________________ logical inclusive OR expr || expr_ _______________________________________ simple assignment lvalue = expr multiply and assign lvalue ∗= expr divide and assign lvalue /= expr modulo and assign lvalue %= expr add and assign lvalue += expr subtract and assign lvalue -= expr shift left and assign lvalue <<= expr shift right and assign lvalue >>= expr AND and assign lvalue &= expr inclusive OR and assign lvalue |= expr exclusive OR and assign lvalue ^= expr_ _______________________________________ conditional expression expr ? expr : expr_ _______________________________________ throw exception t th hr ro ow wexpr_ _______________________________________ comma (sequencing) expr , expr_ _______________________________________                                                                               Each box holds operators with the same precedence. Operators in higher boxes have higher prece- dence than operators in lower boxes. For example: a a+b b*c c means a a+(b b*c c) rather than (a a+b b)*c c because * has higher precedence than +. Unary operators and assignment operators are right-associative; all others are left-associative. For example, a a=b b=c c means a a=(b b=c c), a a+b b+c c means (a a+b b)+c c, and *p p++ means *(p p++), not (*p p)++. A few grammar rules cannot be expressed in terms of precedence (also known as binding strength) and associativity. For example, a a=b by y?x x:y y) ; / / address of the int with the larger value } If both the second and third operands of ?: are lvalues and have the same type, the result is of that type and is an lvalue. Preserving lvalues in this way allows greater flexibility in using operators. This is particularly useful when writing code that needs to work uniformly and efficiently with both built-in and user-defined types (e.g., when writing templates or programs that generate C++ code). The result of s si iz ze eo of f is of an unsigned integral type called s si iz ze e_ _t t defined in . The result of pointer subtraction is of a signed integral type called p pt tr rd di if ff f_ _t t defined in . Implementations do not have to check for arithmetic overflow and hardly any do. For example: v vo oi id d f f() { i in nt t i i = 1 1; w wh hi il le e (0 0 < i i) i i++; c co ou ut t << "i i h ha as s b be ec co om me e n ne eg ga at ti iv ve e!" << i i << ´\ \n n´; } This will (eventually) try to increase i i past the largest integer. What happens then is undefined, but typically the value ‘‘wraps around’’ to a negative number (on my machine -2 21 14 47 74 48 83 36 64 48 8). Simi- larly, the effect of dividing by zero is undefined, but doing so usually causes abrupt termination of the program. In particular, underflow, overflow, and division by zero do not throw standard excep- tions (§14.10). 6.2.2 Evaluation Order [expr.evaluation] The order of evaluation of subexpressions within an expression is undefined. In particular, you cannot assume that the expression is evaluated left to right. For example: i in nt t x x = f f(2 2)+g g(3 3) ; / / undefined whether f() or g() is called first The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.2.2 Evaluation Order 123 Better code can be generated in the absence of restrictions on expression evaluation order. How- ever, the absence of restrictions on evaluation order can lead to undefined results. For example, i in nt t i i = 1 1; v v[i i] = i i++; / / undefined result may be evaluated as either v v[1 1]=1 1 or v v[2 2]=1 1 or may cause some even stranger behavior. Com- pilers can warn about such ambiguities. Unfortunately, most do not. The operators , (comma), && (logical and), and || (logical or) guarantee that their left-hand operand is evaluated before their right-hand operand. For example, b b=(a a=2 2,a a+1 1) assigns 3 3 to b b. Examples of the use of || and && can be found in §6.2.3. For built-in types, the second operand of && is evaluated only if its first operand is t tr ru ue e, and the second operand of || is evaluated only if its first operand is f fa al ls se e; this is sometimes called short-circuit evaluation. Note that the sequencing operator , (comma) is logically different from the comma used to separate arguments in a function call. Consider: f f1 1(v v[i i] ,i i++) ; / / two arguments f f2 2( (v v[i i] ,i i++) ) ; / / one argument The call of f f1 1 has two arguments, v v[i i] and i i++, and the order of evaluation of the argument expressions is undefined. Order dependence of argument expressions is very poor style and has undefined behavior. The call of f f2 2 has one argument, the comma expression (v v[i i] ,i i++), which is equivalent to i i++. Parentheses can be used to force grouping. For example, a a*b b/c c means (a a*b b)/c c so parenthe- ses must be used to get a a*(b b/c c); a a*(b b/c c) may be evaluated as (a a*b b)/c c only if the user cannot tell the difference. In particular, for many floating-point computations a a*(b b/c c) and (a a*b b)/c c are significantly different, so a compiler will evaluate such expressions exactly as written. 6.2.3 Operator Precedence [expr.precedence] Precedence levels and associativity rules reflect the most common usage. For example, i if f (i i<=0 0 || m ma ax x>, and << are applied to objects of integer types ± that is, b bo oo ol l, c ch ha ar r, s sh ho or rt t, i in nt t, l lo on ng g, and their u un ns si ig gn ne ed d counterparts. The results are also integers. A typical use of bitwise logical operators is to implement the notion of a small set (a bit vector). In this case, each bit of an unsigned integer represents one member of the set, and the number of bits limits the number of members. The binary operator & is interpreted as intersection, | as union, ^ as symmetric difference, and ~ as complement. An enumeration can be used to name the mem- bers of such a set. Here is a small example borrowed from an implementation of o os st tr re ea am m: e en nu um m i io os s_ _b ba as se e: :i io os st ta at te e { g go oo od db bi it t=0 0, e eo of fb bi it t=1 1, f fa ai il lb bi it t=2 2, b ba ad db bi it t=4 4 }; The implementation of a stream can set and test its state like this: s st ta at te e = g go oo od db bi it t; / / ... i if f (s st ta at te e&(b ba ad db bi it t|f fa ai il lb bi it t)) / / stream no good The extra parentheses are necessary because & has higher precedence than |. A function that reaches the end of input might report it like this: s st ta at te e |= e eo of fb bi it t; The |= operator is used to add to the state. A simple assignment, s st ta at te e=e eo of fb bi it t, would have cleared all other bits. These stream state flags are observable from outside the stream implementation. For example, we could see how the states of two streams differ like this: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.2.4 Bitwise Logical Operators 125 i in nt t d di if ff f = c ci in n.r rd ds st ta at te e()^c co ou ut t.r rd ds st ta at te e() ; / / rdstate() returns the state Computing differences of stream states is not very common. For other similar types, computing differences is essential. For example, consider comparing a bit vector that represents the set of interrupts being handled with another that represents the set of interrupts waiting to be handled. Please note that this bit fiddling is taken from the implementation of iostreams rather than from the user interface. Convenient bit manipulation can be very important, but for reliability, maintain- ability, portability, etc., it should be kept at low levels of a system. For more general notions of a set, see the standard library s se et t (§17.4.3), b bi it ts se et t (§17.5.3), and v ve ec ct to or r (§16.3.11). Using fields (§C.8.1) is really a convenient shorthand for shifting and masking to extract bit fields from a word. This can, of course, also be done using the bitwise logical operators. For example, one could extract the middle 16 bits of a 32-bit l lo on ng g like this: u un ns si ig gn ne ed d s sh ho or rt t m mi id dd dl le e(l lo on ng g a a) { r re et tu ur rn n (a a>>8 8)&0 0x xf ff ff ff f; } Do not confuse the bitwise logical operators with the logical operators: &&, ||, and ! . The latter return either t tr ru ue e or f fa al ls se e, and they are primarily useful for writing the test in an i if f, w wh hi il le e, or f fo or r statement (§6.3.2, §6.3.3). For example, !0 0 (not zero) is the value t tr ru ue e, whereas ~0 0 (complement of zero) is the bit pattern all-ones, which in two’s complement representation is the value -1 1. 6.2.5 Increment and Decrement [expr.incr] The ++ operator is used to express incrementing directly, rather than expressing it indirectly using a combination of an addition and an assignment. By definition, ++l lv va al lu ue e means l lv va al lu ue e+=1 1, which again means l lv va al lu ue e=l lv va al lu ue e+1 1 provided l lv va al lu ue e has no side effects. The expression denoting the object to be incremented is evaluated once (only). Decrementing is similarly expressed by the -- operator. The operators ++ and -- can be used as both prefix and postfix operators. The value of ++x x is the new (that is, incremented) value of x x. For example, y y=++x x is equivalent to y y=(x x+=1 1). The value of x x++, however, is the old value of x x. For example, y y=x x++ is equivalent to y y=(t t=x x,x x+=1 1,t t), where t t is a variable of the same type as x x. Like addition and subtraction of pointers, ++ and -- on pointers operate in terms of elements of the array into which the pointer points; p p++ makes p p point to the next element (§5.3.1). The increment operators are particularly useful for incrementing and decrementing variables in loops. For example, one can copy a zero-terminated string like this: v vo oi id d c cp py y(c ch ha ar r* p p, c co on ns st t c ch ha ar r* q q) { w wh hi il le e (*p p++ = *q q++) ; } Like C, C++ is both loved and hated for enabling such terse, expression-oriented coding. Because w wh hi il le e (*p p++ = *q q++) ; is more than a little obscure to non-C programmers and because the style of coding is not uncom- mon in C and C++, it is worth examining more closely. Consider first a more traditional way of copying an array of characters: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.126 Expressions and Statements Chapter 6 i in nt t l le en ng gt th h = s st tr rl le en n(q q) ; f fo or r (i in nt t i i = 0 0; i i<=l le en ng gt th h; i i++) p p[i i] = q q[i i] ; This is wasteful. The length of a zero-terminated string is found by reading the string looking for the terminating zero. Thus, we read the string twice: once to find its length and once to copy it. So we try this instead: i in nt t i i; f fo or r (i i = 0 0; q q[i i]!=0 0 ; i i++) p p[i i] = q q[i i] ; p p[i i] = 0 0; / / terminating zero The variable i i used for indexing can be eliminated because p p and q q are pointers: w wh hi il le e (*q q != 0 0) { *p p = *q q; p p++; / / point to next character q q++; / / point to next character } *p p = 0 0; / / terminating zero Because the post-increment operation allows us first to use the value and then to increment it, we can rewrite the loop like this: w wh hi il le e (*q q != 0 0) { *p p++ = *q q++; } *p p = 0 0; / / terminating zero The value of *p p++ = *q q++ is *q q. We can therefore rewrite the example like this: w wh hi il le e ((*p p++ = *q q++) != 0 0) { } In this case, we don’t notice that *q q is zero until we already have copied it into *p p and incremented p p. Consequently, we can eliminate the final assignment of the terminating zero. Finally, we can reduce the example further by observing that we don’t need the empty block and that the ‘‘!= 0 0’’ is redundant because the result of a pointer or integral condition is always compared to zero anyway. Thus, we get the version we set out to discover: w wh hi il le e (*p p++ = *q q++) ; Is this version less readable than the previous versions? Not to an experienced C or C++ program- mer. Is this version more efficient in time or space than the previous versions? Except for the first version that called s st tr rl le en n(), not really. Which version is the most efficient will vary among machine architectures and among compilers. The most efficient way of copying a zero-terminated character string for your particular machine ought to be the standard string copy function: c ch ha ar r* s st tr rc cp py y(c ch ha ar r*, c co on ns st t c ch ha ar r*) ; / / from For more general copying, the standard c co op py y algorithm (§2.7.2, §18.6.1) can be used. Whenever possible, use standard library facilities in preference to fiddling with pointers and bytes. Standard library functions may be inlined (§7.1.1) or even implemented using specialized machine The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.2.5 Increment and Decrement 127 instructions. Therefore, you should measure carefully before believing that some piece of hand- crafted code outperforms library functions. 6.2.6 Free Store [expr.free] A named object has its lifetime determined by its scope (§4.9.4). However, it is often useful to cre- ate an object that exists independently of the scope in which it was created. In particular, it is com- mon to create objects that can be used after returning from the function in which they were created. The operator n ne ew w creates such objects, and the operator d de el le et te e can be used to destroy them. Objects allocated by n ne ew w are said to be ‘‘on the free store’’ (also, to be ‘‘heap objects,’’ or ‘‘allo- cated in dynamic memory’’). Consider how we might write a compiler in the style used for the desk calculator (§6.1). The syntax analysis functions might build a tree of the expressions for use by the code generator: s st tr ru uc ct t E En no od de e { T To ok ke en n_ _v va al lu ue e o op pe er r; E En no od de e* l le ef ft t; E En no od de e* r ri ig gh ht t; / / ... }; E En no od de e* e ex xp pr r(b bo oo ol l g ge et t) { E En no od de e* l le ef ft t = t te er rm m(g ge et t) ; f fo or r (;;) s sw wi it tc ch h(c cu ur rr r_ _t to ok k) { c ca as se e P PL LU US S: c ca as se e M MI IN NU US S: { E En no od de e* n n = n ne ew w E En no od de e; / / create an Enode on free store n n->o op pe er r = c cu ur rr r_ _t to ok k; n n->l le ef ft t = l le ef ft t; n n->r ri ig gh ht t = t te er rm m(t tr ru ue e) ; l le ef ft t = n n; b br re ea ak k; } d de ef fa au ul lt t: r re et tu ur rn n l le ef ft t; / / return node } } A code generator would then use the resulting nodes and delete them: v vo oi id d g ge en ne er ra at te e(E En no od de e* n n) { s sw wi it tc ch h (n n->o op pe er r) { c ca as se e P PL LU US S: / / ... d de el le et te e n n; / / delete an Enode from the free store } } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.128 Expressions and Statements Chapter 6 An object created by n ne ew w exists until it is explicitly destroyed by d de el le et te e. Then, the space it occu- pied can be reused by n ne ew w. A C++ implementation does not guarantee the presence of a ‘‘garbage collector’’ that looks out for unreferenced objects and makes them available to n ne ew w for reuse. Con- sequently, I will assume that objects created by n ne ew w are manually freed using d de el le et te e. If a garbage collector is present, the d de el le et te es can be omitted in most cases (§C.9.1). The d de el le et te e operator may be applied only to a pointer returned by n ne ew w or to zero. Applying d de el le et te e to zero has no effect. More specialized versions of operator n ne ew w can also be defined (§15.6). 6.2.6.1 Arrays [expr.array] Arrays of objects can also be created using n ne ew w. For example: c ch ha ar r* s sa av ve e_ _s st tr ri in ng g(c co on ns st t c ch ha ar r* p p) { c ch ha ar r* s s = n ne ew w c ch ha ar r[s st tr rl le en n(p p)+1 1] ; s st tr rc cp py y(s s,p p) ; / / copy from p to s r re et tu ur rn n s s; } i in nt t m ma ai in n(i in nt t a ar rg gc c, c ch ha ar r* a ar rg gv v[]) { i if f (a ar rg gc c < 2 2) e ex xi it t(1 1) ; c ch ha ar r* p p = s sa av ve e_ _s st tr ri in ng g(a ar rg gv v[1 1]) ; / / ... d de el le et te e[] p p; } The ‘‘plain’’ operator d de el le et te e is used to delete individual objects; d de el le et te e[] is used to delete arrays. To deallocate space allocated by n ne ew w, d de el le et te e and d de el le et te e[] must be able to determine the size of the object allocated. This implies that an object allocated using the standard implementation of n ne ew w will occupy slightly more space than a static object. Typically, one word is used to hold the object’s size. Note that a v ve ec ct to or r (§3.7.1, §16.3) is a proper object and can therefore be allocated and deallo- cated using plain n ne ew w and d de el le et te e. For example: v vo oi id d f f(i in nt t n n) { v ve ec ct to or r* p p = n ne ew w v ve ec ct to or r(n n) ; / / individual object i in nt t* q q = n ne ew w i in nt t[n n] ; / / array / / ... d de el le et te e p p; d de el le et te e[] q q; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.2.6.2 Memory Exhaustion 129 6.2.6.2 Memory Exhaustion [expr.exhaust] The free store operators n ne ew w, d de el le et te e, n ne ew w[], and d de el le et te e[] are implemented using functions: v vo oi id d* o op pe er ra at to or r n ne ew w(s si iz ze e_ _t t) ; / / space for individual object v vo oi id d o op pe er ra at to or r d de el le et te e(v vo oi id d*) ; v vo oi id d* o op pe er ra at to or r n ne ew w[](s si iz ze e_ _t t) ; / / space for array v vo oi id d o op pe er ra at to or r d de el le et te e[](v vo oi id d*) ; When operator n ne ew w needs to allocate space for an object, it calls o op pe er ra at to or r n ne ew w() to allocate a suit- able number of bytes. Similarly, when operator n ne ew w needs to allocate space for an array, it calls o op pe er ra at to or r n ne ew w[](). The standard implementations of o op pe er ra at to or r n ne ew w() and o op pe er ra at to or r n ne ew w[]() do not initialize the memory returned. What happens when n ne ew w can find no store to allocate? By default, the allocator throws a b ba ad d_ _a al ll lo oc c exception. For example: v vo oi id d f f() { t tr ry y { f fo or r(;;) n ne ew w c ch ha ar r[1 10 00 00 00 0] ; } c ca at tc ch h(b ba ad d_ _a al ll lo oc c) { c ce er rr r << "M Me em mo or ry y e ex xh ha au us st te ed d!\ \n n"; } } However much memory we have available, this will eventually invoke the b ba ad d_ _a al ll lo oc c handler. We can specify what n ne ew w should do upon memory exhaustion. When n ne ew w fails, it first calls a function specified by a call to s se et t_ _n ne ew w_ _h ha an nd dl le er r() declared in , if any. For example: v vo oi id d o ou ut t_ _o of f_ _s st to or re e() { c ce er rr r << "o op pe er ra at to or r n ne ew w f fa ai il le ed d: o ou ut t o of f s st to or re e\ \n n"; t th hr ro ow w b ba ad d_ _a al ll lo oc c() ; } i in nt t m ma ai in n() { s se et t_ _n ne ew w_ _h ha an nd dl le er r(o ou ut t_ _o of f_ _s st to or re e) ; / / make out_of_store the new_handler f fo or r (;;) n ne ew w c ch ha ar r[1 10 00 00 00 0] ; c co ou ut t << "d do on ne e\ \n n"; } This will never get to write d do on ne e. Instead, it will write o op pe er ra at to or r n ne ew w f fa ai il le ed d: o ou ut t o of f s st to or re e See §14.4.5 for a plausible implementation of an o op pe er ra at to or r n ne ew w() that checks to see if there is a new handler to call and that throws b ba ad d_ _a al ll lo oc c if not. A n ne ew w_ _h ha an nd dl le er r might do something more clever than simply terminating the program. If you know how n ne ew w and d de el le et te e work ± for example, The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.130 Expressions and Statements Chapter 6 because you provided your own o op pe er ra at to or r n ne ew w() and o op pe er ra at to or r d de el le et te e() ± the handler might attempt to find some memory for n ne ew w to return. In other words, a user might provide a garbage collector, thus rendering the use of d de el le et te e optional. Doing this is most definitely not a task for a beginner, though. For almost everybody who needs an automatic garbage collector, the right thing to do is to acquire one that has already been written and tested (§C.9.1). By providing a n ne ew w_ _h ha an nd dl le er r, we take care of the check for memory exhaustion for every ordi- nary use of n ne ew w in the program. Two alternative ways of controlling memory allocation exist. We can either provide nonstandard allocation and deallocation functions (§15.6) for the standard uses of n ne ew w or rely on additional allocation information provided by the user (§10.4.11, §19.4.5). 6.2.7 Explicit Type Conversion [expr.cast] Sometimes, we have to deal with‘‘raw memory;’’ that is, memory that holds or will hold objects of a type not known to the compiler. For example, a memory allocator may return a v vo oi id d* pointing to newly allocated memory or we might want to state that a given integer value is to be treated as the address of an I/O device: v vo oi id d* m ma al ll lo oc c(s si iz ze e_ _t t) ; v vo oi id d f f() { i in nt t* p p = s st ta at ti ic c_ _c ca as st t(m ma al ll lo oc c(1 10 00 0)) ; / / new allocation used as ints I IO O_ _d de ev vi ic ce e* d d1 1 = r re ei in nt te er rp pr re et t_ _c ca as st t(0 0X Xf ff f0 00 0) ; / / device at 0Xff00 / / ... } A compiler does not know the type of the object pointed to by the v vo oi id d*. Nor can it know whether the integer 0 0X Xf ff f0 00 0 is a valid address. Consequently, the correctness of the conversions are com- pletely in the hands of the programmer. Explicit type conversion, often called casting, is occasion- ally essential. However, traditionally it is seriously overused and a major source of errors. The s st ta at ti ic c_ _c ca as st t operator converts between related types such as one pointer type to another, an enumeration to an integral type, or a floating-point type to an integral type. The r re ei in nt te er rp pr re et t_ _c ca as st t handles conversions between unrelated types such as an integer to a pointer. This distinction allows the compiler to apply some minimal type checking for s st ta at ti ic c_ _c ca as st t and makes it easier for a programmer to find the more dangerous conversions represented as r re ei in nt te er rp pr re et t_ _c ca as st ts. Some s st ta at ti ic c_ _c ca as st ts are portable, but few r re ei in nt te er rp pr re et t_ _c ca as st ts are. Hardly any guarantees are made for r re ei in nt te er rp pr re et t_ _c ca as st t, but generally it produces a value of a new type that has the same bit pattern as its argument. If the target has at least as many bits as the original value, we can r re ei in nt te er rp pr re et t_ _c ca as st t the result back to its original type and use it. The result of a r re ei in nt te er rp pr re et t_ _c ca as st t is guaranteed to be usable only if its result type is the exact type used to define the value involved. Note that r re ei in nt te er rp pr re et t_ _c ca as st t is the kind of conversion that must be used for pointers to functions (§7.7). If you feel tempted to use an explicit type conversion, take the time to consider if it is really necessary. In C++, explicit type conversion is unnecessary in most cases when C needs it (§1.6) and also in many cases in which earlier versions of C++ needed it (§1.6.2, §B.2.3). In many pro- grams, explicit type conversion can be completely avoided; in others, its use can be localized to a few routines. In this book, explicit type conversion is used in realistic situations in §6.2.7, §7.7, §13.5, §15.4, and §25.4.1, only. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.2.7 Explicit Type Conversion 131 A form of run-time checked conversion, d dy yn na am mi ic c_ _c ca as st t (§15.4.1), and a cast for removing c co on ns st t qualifiers, c co on ns st t_ _c ca as st t (§15.4.2.1), are also provided. From C, C++ inherited the notation (T T)e e, which performs any conversion that can be expressed as a combination of s st ta at ti ic c_ _c ca as st ts, r re ei in nt te er rp pr re et t_ _c ca as st ts, and c co on ns st t_ _c ca as st ts to make a value of type T T from the expression e e (§B.2.3). This C-style cast is far more dangerous than the named conversion operators because the notation is harder to spot in a large program and the kind of conversion intended by the programmer is not explicit. That is, (T T)e e might be doing a portable conversion between related types, a nonportable conversion between unrelated types, or removing the c co on ns st t modifier from a pointer type. Without knowing the exact types of T T and e e, you cannot tell. 6.2.8 Constructors [expr.ctor] The construction of a value of type T T from a value e e can be expressed by the functional notation T T(e e). For example: v vo oi id d f f(d do ou ub bl le e d d) { i in nt t i i = i in nt t(d d) ; / / truncate d c co om mp pl le ex x z z = c co om mp pl le ex x(d d) ; / / make a complex from d / / ... } The T T(e e) construct is sometimes referred to as a function-style cast. For a built-in type T T, T T(e e) is equivalent to s st ta at ti ic c_ _c ca as st t(e e). Unfortunately, this implies that the use of T T(e e) is not always safe. For arithmetic types, values can be truncated and even explicit conversion of a longer integer type to a shorter (such as l lo on ng g to c ch ha ar r) can result in undefined behavior. I try to use the notation exclusively where the construction of a value is well-defined; that is, for narrowing arithmetic con- versions (§C.6), for conversion from integers to enumerations (§4.8), and the construction of objects of user-defined types (§2.5.2, §10.2.3). Pointer conversions cannot be expressed directly using the T T(e e) notation. For example, c ch ha ar r*(2 2) is a syntax error. Unfortunately, the protection that the constructor notation provides against such dangerous conversions can be circumvented by using t ty yp pe ed de ef f names (§4.9.7) for pointer types. The constructor notation T T() is used to express the default value of type T T. For example: v vo oi id d f f(d do ou ub bl le e d d) { i in nt t j j = i in nt t() ; / / default int value c co om mp pl le ex x z z = c co om mp pl le ex x() ; / / default complex value / / ... } The value of an explicit use of the constructor for a built-in type is 0 0 converted to that type (§4.9.5). Thus, i in nt t() is another way of writing 0 0. For a user-defined type T T, T T() is defined by the default constructor (§10.4.2), if any. The use of the constructor notation for built-in types is particularly important when writing tem- plates. Then, the programmer does not know whether a template parameter will refer to a built-in type or a user-defined type (§16.3.4, §17.4.1.2). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.132 Expressions and Statements Chapter 6 6.3 Statement Summary [expr.stmts] Here are a summary and some examples of C++ statements:_ ______________________________________________________________ Statement Syntax_ _______________________________________________________________ ______________________________________________________________ statement: declaration { statement-listopt } t tr ry y { statement-listopt } handler-list expressionopt ; i if f ( condition ) statement i if f ( condition ) statement e el ls se estatement s sw wi it tc ch h ( condition ) statement w wh hi il le e ( condition ) statement d do ostatement w wh hi il le e ( expression ) ; f fo or r ( for-init-statement conditionopt ; expressionopt ) statement c ca as se econstant-expression : statement d de ef fa au ul lt t : statement b br re ea ak k ; c co on nt ti in nu ue e ; r re et tu ur rn nexpressionopt ; g go ot to oidentifier ; identifier : statement statement-list: statement statement-listopt condition: expression type-specifier declarator = expression handler-list: c ca at tc ch h ( exception-declaration ) { statement-listopt } handler-list handler-listopt_ ______________________________________________________________                                                                                     Note that a declaration is a statement and that there is no assignment statement or procedure call statement; assignments and function calls are expressions. The statements for handling exceptions, try-blocks, are described in §8.3.1. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.3.1 Declarations as Statements 133 6.3.1 Declarations as Statements [expr.dcl] A declaration is a statement. Unless a variable is declared s st ta at ti ic c, its initializer is executed when- ever the thread of control passes through the declaration (see also §10.4.8). The reason for allow- ing declarations wherever a statement can be used (and a few other places; §6.3.2.1, §6.3.3.1) is to enable the programmer to minimize the errors caused by uninitialized variables and to allow better locality in code. There is rarely a reason to introduce a variable before there is a value for it to hold. For example: v vo oi id d f f(v ve ec ct to or r& v v, i in nt t i i, c co on ns st t c ch ha ar r* p p) { i if f (p p==0 0) r re et tu ur rn n; i if f (i i<0 0 || v v.s si iz ze e()<=i i) e er rr ro or r("b ba ad d i in nd de ex x") ; s st tr ri in ng g s s = v v[i i] ; i if f (s s == p p) { / / ... } / / ... } The ability to place declarations after executable code is essential for many constants and for single-assignment styles of programming where a value of an object is not changed after initial- ization. For user-defined types, postponing the definition of a variable until a suitable initializer is available can also lead to better performance. For example, s st tr ri in ng g s s; /* ... */ s s = "T Th he e b be es st t i is s t th he e e en ne em my y o of f t th he e g go oo od d."; can easily be much slower than s st tr ri in ng g s s = "V Vo ol lt ta ai ir re e"; The most common reason to declare a variable without an initializer is that it requires a statement to initialize it. Examples are input variables and arrays. 6.3.2 Selection Statements [expr.select] A value can be tested by either an i if f statement or a s sw wi it tc ch h statement: i if f ( condition ) statement i if f ( condition ) statement e el ls se estatement s sw wi it tc ch h( condition ) statement The comparison operators == != < <= > >= return the b bo oo ol l t tr ru ue e if the comparison is true and f fa al ls se e otherwise. In an i if f statement, the first (or only) statement is executed if the expression is nonzero and the second statement (if it is specified) is executed otherwise. This implies that any arithmetic or pointer expression can be used as a condition. For example, if x x is an integer, then i if f (x x) / / ... The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.134 Expressions and Statements Chapter 6 means i if f (x x != 0 0) / / ... For a pointer p p, i if f (p p) / / ... is a direct statement of the test ‘‘does p p point to a valid object,’’ whereas i if f (p p != 0 0) / / ... states the same question indirectly by comparing to a value known not to point to an object. Note that the representation of the pointer 0 0 is not all-zeros on all machines (§5.1.1). Every compiler I have checked generated the same code for both forms of the test. The logical operators && || ! are most commonly used in conditions. The operators && and || will not evaluate their second argument unless doing so is necessary. For example, i if f (p p && 1 1

c co ou un nt t) / / ... first tests that p p is nonzero. It tests 1 1

c co ou un nt t only if p p is nonzero. Some if-statements can conveniently be replaced by conditional-expressions. For example, i if f (a a <= b b) m ma ax x = b b; e el ls se e m ma ax x = a a; is better expressed like this: m ma ax x = (a a<=b b) ? b b : a a; The parentheses around the condition are not necessary, but I find the code easier to read when they are used. A switch-statement can alternatively be written as a set of i if f-s st ta at te em me en nt ts. For example, s sw wi it tc ch h (v va al l) { c ca as se e 1 1: f f() ; b br re ea ak k; c ca as se e 2 2: g g() ; b br re ea ak k; d de ef fa au ul lt t: h h() ; b br re ea ak k; } could alternatively be expressed as The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.3.2 Selection Statements 135 i if f (v va al l == 1 1) f f() ; e el ls se e i if f (v va al l == 2 2) g g() ; e el ls se e h h() ; The meaning is the same, but the first (s sw wi it tc ch h) version is preferred because the nature of the opera- tion (testing a value against a set of constants) is explicit. This makes the s sw wi it tc ch h statement easier to read for nontrivial examples. It can also lead to the generation of better code. Beware that a case of a switch must be terminated somehow unless you want to carry on execut- ing the next case. Consider: s sw wi it tc ch h (v va al l) { / / beware c ca as se e 1 1: c co ou ut t << "c ca as se e 1 1\ \n n"; c ca as se e 2 2: c co ou ut t << "c ca as se e 2 2\ \n n"; d de ef fa au ul lt t: c co ou ut t << "d de ef fa au ul lt t: c ca as se e n no ot t f fo ou un nd d\ \n n"; } Invoked with v va al l==1 1, this prints c ca as se e 1 1 c ca as se e 2 2 d de ef fa au ul lt t: c ca as se e n no ot t f fo ou un nd d to the great surprise of the uninitiated. It is a good idea to comment the (rare) cases in which a fall-through is intentional so that an uncommented fall-through can be assumed to be an error. A b br re ea ak k is the most common way of terminating a case, but a r re et tu ur rn n is often useful (§6.1.1). 6.3.2.1 Declarations in Conditions [expr.cond] To avoid accidental misuse of a variable, it is usually a good idea to introduce the variable into the smallest scope possible. In particular, it is usually best to delay the definition of a local variable until one can give it an initial value. That way, one cannot get into trouble by using the variable before its initial value is assigned. One of the most elegant applications of these two principles is to declare a variable in a condi- tion. Consider: i if f (d do ou ub bl le e d d = p pr ri im m(t tr ru ue e)) { l le ef ft t /= d d; b br re ea ak k; } Here, d d is declared and initialized and the value of d d after initialization is tested as the value of the condition. The scope of d d extends from its point of declaration to the end of the statement that the condition controls. For example, had there been an e el ls se e-branch to the if-statement, d d would be in scope on both branches. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.136 Expressions and Statements Chapter 6 The obvious and traditional alternative is to declare d d before the condition. However, this opens the scope (literally) for the use of d d before its initialization or after its intended useful life: d do ou ub bl le e d d; / / ... d d2 2 = d d; / / oops! / / ... i if f (d d = p pr ri im m(t tr ru ue e)) { l le ef ft t /= d d; b br re ea ak k; } / / ... d d = 2 2.0 0; / / two unrelated uses of d In addition to the logical benefits of declaring variables in conditions, doing so also yields the most compact source code. A declaration in a condition must declare and initialize a single variable or c co on ns st t. 6.3.3 Iteration Statements [expr.loop] A loop can be expressed as a f fo or r, w wh hi il le e, or d do o statement: w wh hi il le e ( c co on nd di it ti io on n ) s st ta at te em me en nt t d do o s st ta at te em me en nt t w wh hi il le e ( e ex xp pr re es ss si io on n ) ; f fo or r ( f fo or r-i in ni it t-s st ta at te em me en nt t c co on nd di it ti io on no op pt t ; e ex xp pr re es ss si io on no op pt t ) s st ta at te em me en nt t Each of these statements executes a statement (called the controlled statement or the body of the loop) repeatedly until the condition becomes false or the programmer breaks out of the loop some other way. The for-statement is intended for expressing fairly regular loops. The loop variable, the termi- nation condition, and the expression that updates the loop variable can be presented ‘‘up front’’ on a single line. This can greatly increase readability and thereby decrease the frequency of errors. If no initialization is needed, the initializing statement can be empty. If the condition is omitted, the for-statement will loop forever unless the user explicitly exits it by a b br re ea ak k, r re et tu ur rn n, g go ot to o, t th hr ro ow w, or some less obvious way such as a call of e ex xi it t() (§9.4.1.1). If the expression is omitted, we must update some form of loop variable in the body of the loop. If the loop isn’t of the simple ‘‘intro- duce a loop variable, test the condition, update the loop variable’’ variety, it is often better expressed as a while-statement. A for-statement is also useful for expressing a loop without an explicit termination condition: f fo or r(;;) { / / ‘‘forever’’ / / ... } A while-statement simply executes its controlled statement until its condition becomes f fa al ls se e. I tend to prefer while-statements over for-statements when there isn’t an obvious loop variable or where the update of a loop variable naturally comes in the middle of the loop body. An input loop is an example of a loop where there is no obvious loop variable: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 6.3.3 Iteration Statements 137 w wh hi il le e(c ci in n>>c ch h) / / ... In my experience, the do-statement is a source of errors and confusion. The reason is that its body is always executed once before the condition is evaluated. However, for the body to work cor- rectly, something very much like the condition must hold even the first time through. More often than I would have guessed, I have found that condition not to hold as expected either when the pro- gram was first written and tested or later after the code preceding it has been modified. I also prefer the condition ‘‘up front where I can see it.’’ Consequently, I tend to avoid do-statements. 6.3.3.1 Declarations in For-Statements [expr.for] A variable can be declared in the initializer part of a for-statement. If that initializer is a declara- tion, the variable (or variables) it introduces is in scope until the end of the for-statement. For example: v vo oi id d f f(i in nt t v v[] , i in nt t m ma ax x) { f fo or r (i in nt t i i = 0 0; i im m *p p.m m *a a[i i] 10. (*2) Write these functions: s st tr rl le en n(), which returns the length of a C-style string; s st tr rc cp py y(), which copies a string into another; and s st tr rc cm mp p(), which compares two strings. Consider what the argument types and return types ought to be. Then compare your functions with the stan- dard library versions as declared in () and as specified in §20.4.1. 11. (∗1) See how your compiler reacts to these errors: v vo oi id d f f(i in nt t a a, i in nt t b b) { i if f (a a = 3 3) / / ... i if f (a a&0 07 77 7 == 0 0) / / ... a a := b b+1 1; } Devise more simple errors and see how the compiler reacts. 12. (∗2) Modify the program from §6.6[3] to also compute the median. 13. (∗2) Write a function c ca at t() that takes two C-style string arguments and returns a string that is the concatenation of the arguments. Use n ne ew w to find store for the result. 14. (∗2) Write a function r re ev v() that takes a string argument and reverses the characters in it. That is, after r re ev v(p p) the last character of p p will be the first, etc. 15. (∗1.5) What does the following example do? v vo oi id d s se en nd d(i in nt t* t to o, i in nt t* f fr ro om m, i in nt t c co ou un nt t) / / Duff’s device. Helpful comment deliberately deleted. { i in nt t n n = (c co ou un nt t+7 7)/8 8; s sw wi it tc ch h (c co ou un nt t%8 8) { c ca as se e 0 0: d do o { *t to o++ = *f fr ro om m++; c ca as se e 7 7: *t to o++ = *f fr ro om m++; c ca as se e 6 6: *t to o++ = *f fr ro om m++; c ca as se e 5 5: *t to o++ = *f fr ro om m++; c ca as se e 4 4: *t to o++ = *f fr ro om m++; c ca as se e 3 3: *t to o++ = *f fr ro om m++; c ca as se e 2 2: *t to o++ = *f fr ro om m++; c ca as se e 1 1: *t to o++ = *f fr ro om m++; } w wh hi il le e (--n n>0 0) ; } } Why would anyone write something like that? 16. (∗2) Write a function a at to oi i(c co on ns st t c ch ha ar r*) that takes a string containing digits and returns the corresponding i in nt t. For example, a at to oi i("1 12 23 3") is 1 12 23 3. Modify a at to oi i() to handle C++ octal and hexadecimal notation in addition to plain decimal numbers. Modify a at to oi i() to handle the C++ The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.142 Expressions and Statements Chapter 6 character constant notation. 17. (∗2) Write a function i it to oa a(i in nt t i i, c ch ha ar r b b[]) that creates a string representation of i i in b b and returns b b. 18. (*2) Type in the calculator example and get it to work. Do not ‘‘save time’’ by using an already entered text. You’ll learn most from finding and correcting ‘‘little silly errors.’’ 19. (∗2) Modify the calculator to report line numbers for errors. 20. (∗3) Allow a user to define functions in the calculator. Hint: Define a function as a sequence of operations just as a user would have typed them. Such a sequence can be stored either as a character string or as a list of tokens. Then read and execute those operations when the function is called. If you want a user-defined function to take arguments, you will have to invent a nota- tion for that. 21. (∗1.5) Convert the desk calculator to use a s sy ym mb bo ol l structure instead of using the static variables n nu um mb be er r_ _v va al lu ue e and s st tr ri in ng g_ _v va al lu ue e. 22. (∗2.5) Write a program that strips comments out of a C++ program. That is, read from c ci in n, remove both / / comments and /* */ comments, and write the result to c co ou ut t. Do not worry about making the layout of the output look nice (that would be another, and much harder, exer- cise). Do not worry about incorrect programs. Beware of / /, /*, and */ in comments, strings, and character constants. 23. (∗2) Look at some programs to get an idea of the variety of indentation, naming, and comment- ing styles actually used. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 7 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Functions To iterate is human, to recurse divine. ± L. Peter Deutsch Function declarations and definitions Ð argument passing Ð return values Ð function overloading Ð ambiguity resolution Ð default arguments Ð s st td da ar rg gs s Ð pointers to functions Ð macros Ð advice Ð exercises. 7.1 Function Declarations [fct.dcl] The typical way of getting something done in a C++ program is to call a function to do it. Defining a function is the way you specify how an operation is to be done. A function cannot be called unless it has been previously declared. A function declaration gives the name of the function, the type of the value returned (if any) by the function, and the number and types of the arguments that must be supplied in a call of the func- tion. For example: E El le em m* n ne ex xt t_ _e el le em m() ; c ch ha ar r* s st tr rc cp py y(c ch ha ar r* t to o, c co on ns st t c ch ha ar r* f fr ro om m) ; v vo oi id d e ex xi it t(i in nt t) ; The semantics of argument passing are identical to the semantics of initialization. Argument types are checked and implicit argument type conversion takes place when necessary. For example: d do ou ub bl le e s sq qr rt t(d do ou ub bl le e) ; d do ou ub bl le e s sr r2 2 = s sq qr rt t(2 2) ; / / call sqrt() with the argument double(2) d do ou ub bl le e s sq q3 3 = s sq qr rt t("t th hr re ee e") ; / / error: sqrt() requires an argument of type double The value of such checking and type conversion should not be underestimated. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.144 Functions Chapter 7 A function declaration may contain argument names. This can be a help to the reader of a pro- gram, but the compiler simply ignores such names. As mentioned in §4.7, v vo oi id d as a return type means that the function does not return a value. 7.1.1 Function Definitions [fct.def] Every function that is called in a program must be defined somewhere (once only). A function def- inition is a function declaration in which the body of the function is presented. For example: e ex xt te er rn n v vo oi id d s sw wa ap p(i in nt t*, i in nt t*) ; / / a declaration v vo oi id d s sw wa ap p(i in nt t* p p, i in nt t* q q) / / a definition { i in nt t t t = *p p; *p p = *q q; *q q = t t; } The type of the definition and all declarations for a function must specify the same type. The argu- ment names, however, are not part of the type and need not be identical. It is not uncommon to have function definitions with unused arguments: v vo oi id d s se ea ar rc ch h(t ta ab bl le e* t t, c co on ns st t c ch ha ar r* k ke ey y, c co on ns st t c ch ha ar r*) { / / no use of the third argument } As shown, the fact that an argument is unused can be indicated by not naming it. Typically, unnamed arguments arise from the simplification of code or from planning ahead for extensions. In both cases, leaving the argument in place, although unused, ensures that callers are not affected by the change. A function can be defined to be i in nl li in ne e. For example: i in nl li in ne e i in nt t f fa ac c(i in nt t n n) { r re et tu ur rn n (n n<2 2) ? 1 1 : n n*f fa ac c(n n-1 1) ; } The i in nl li in ne e specifier is a hint to the compiler that it should attempt to generate code for a call of f fa ac c() inline rather than laying down the code for the function once and then calling through the usual function call mechanism. A clever compiler can generate the constant 7 72 20 0 for a call f fa ac c(6 6). The possibility of mutually recursive inline functions, inline functions that recurse or not depending on input, etc., makes it impossible to guarantee that every call of an i in nl li in ne e function is actually inlined. The degree of cleverness of a compiler cannot be legislated, so one compiler might gener- ate 7 72 20 0, another 6 6*f fa ac c(5 5), and yet another an un-inlined call f fa ac c(6 6). To make inlining possible in the absence of unusually clever compilation and linking facilities, the definition ± and not just the declaration ± of an inline function must be in scope (§9.2). An i in nl li in ne e specifier does not affect the semantics of a function. In particular, an inline function still has a unique address and so has s st ta at ti ic c variables (§7.1.2) of an inline function. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 7.1.2 Static Variables 145 7.1.2 Static Variables [fct.static] A local variable is initialized when the thread of execution reaches its definition. By default, this happens in every call of the function and each invocation of the function has its own copy of the variable. If a local variable is declared s st ta at ti ic c, a single, statically allocated object will be used to represent that variable in all calls of the function. It will be initialized only the first time the thread of execution reaches its definition. For example: v vo oi id d f f(i in nt t a a) { w wh hi il le e (a a--) { s st ta at ti ic c i in nt t n n = 0 0; / / initialized once i in nt t x x = 0 0; / / initialized n times c co ou ut t << "n n == " << n n++ << ", x x == " << x x++ << ´\ \n n´; } } i in nt t m ma ai in n() { f f(3 3) ; } This prints: n n == 0 0, x x == 0 0 n n == 1 1, x x == 0 0 n n == 2 2, x x == 0 0 A static variable provides a function with ‘‘a memory’’ without introducing a global variable that might be accessed and corrupted by other functions (see also §10.2.4). 7.2 Argument Passing [fct.arg] When a function is called, store is set aside for its formal arguments and each formal argument is initialized by its corresponding actual argument. The semantics of argument passing are identical to the semantics of initialization. In particular, the type of an actual argument is checked against the type of the corresponding formal argument, and all standard and user-defined type conversions are performed. There are special rules for passing arrays (§7.2.1), a facility for passing unchecked arguments (§7.6), and a facility for specifying default arguments (§7.5). Consider: v vo oi id d f f(i in nt t v va al l, i in nt t& r re ef f) { v va al l++; r re ef f++; } When f f() is called, v va al l++ increments a local copy of the first actual argument, whereas r re ef f++ increments the second actual argument. For example, The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.146 Functions Chapter 7 v vo oi id d g g() { i in nt t i i = 1 1; i in nt t j j = 1 1; f f(i i,j j) ; } will increment j j but not i i. The first argument, i i, is passed by value, the second argument, j j, is passed by reference. As mentioned in §5.5, functions that modify call-by-reference arguments can make programs hard to read and should most often be avoided (but see §21.2.1). It can, however, be noticeably more efficient to pass a large object by reference than to pass it by value. In that case, the argument might be declared c co on ns st t to indicate that the reference is used for efficiency rea- sons only and not to enable the called function to change the value of the object: v vo oi id d f f(c co on ns st t L La ar rg ge e& a ar rg g) { / / the value of "arg" cannot be changed without explicit use of type conversion } The absence of c co on ns st t in the declaration of a reference argument is taken as a statement of intent to modify the variable: v vo oi id d g g(L La ar rg ge e& a ar rg g) ; / / assume that g() modifies arg Similarly, declaring a pointer argument c co on ns st t tells readers that the value of an object pointed to by that argument is not changed by the function. For example: i in nt t s st tr rl le en n(c co on ns st t c ch ha ar r*) ; / / number of characters in a C-style string c ch ha ar r* s st tr rc cp py y(c ch ha ar r* t to o, c co on ns st t c ch ha ar r* f fr ro om m) ; / / copy a C-style string i in nt t s st tr rc cm mp p(c co on ns st t c ch ha ar r*, c co on ns st t c ch ha ar r*) ; / / compare C-style strings The importance of using c co on ns st t arguments increases with the size of a program. Note that the semantics of argument passing are different from the semantics of assignment. This is important for c co on ns st t arguments, reference arguments, and arguments of some user-defined types (§10.4.4.1). A literal, a constant, and an argument that requires conversion can be passed as a c co on ns st t& argu- ment, but not as a non-c co on ns st t argument. Allowing conversions for a c co on ns st t T T& argument ensures that such an argument can be given exactly the same set of values as a T T argument by passing the value in a temporary, if necessary. For example: f fl lo oa at t f fs sq qr rt t(c co on ns st t f fl lo oa at t&) ; / / Fortran-style sqrt taking a reference argument v vo oi id d g g(d do ou ub bl le e d d) { f fl lo oa at t r r = f fs sq qr rt t(2 2.0 0f f) ; / / pass ref to temp holding 2.0f r r = f fs sq qr rt t(r r) ; / / pass ref to r r r = f fs sq qr rt t(d d) ; / / pass ref to temp holding float(d) } Disallowing conversions for non-c co on ns st t reference arguments (§5.5) avoids the possibility of silly mistakes arising from the introduction of temporaries. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 7.2 Argument Passing 147 v vo oi id d u up pd da at te e(f fl lo oa at t& i i) ; v vo oi id d g g(d do ou ub bl le e d d, f fl lo oa at t r r) { u up pd da at te e(2 2.0 0f f) ; / / error: const argument u up pd da at te e(r r) ; / / pass ref to r u up pd da at te e(d d) ; / / error: type conversion required } Had these calls been allowed, u up pd da at te e() would quietly have updated temporaries that immediately were deleted. Usually, that would come as an unpleasant surprise to the programmer. 7.2.1 Array Arguments [fct.array] If an array is used as a function argument, a pointer to its initial element is passed. For example: i in nt t s st tr rl le en n(c co on ns st t c ch ha ar r*) ; v vo oi id d f f() { c ch ha ar r v v[] = "a an n a ar rr ra ay y"; i in nt t i i = s st tr rl le en n(v v) ; i in nt t j j = s st tr rl le en n("N Ni ic ch ho ol la as s") ; } That is, an argument of type T T[] will be converted to a T T* when passed as an argument. This implies that an assignment to an element of an array argument changes the value of an element of the argument array. In other words, arrays differ from other types in that an array is not (and can- not be) passed by value. The size of an array is not available to the called function. This can be a nuisance, but there are several ways of circumventing this problem. C-style strings are zero-terminated, so their size can be computed easily. For other arrays, a second argument specifying the size can be passed. For example: v vo oi id d c co om mp pu ut te e1 1(i in nt t* v ve ec c_ _p pt tr r, i in nt t v ve ec c_ _s si iz ze e) ; / / one way s st tr ru uc ct t V Ve ec c { i in nt t* p pt tr r; i in nt t s si iz ze e; }; v vo oi id d c co om mp pu ut te e2 2(c co on ns st t V Ve ec c& v v) ; / / another way Alternatively, a type such as v ve ec ct to or r (§3.7.1, §16.3) can be used instead of an array. Multidimensional arrays are trickier (see §C.7), but often arrays of pointers can be used instead, and they need no special treatment. For example: c ch ha ar r* d da ay y[] = { "m mo on n", "t tu ue e", "w we ed d", "t th hu u", "f fr ri i", "s sa at t", "s su un n" }; Again, v ve ec ct to or r and similar types are alternatives to the built-in, low-level arrays and pointers. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.148 Functions Chapter 7 7.3 Value Return [fct.return] A value must be returned from a function that is not declared v vo oi id d (however, m ma ai in n() is special; see §3.2). Conversely, a value cannot be returned from a v vo oi id d function. For example: i in nt t f f1 1() { } / / error: no value returned v vo oi id d f f2 2() { } / / ok i in nt t f f3 3() { r re et tu ur rn n 1 1; } / / ok v vo oi id d f f4 4() { r re et tu ur rn n 1 1; } / / error: return value in void function i in nt t f f5 5() { r re et tu ur rn n; } / / error: return value missing v vo oi id d f f6 6() { r re et tu ur rn n; } / / ok A return value is specified by a return statement. For example: i in nt t f fa ac c(i in nt t n n) { r re et tu ur rn n (n n>1 1) ? n n*f fa ac c(n n-1 1) : 1 1; } A function that calls itself is said to be recursive. There can be more than one return statement in a function: i in nt t f fa ac c2 2(i in nt t n n) { i if f (n n > 1 1) r re et tu ur rn n n n*f fa ac c2 2(n n-1 1) ; r re et tu ur rn n 1 1; } Like the semantics of argument passing, the semantics of function value return are identical to the semantics of initialization. A return statement is considered to initialize an unnamed variable of the returned type. The type of a return expression is checked against the type of the returned type, and all standard and user-defined type conversions are performed. For example: d do ou ub bl le e f f() { r re et tu ur rn n 1 1; } / / 1 is implicitly converted to double(1) Each time a function is called, a new copy of its arguments and local (automatic) variables is cre- ated. The store is reused after the function returns, so a pointer to a local variable should never be returned. The contents of the location pointed to will change unpredictably: i in nt t* f fp p() { i in nt t l lo oc ca al l = 1 1; /* ... */ r re et tu ur rn n &l lo oc ca al l; } / / bad This error is less common than the equivalent error using references: i in nt t& f fr r() { i in nt t l lo oc ca al l = 1 1; /* ... */ r re et tu ur rn n l lo oc ca al l; } / / bad Fortunately, a compiler can easily warn about returning references to local variables. A v vo oi id d function cannot return a value. However, a call of a v vo oi id d function doesn’t yield a value, so a v vo oi id d function can use a call of a v vo oi id d function as the expression in a r re et tu ur rn n statement. For example: v vo oi id d g g(i in nt t* p p) ; v vo oi id d h h(i in nt t* p p) { /* ... */ r re et tu ur rn n g g(p p) ; } / / ok: return of ‘‘no value’’ This form of return is important when writing template functions where the return type is a tem- plate parameter (see §18.4.4.2). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 7.4 Overloaded Function Names 149 7.4 Overloaded Function Names [fct.over] Most often, it is a good idea to give different functions different names, but when some functions conceptually perform the same task on objects of different types, it can be more convenient to give them the same name. Using the same name for operations on different types is called overloading. The technique is already used for the basic operations in C++. That is, there is only one name for addition, +, yet it can be used to add values of integer, floating-point, and pointer types. This idea is easily extended to functions defined by the programmer. For example: v vo oi id d p pr ri in nt t(i in nt t) ; / / print an int v vo oi id d p pr ri in nt t(c co on ns st t c ch ha ar r*) ; / / print a C-style character string As far as the compiler is concerned, the only thing functions of the same name have in common is that name. Presumably, the functions are in some sense similar, but the language does not con- strain or aid the programmer. Thus overloaded function names are primarily a notational conve- nience. This convenience is significant for functions with conventional names such as s sq qr rt t, p pr ri in nt t, and o op pe en n. When a name is semantically significant, this convenience becomes essential. This hap- pens, for example, with operators such as +, *, and <<, in the case of constructors (§11.7), and in generic programming (§2.7.2, Chapter 18). When a function f f is called, the compiler must figure out which of the functions with the name f f is to be invoked. This is done by comparing the types of the actual arguments with the types of the formal arguments of all functions called f f. The idea is to invoke the function that is the best match on the arguments and give a compile-time error if no function is the best match. For example: v vo oi id d p pr ri in nt t(d do ou ub bl le e) ; v vo oi id d p pr ri in nt t(l lo on ng g) ; v vo oi id d f f() { p pr ri in nt t(1 1L L) ; / / print(long) p pr ri in nt t(1 1.0 0) ; / / print(double) p pr ri in nt t(1 1) ; / / error, ambiguous: print(long(1)) or print(double(1))? } Finding the right version to call from a set of overloaded functions is done by looking for a best match between the type of the argument expression and the parameters (formal arguments) of the functions. To approximate our notions of what is reasonable, a series of criteria are tried in order: [1] Exact match; that is, match using no or only trivial conversions (for example, array name to pointer, function name to pointer to function, and T T to c co on ns st t T T) [2] Match using promotions; that is, integral promotions (b bo oo ol l to i in nt t, c ch ha ar r to i in nt t, s sh ho or rt t to i in nt t, and their u un ns si ig gn ne ed d counterparts; §C.6.1), f fl lo oa at t to d do ou ub bl le e, and d do ou ub bl le e to l lo on ng g d do ou ub bl le e [3] Match using standard conversions (for example, i in nt t to d do ou ub bl le e, d do ou ub bl le e to i in nt t, D De er ri iv ve ed d* to B Ba as se e* (§12.2), T* to v vo oi id d* (§5.6), i in nt t to u un ns si ig gn ne ed d i in nt t; §C.6) [4] Match using user-defined conversions (§11.4) [5] Match using the ellipsis ... in a function declaration (§7.6) If two matches are found at the highest level where a match is found, the call is rejected as ambigu- ous. The resolution rules are this elaborate primarily to take into account the elaborate C and C++ rules for built-in numeric types (§C.6). For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.150 Functions Chapter 7 v vo oi id d p pr ri in nt t(i in nt t) ; v vo oi id d p pr ri in nt t(c co on ns st t c ch ha ar r*) ; v vo oi id d p pr ri in nt t(d do ou ub bl le e) ; v vo oi id d p pr ri in nt t(l lo on ng g) ; v vo oi id d p pr ri in nt t(c ch ha ar r) ; v vo oi id d h h(c ch ha ar r c c, i in nt t i i, s sh ho or rt t s s, f fl lo oa at t f f) { p pr ri in nt t(c c) ; / / exact match: invoke print(char) p pr ri in nt t(i i) ; / / exact match: invoke print(int) p pr ri in nt t(s s) ; / / integral promotion: invoke print(int) p pr ri in nt t(f f) ; / / float to double promotion: print(double) p pr ri in nt t(´a a´) ; / / exact match: invoke print(char) p pr ri in nt t(4 49 9) ; / / exact match: invoke print(int) p pr ri in nt t(0 0) ; / / exact match: invoke print(int) p pr ri in nt t("a a") ; / / exact match: invoke print(const char*) } The call p pr ri in nt t(0 0) invokes p pr ri in nt t(i in nt t) because 0 0 is an i in nt t. The call p pr ri in nt t(´a a´) invokes p pr ri in nt t(c ch ha ar r) because ´a a´ is a c ch ha ar r (§4.3.1). The reason to distinguish between conversions and promotions is that we want to prefer safe promotions, such as c ch ha ar r to i in nt t, over unsafe conversions, such as i in nt t to c ch ha ar r. The overloading resolution is independent of the order of declaration of the functions consid- ered. Overloading relies on a relatively complicated set of rules, and occasionally a programmer will be surprised which function is called. So, why bother? Consider the alternative to overloading. Often, we need similar operations performed on objects of several types. Without overloading, we must define several functions with different names: v vo oi id d p pr ri in nt t_ _i in nt t(i in nt t) ; v vo oi id d p pr ri in nt t_ _c ch ha ar r(c ch ha ar r) ; v vo oi id d p pr ri in nt t_ _s st tr ri in ng g(c co on ns st t c ch ha ar r*) ; / / C-style string v vo oi id d g g(i in nt t i i, c ch ha ar r c c, c co on ns st t c ch ha ar r* p p, d do ou ub bl le e d d) { p pr ri in nt t_ _i in nt t(i i) ; / / ok p pr ri in nt t_ _c ch ha ar r(c c) ; / / ok p pr ri in nt t_ _s st tr ri in ng g(p p) ; / / ok p pr ri in nt t_ _i in nt t(c c) ; / / ok? calls print_int(int(c)) p pr ri in nt t_ _c ch ha ar r(i i) ; / / ok? calls print_char(char(i)) p pr ri in nt t_ _s st tr ri in ng g(i i) ; / / error p pr ri in nt t_ _i in nt t(d d) ; / / ok? calls print_int(int(d)) } Compared to the overloaded p pr ri in nt t(), we have to remember several names and remember to use those correctly. This can be tedious, defeats attempts to do generic programming (§2.7.2), and gen- erally encourages the programmer to focus on relatively low-level type issues. Because there is no overloading, all standard conversions apply to arguments to these functions. It can also lead to The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 7.4 Overloaded Function Names 151 errors. In the previous example, this implies that only one of the four calls with a ‘‘wrong’’ argu- ment is caught by the compiler. Thus, overloading can increase the chances that an unsuitable argument will be rejected by the compiler. 7.4.1 Overloading and Return Type [fct.return] Return types are not considered in overload resolution. The reason is to keep resolution for an indi- vidual operator (§11.2.1, §11.2.4) or function call context-independent. Consider: f fl lo oa at t s sq qr rt t(f fl lo oa at t) ; d do ou ub bl le e s sq qr rt t(d do ou ub bl le e) ; v vo oi id d f f(d do ou ub bl le e d da a, f fl lo oa at t f fl la a) { f fl lo oa at t f fl l = s sq qr rt t(d da a) ; / / call sqrt(double) d do ou ub bl le e d d = s sq qr rt t(d da a) ; / / call sqrt(double) f fl l = s sq qr rt t(f fl la a) ; / / call sqrt(float) d d = s sq qr rt t(f fl la a) ; / / call sqrt(float) } If the return type were taken into account, it would no longer be possible to look at a call of s sq qr rt t() in isolation and determine which function was called. 7.4.2 Overloading and Scopes [fct.scope] Functions declared in different non-namespace scopes do not overload. For example: v vo oi id d f f(i in nt t) ; v vo oi id d g g() { v vo oi id d f f(d do ou ub bl le e) ; f f(1 1) ; / / call f(double) } Clearly, f f(i in nt t) would have been the best match for f f(1 1), but only f f(d do ou ub bl le e) is in scope. In such cases, local declarations can be added or subtracted to get the desired behavior. As always, inten- tional hiding can be a useful technique, but unintentional hiding is a source of surprises. When overloading across class scopes (§15.2.2) or namespace scopes (§8.2.9.2) is wanted, using- declarations or u us si in ng g-d di ir re ec ct ti iv ve es s can be used (§8.2.2). See also §8.2.6 and §8.2.9.2. 7.4.3 Manual Ambiguity Resolution [fct.man.ambig] Declaring too few (or too many) overloaded versions of a function can lead to ambiguities. For example: v vo oi id d f f1 1(c ch ha ar r) ; v vo oi id d f f1 1(l lo on ng g) ; v vo oi id d f f2 2(c ch ha ar r*) ; v vo oi id d f f2 2(i in nt t*) ; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.152 Functions Chapter 7 v vo oi id d k k(i in nt t i i) { f f1 1(i i) ; / / ambiguous: f1(char) or f1(long) f f2 2(0 0) ; / / ambiguous: f2(char*) or f2(int*) } Where possible, the thing to do in such cases is to consider the set of overloaded versions of a func- tion as a whole and see if it makes sense according to the semantics of the function. Often the problem can be solved by adding a version that resolves ambiguities. For example, adding i in nl li in ne e v vo oi id d f f1 1(i in nt t n n) { f f1 1(l lo on ng g(n n)) ; } would resolve all ambiguities similar to f f1 1(i i) in favor of the larger type l lo on ng g i in nt t. One can also add an explicit type conversion to resolve a specific call. For example: f f2 2(s st ta at ti ic c_ _c ca as st t(0 0)) ; However, this is most often simply an ugly stopgap. Soon another similar call will be made and have to be dealt with. Some C++ novices get irritated by the ambiguity errors reported by the compiler. More experi- enced programmers appreciate these error messages as useful indicators of design errors. 7.4.4 Resolution for Multiple Arguments [fct.fct.res] Given the overload resolution rules, one can ensure that the simplest algorithm (function) will be used when the efficiency or precision of computations differs significantly for the types involved. For example: i in nt t p po ow w(i in nt t, i in nt t) ; d do ou ub bl le e p po ow w(d do ou ub bl le e, d do ou ub bl le e) ; c co om mp pl le ex x p po ow w(d do ou ub bl le e, c co om mp pl le ex x) ; c co om mp pl le ex x p po ow w(c co om mp pl le ex x, i in nt t) ; c co om mp pl le ex x p po ow w(c co om mp pl le ex x, d do ou ub bl le e) ; c co om mp pl le ex x p po ow w(c co om mp pl le ex x, c co om mp pl le ex x) ; v vo oi id d k k(c co om mp pl le ex x z z) { i in nt t i i = p po ow w(2 2,2 2) ; / / invoke pow(int,int) d do ou ub bl le e d d = p po ow w(2 2.0 0,2 2.0 0) ; / / invoke pow(double,double) c co om mp pl le ex x z z2 2 = p po ow w(2 2,z z) ; / / invoke pow(double,complex) c co om mp pl le ex x z z3 3 = p po ow w(z z,2 2) ; / / invoke pow(complex,int) c co om mp pl le ex x z z4 4 = p po ow w(z z,z z) ; / / invoke pow(complex,complex) } In the process of choosing among overloaded functions with two or more arguments, a best match is found for each argument using the rules from §7.4. A function that is the best match for one argument and a better than or equal match for all other arguments is called. If no such function exists, the call is rejected as ambiguous. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 7.4.4 Resolution for Multiple Arguments 153 v vo oi id d g g() { d do ou ub bl le e d d = p po ow w(2 2.0 0,2 2) ; / / error: pow(int(2.0),2) or pow(2.0,double(2))? } The call is ambiguous because 2 2.0 0 is the best match for the first argument of p po ow w(d do ou ub bl le e,d do ou ub bl le e) and 2 2 is the best match for the second argument of p po ow w(i in nt t,i in nt t). 7.5 Default Arguments [fct.defarg] A general function often needs more arguments than are necessary to handle simple cases. In par- ticular, functions that construct objects (§10.2.3) often provide several options for flexibility. Con- sider a function for printing an integer. Giving the user an option of what base to print it in seems reasonable, but in most programs integers will be printed as decimal integer values. For example: v vo oi id d p pr ri in nt t(i in nt t v va al lu ue e, i in nt t b ba as se e =1 10 0) ; / / default base is 10 v vo oi id d f f() { p pr ri in nt t(3 31 1) ; p pr ri in nt t(3 31 1,1 10 0) ; p pr ri in nt t(3 31 1,1 16 6) ; p pr ri in nt t(3 31 1,2 2) ; } might produce this output: 3 31 1 3 31 1 1 1f f 1 11 11 11 11 1 The effect of a default argument can alternatively be achieved by overloading: v vo oi id d p pr ri in nt t(i in nt t v va al lu ue e, i in nt t b ba as se e) ; i in nl li in ne e v vo oi id d p pr ri in nt t(i in nt t v va al lu ue e) { p pr ri in nt t(v va al lu ue e,1 10 0) ; } However, overloading makes it less obvious to the reader that the intent is to have a single print function plus a shorthand. A default argument is type checked at the time of the function declaration and evaluated at the time of the call. Default arguments may be provided for trailing arguments only. For example: i in nt t f f(i in nt t, i in nt t =0 0, c ch ha ar r* =0 0) ; / / ok i in nt t g g(i in nt t =0 0, i in nt t =0 0, c ch ha ar r*) ; / / error i in nt t h h(i in nt t =0 0, i in nt t, c ch ha ar r* =0 0) ; / / error Note that the space between the * and the = is significant (*= is an assignment operator; §6.2): i in nt t n na as st ty y(c ch ha ar r*=0 0) ; / / syntax error A default argument can be repeated in a subsequent declaration in the same scope but not changed. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.154 Functions Chapter 7 v vo oi id d f f(i in nt t x x = 7 7) ; v vo oi id d f f(i in nt t = 7 7) ; / / ok v vo oi id d f f(i in nt t = 8 8) ; / / error: different default arguments v vo oi id d g g() { v vo oi id d f f(i in nt t x x = 9 9) ; / / ok: this declaration hides the outer one / / ... } Declaring a name in a nested scope so that the name hides a declaration of the same name in an outer scope is error prone. 7.6 Unspecified Number of Arguments [fct.stdarg] For some functions, it is not possible to specify the number and type of all arguments expected in a call. Such a function is declared by terminating the list of argument declarations with the ellipsis (...), which means ‘‘and maybe some more arguments.’’ For example: i in nt t p pr ri in nt tf f(c co on ns st t c ch ha ar r* ...) ; This specifies that a call of the C standard library function p pr ri in nt tf f() (§21.8) must have at least one argument, a c ch ha ar r*, but may or may not have others. For example: p pr ri in nt tf f("H He el ll lo o, w wo or rl ld d!\ \n n") ; p pr ri in nt tf f("M My y n na am me e i is s %s s %s s\ \n n", f fi ir rs st t_ _n na am me e, s se ec co on nd d_ _n na am me e) ; p pr ri in nt tf f("%d d + %d d = %d d\ \n n",2 2,3 3,5 5) ; Such a function must rely on information not available to the compiler when interpreting its argu- ment list. In the case of p pr ri in nt tf f(), the first argument is a format string containing special character sequences that allow p pr ri in nt tf f() to handle other arguments correctly; %s s means ‘‘expect a c ch ha ar r* argument’’ and %d d means ‘‘expect an i in nt t argument.’’ However, the compiler cannot in general know that, so it cannot ensure that the expected arguments are really there or that an argument is of the proper type. For example, #i in nc cl lu ud de e i in nt t m ma ai in n() { p pr ri in nt tf f("M My y n na am me e i is s %s s %s s\ \n n",2 2) ; } will compile and (at best) cause some strange-looking output (try it!). Clearly, if an argument has not been declared, the compiler does not have the information needed to perform the standard type checking and type conversion for it. In that case, a c ch ha ar r or a s sh ho or rt t is passed as an i in nt t and a f fl lo oa at t is passed as a d do ou ub bl le e. This is not necessarily what the pro- grammer expects. A well-designed program needs at most a few functions for which the argument types are not completely specified. Overloaded functions and functions using default arguments can be used to The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 7.6 Unspecified Number of Arguments 155 take care of type checking in most cases when one would otherwise consider leaving argument types unspecified. Only when both the number of arguments and the type of arguments vary is the ellipsis necessary. The most common use of the ellipsis is to specify an interface to C library func- tions that were defined before C++ provided alternatives: i in nt t f fp pr ri in nt tf f(F FI IL LE E*, c co on ns st t c ch ha ar r* ...) ; / / from i in nt t e ex xe ec cl l(c co on ns st t c ch ha ar r* ...) ; / / from UNIX header A standard set of macros for accessing the unspecified arguments in such functions can be found in . Consider writing an error function that takes one integer argument indicating the severity of the error followed by an arbitrary number of strings. The idea is to compose the error message by passing each word as a separate string argument. The list of string arguments should be terminated by a null pointer to c ch ha ar r: e ex xt te er rn n v vo oi id d e er rr ro or r(i in nt t ...) ; e ex xt te er rn n c ch ha ar r* i it to oa a(i in nt t, c ch ha ar r[]) ; / / see §6.6[17] c co on ns st t c ch ha ar r* N Nu ul ll l_ _c cp p = 0 0; i in nt t m ma ai in n(i in nt t a ar rg gc c, c ch ha ar r* a ar rg gv v[]) { s sw wi it tc ch h (a ar rg gc c) { c ca as se e 1 1: e er rr ro or r(0 0,a ar rg gv v[0 0] ,N Nu ul ll l_ _c cp p) ; b br re ea ak k; c ca as se e 2 2: e er rr ro or r(0 0,a ar rg gv v[0 0] ,a ar rg gv v[1 1] ,N Nu ul ll l_ _c cp p) ; b br re ea ak k; d de ef fa au ul lt t: c ch ha ar r b bu uf ff fe er r[8 8] ; e er rr ro or r(1 1,a ar rg gv v[0 0] , "w wi it th h",i it to oa a(a ar rg gc c-1 1,b bu uf ff fe er r) ,"a ar rg gu um me en nt ts s", N Nu ul ll l_ _c cp p) ; } / / ... } The function i it to oa a() returns the character string representing its integer argument. Note that using the integer 0 0 as the terminator would not have been portable: on some imple- mentations, the integer zero and the null pointer do not have the same representation. This illus- trates the subtleties and extra work that face the programmer once type checking has been sup- pressed using the ellipsis. The error function could be defined like this: v vo oi id d e er rr ro or r(i in nt t s se ev ve er ri it ty y ...) / / "severity" followed by a zero-terminated list of char*s { v va a_ _l li is st t a ap p; v va a_ _s st ta ar rt t(a ap p,s se ev ve er ri it ty y) ; / / arg startup The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.156 Functions Chapter 7 f fo or r (;;) { c ch ha ar r* p p = v va a_ _a ar rg g(a ap p,c ch ha ar r*) ; i if f (p p == 0 0) b br re ea ak k; c ce er rr r << p p << ´ ´; } v va a_ _e en nd d(a ap p) ; / / arg cleanup c ce er rr r << ´\ \n n´; i if f (s se ev ve er ri it ty y) e ex xi it t(s se ev ve er ri it ty y) ; } First, a v va a_ _l li is st t is defined and initialized by a call of v va a_ _s st ta ar rt t(). The macro v va a_ _s st ta ar rt t takes the name of the v va a_ _l li is st t and the name of the last formal argument as arguments. The macro v va a_ _a ar rg g() is used to pick the unnamed arguments in order. In each call, the programmer must supply a type; v va a_ _a ar rg g() assumes that an actual argument of that type has been passed, but it typically has no way of ensuring that. Before returning from a function in which v va a_ _s st ta ar rt t() has been used, v va a_ _e en nd d() must be called. The reason is that v va a_ _s st ta ar rt t() may modify the stack in such a way that a return cannot successfully be done; v va a_ _e en nd d() undoes any such modifications. 7.7 Pointer to Function [fct.pf] There are only two things one can do to a function: call it and take its address. The pointer obtained by taking the address of a function can then be used to call the function. For example: v vo oi id d e er rr ro or r(s st tr ri in ng g s s) { /* ... */ } v vo oi id d (*e ef fc ct t)(s st tr ri in ng g) ; / / pointer to function v vo oi id d f f() { e ef fc ct t = &e er rr ro or r; / / efct points to error e ef fc ct t("e er rr ro or r") ; / / call error through efct } The compiler will discover that e ef fc ct t is a pointer and call the function pointed to. That is, derefer- encing of a pointer to function using * is optional. Similarly, using & to get the address of a func- tion is optional: v vo oi id d (*f f1 1)(s st tr ri in ng g) = &e er rr ro or r; / / ok v vo oi id d (*f f2 2)(s st tr ri in ng g) = e er rr ro or r; / / also ok; same meaning as &error v vo oi id d g g() { f f1 1("V Va as sa a") ; / / ok (*f f1 1)("M Ma ar ry y R Ro os se e") ; / / also ok } Pointers to functions have argument types declared just like the functions themselves. In pointer assignments, the complete function type must match exactly. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 7.7 Pointer to Function 157 v vo oi id d (*p pf f)(s st tr ri in ng g) ; / / pointer to void(string) v vo oi id d f f1 1(s st tr ri in ng g) ; / / void(string) i in nt t f f2 2(s st tr ri in ng g) ; / / int(string) v vo oi id d f f3 3(i in nt t*) ; / / void(int*) v vo oi id d f f() { p pf f = &f f1 1; / / ok p pf f = &f f2 2; / / error: bad return type p pf f = &f f3 3; / / error: bad argument type p pf f("H He er ra a") ; / / ok p pf f(1 1) ; / / error: bad argument type i in nt t i i = p pf f("Z Ze eu us s") ; / / error: void assigned to int } The rules for argument passing are the same for calls directly to a function and for calls to a func- tion through a pointer. It is often convenient to define a name for a pointer-to-function type to avoid using the some- what nonobvious declaration syntax all the time. Here is an example from a UNIX system header: t ty yp pe ed de ef f v vo oi id d (*S SI IG G_ _T TY YP P)(i in nt t) ; / / from t ty yp pe ed de ef f v vo oi id d (*S SI IG G_ _A AR RG G_ _T TY YP P)(i in nt t) ; S SI IG G_ _T TY YP P s si ig gn na al l(i in nt t, S SI IG G_ _A AR RG G_ _T TY YP P) ; An array of pointers to functions is often useful. For example, the menu system for my mouse- based editor is implemented using arrays of pointers to functions to represent operations. The sys- tem cannot be described in detail here, but this is the general idea: t ty yp pe ed de ef f v vo oi id d (*P PF F)() ; P PF F e ed di it t_ _o op ps s[] = { / / edit operations &c cu ut t, &p pa as st te e, &c co op py y, &s se ea ar rc ch h }; P PF F f fi il le e_ _o op ps s[] = { / / file management &o op pe en n, &a ap pp pe en nd d, &c cl lo os se e, &w wr ri it te e }; We can then define and initialize the pointers that control actions selected from a menu associated with the mouse buttons: P PF F* b bu ut tt to on n2 2 = e ed di it t_ _o op ps s; P PF F* b bu ut tt to on n3 3 = f fi il le e_ _o op ps s; In a complete implementation, more information is needed to define each menu item. For example, a string specifying the text to be displayed must be stored somewhere. As the system is used, the meaning of mouse buttons changes frequently with the context. Such changes are performed (partly) by changing the value of the button pointers. When a user selects a menu item, such as item 3 for button 2, the associated operation is executed: b bu ut tt to on n2 2[2 2]() ; / / call button2’s 3rd function The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.158 Functions Chapter 7 One way to gain appreciation of the expressive power of pointers to functions is to try to write such code without them ± and without using their better-behaved cousins, the virtual functions (§12.2.6). A menu can be modified at run-time by inserting new functions into the operator table. It is also easy to construct new menus at run-time. Pointers to functions can be used to provide a simple form of polymorphic routines, that is, rou- tines that can be applied to objects of many different types: t ty yp pe ed de ef f i in nt t (*C CF FT T)(c co on ns st t v vo oi id d*, c co on ns st t v vo oi id d*) ; v vo oi id d s ss so or rt t(v vo oi id d* b ba as se e, s si iz ze e_ _t t n n, s si iz ze e_ _t t s sz z, C CF FT T c cm mp p) /* Sort the "n" elements of vector "base" into increasing order using the comparison function pointed to by "cmp". The elements are of size "sz". Shell sort (Knuth, Vol3, pg84) */ { f fo or r (i in nt t g ga ap p=n n/2 2; 0 0(b ba as se e) ; / / necessary cast c ch ha ar r* p pj j = b b+j j*s sz z; / / &base[j] c ch ha ar r* p pj jg g = b b+(j j+g ga ap p)*s sz z; / / &base[j+gap] i if f (c cm mp p(p pj j,p pj jg g)<0 0) { / / swap base[j] and base[j+gap]: f fo or r (i in nt t k k=0 0; k k(p p)->n na am me e,s st ta at ti ic c_ _c ca as st t(q q)->n na am me e) ; } i in nt t c cm mp p2 2(c co on ns st t v vo oi id d* p p, c co on ns st t v vo oi id d* q q) / / Compare dept numbers { r re et tu ur rn n s st ta at ti ic c_ _c ca as st t(p p)->d de ep pt t - s st ta at ti ic c_ _c ca as st t(q q)->d de ep pt t; } This program sorts and prints: i in nt t m ma ai in n() { c co ou ut t << "H He ea ad ds s i in n a al lp ph ha ab be et ti ic ca al l o or rd de er r:\ \n n"; s ss so or rt t(h he ea ad ds s,6 6,s si iz ze eo of f(U Us se er r) ,c cm mp p1 1) ; p pr ri in nt t_ _i id d(h he ea ad ds s,6 6) ; c co ou ut t << "\ \n n"; c co ou ut t << "H He ea ad ds s i in n o or rd de er r o of f d de ep pa ar rt tm me en nt t n nu um mb be er r:\ \n n"; s ss so or rt t(h he ea ad ds s,6 6,s si iz ze eo of f(U Us se er r) ,c cm mp p2 2) ; p pr ri in nt t_ _i id d(h he ea ad ds s,6 6) ; } You can take the address of an overloaded function by assigning to or initializing a pointer to func- tion. In that case, the type of the target is used to select from the set of overloaded functions. For example: v vo oi id d f f(i in nt t) ; i in nt t f f(c ch ha ar r) ; v vo oi id d (*p pf f1 1)(i in nt t) = &f f; / / void f(int) i in nt t (*p pf f2 2)(c ch ha ar r) = &f f; / / int f(char) v vo oi id d (*p pf f3 3)(c ch ha ar r) = &f f; / / error: no void f(char) The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.160 Functions Chapter 7 A function must be called through a pointer to function with exactly the right argument and return types. There is no implicit conversion of argument or return types when pointers to functions are assigned or initialized. This means that i in nt t c cm mp p3 3(c co on ns st t m my yt ty yp pe e*,c co on ns st t m my yt ty yp pe e*) ; is not a suitable argument for s ss so or rt t(). The reason is that accepting c cm mp p3 3 as an argument to s ss so or rt t() would violate the guarantee that c cm mp p3 3 will be called with arguments of type m my yt ty yp pe e* (see also §9.2.5). 7.8 Macros [fct.macro] Macros are very important in C but have far fewer uses in C++. The first rule about macros is: Don’t use them unless you have to. Almost every macro demonstrates a flaw in the programming language, in the program, or in the programmer. Because they rearrange the program text before the compiler proper sees it, macros are also a major problem for many programming tools. So when you use macros, you should expect inferior service from tools such as debuggers, cross- reference tools, and profilers. If you must use macros, please read the reference manual for your own implementation of the C++ preprocessor carefully and try not to be too clever. Also to warn readers, follow the convention to name macros using lots of capital letters. The syntax of macros is presented in §A.11. A simple macro is defined like this: #d de ef fi in ne e N NA AM ME E r re es st t o of f l li in ne e Where N NA AM ME E is encountered as a token, it is replaced by r re es st t o of f l li in ne e. For example, n na am me ed d = N NA AM ME E will expand into n na am me ed d = r re es st t o of f l li in ne e A macro can also be defined to take arguments. For example: #d de ef fi in ne e M MA AC C(x x,y y) a ar rg gu um me en nt t1 1: x x a ar rg gu um me en nt t2 2: y y When M MA AC C is used, two argument strings must be presented. They will replace x x and y y when M MA AC C() is expanded. For example, e ex xp pa an nd de ed d = M MA AC C(f fo oo o b ba ar r, y yu uk k y yu uk k) will be expanded into e ex xp pa an nd de ed d = a ar rg gu um me en nt t1 1: f fo oo o b ba ar r a ar rg gu um me en nt t2 2: y yu uk k y yu uk k Macro names cannot be overloaded, and the macro preprocessor cannot handle recursive calls: #d de ef fi in ne e P PR RI IN NT T(a a,b b) c co ou ut t<<(a a)<<(b b) #d de ef fi in ne e P PR RI IN NT T(a a,b b,c c) c co ou ut t<<(a a)<<(b b)<<(c c) /* trouble?: redefines, does not overload */ #d de ef fi in ne e F FA AC C(n n) (n n>1 1)?n n*F FA AC C(n n-1 1):1 1 /* trouble: recursive macro */ The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 7.8 Macros 161 Macros manipulate character strings and know little about C++ syntax and nothing about C++ types or scope rules. Only the expanded form of a macro is seen by the compiler, so an error in a macro will be reported when the macro is expanded, not when it is defined. This leads to very obscure error messages. Here are some plausible macros: #d de ef fi in ne e C CA AS SE E b br re ea ak k;c ca as se e #d de ef fi in ne e F FO OR RE EV VE ER R f fo or r(;;) Here are some completely unnecessary macros: #d de ef fi in ne e P PI I 3 3.1 14 41 15 59 93 3 #d de ef fi in ne e B BE EG GI IN N { #d de ef fi in ne e E EN ND D } Here are some dangerous macros: #d de ef fi in ne e S SQ QU UA AR RE E(a a) a a*a a #d de ef fi in ne e I IN NC CR R_ _x xx x (x xx x)++ To see why they are dangerous, try expanding this: i in nt t x xx x = 0 0; / / global counter v vo oi id d f f() { i in nt t x xx x = 0 0; / / local variable i in nt t y y = S SQ QU UA AR RE E(x xx x+2 2) ; / / y=xx+2*xx+2; that is y=xx+(2*xx)+2 I IN NC CR R_ _x xx x; / / increments local xx } If you must use a macro, use the scope resolution operator : : when referring to global names (§4.9.4) and enclose occurrences of a macro argument name in parentheses whenever possible. For example: #d de ef fi in ne e M MI IN N(a a,b b) (((a a)<(b b))?(a a):(b b)) If you must write macros complicated enough to require comments, it is wise to use /* */ com- ments because C preprocessors that do not know about / / comments are sometimes used as part of C++ tools. For example: #d de ef fi in ne e M M2 2(a a) s so om me et th hi in ng g(a a) /* thoughtful comment */ Using macros, you can design your own private language. Even if you prefer this ‘‘enhanced lan- guage’’ to plain C++, it will be incomprehensible to most C++ programmers. Furthermore, the C preprocessor is a very simple macro processor. When you try to do something nontrivial, you are likely to find it either impossible or unnecessarily hard to do. The c co on ns st t, i in nl li in ne e, t te em mp pl la at te e, and n na am me es sp pa ac ce e mechanisms are intended as alternatives to many traditional uses of preprocessor con- structs. For example: c co on ns st t i in nt t a an ns sw we er r = 4 42 2; t te em mp pl la at te e i in nl li in ne e T T m mi in n(T T a a, T T b b) { r re et tu ur rn n (a a. 12. (∗1) How would you choose names for pointer to function types defined using t ty yp pe ed de ef f? 13. (∗2) Look at some programs to get an idea of the diversity of styles of names actually used. How are uppercase letters used? How is the underscore used? When are short names such as i i and x x used? 14. (∗1) What is wrong with these macro definitions? #d de ef fi in ne e P PI I = 3 3.1 14 41 15 59 93 3; #d de ef fi in ne e M MA AX X(a a,b b) a a>b b?a a:b b #d de ef fi in ne e f fa ac c(a a) (a a)*f fa ac c((a a)-1 1) 15. (∗3) Write a macro processor that defines and expands simple macros (like the C preprocessor does). Read from c ci in n and write to c co ou ut t. At first, don’t try to handle macros with arguments. Hint: The desk calculator (§6.1) contains a symbol table and a lexical analyzer that you could modify. 16. (∗2) Implement p pr ri in nt t() from §7.5. 17. (∗2) Add functions such as s sq qr rt t(), l lo og g(), and s si in n() to the desk calculator from §6.1. Hint: Predefine the names and call the functions through an array of pointers to functions. Don’t for- get to check the arguments in a function call. 18. (∗1) Write a factorial function that does not use recursion. See also §11.14[6]. 19. (∗2) Write functions to add one day, one month, and one year to a D Da at te e as defined in §5.9[13]. Write a function that gives the day of the week for a given D Da at te e. Write a function that gives the D Da at te e of the first Monday following a given D Da at te e. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 8 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Namespaces and Exceptions The year is 787! A.D.? ± Monty Python No rule is so general, which admits not some exception. ± Robert Burton Modularity, interfaces, and exceptions Ð namespaces Ð u us si in ng g Ð u us si in ng g n na am me es sp pa ac ce e Ð avoiding name clashes Ð name lookup Ð namespace composition Ð namespace aliases Ð namespaces and C code Ð exceptions Ð t th hr ro ow w and c ca at tc ch h Ð exceptions and pro- gram structure Ð advice Ð exercises. 8.1 Modularization and Interfaces [name.module] Any realistic program consists of a number of separate parts. For example, even the simple ‘‘Hello, world!’’ program involves at least two parts: the user code requests H He el ll lo o, w wo or rl ld d! to be printed, and the I/O system does the printing. Consider the desk calculator example from §6.1. It can be viewed as being composed of five parts: [1] The parser, doing syntax analysis [2] The lexer, composing tokens out of characters [3] The symbol table, holding (string,value) pairs [4] The driver, m ma ai in n() [5] The error handler This can be represented graphically: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.166 Namespaces and Exceptions Chapter 8 driver parser lexer symbol table error handler where an arrow means ‘‘using.’’ To simplify the picture, I have not represented the fact that every part relies on error handling. In fact, the calculator was conceived as three parts, with the driver and error handler added for completeness. When one module uses another, it doesn’t need to know everything about the module used. Ideally, most of the details of a module are unknown to its users. Consequently, we make a distinc- tion between a module and its interface. For example, the parser directly relies on the lexer’s inter- face (only), rather than on the complete lexer. The lexer simply implements the services advertised in its interface. This can be presented graphically like this: driver parser interface lexer interface symbol table interface parser implementation lexer implementation symbol table implementation error handler Dashed lines means ‘‘implements.’’ I consider this to be the real structure of the program, and our job as programmers is to represent this faithfully in code. That done, the code will be simple, effi- cient, comprehensible, maintainable, etc., because it will directly reflect our fundamental design. The following sections show how the logical structure of the desk calculator program can be made clear, and §9.3 shows how the program source text can be physically organized to take advan- tage of it. The calculator is a tiny program, so in ‘‘real life’’ I wouldn’t bother using namespaces and separate compilation (§2.4.1, §9.1) to the extent I do here. It is simply used to present tech- niques useful for larger programs without our drowning in code. In real programs, each ‘‘module’’ represented by a separate namespace will often have hundreds of functions, classes, templates, etc. To demonstrate a variety of techniques and language features, I develop the modularization of The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.1 Modularization and Interfaces 167 the calculator in stages. In ‘‘real life,’’ a program is unlikely to grow through all of these stages. An experienced programmer might pick a design that is ‘‘about right’’ from the start. However, as a program evolves over the years, dramatic structural changes are not uncommon. Error handling permeates the structure of a program. When breaking up a program into mod- ules or (conversely) when composing a program out of modules, we must take care to minimize dependencies between modules caused by error handling. C++ provides exceptions to decouple the detection and reporting of errors from the handling of errors. Therefore, the discussion of how to represent modules as namespaces (§8.2) is followed by a demonstration of how we can use excep- tions to further improve modularity (§8.3). There are many more notions of modularity than the ones discussed in this chapter and the next. For example, we might use concurrently executing and communicating processes to represent important aspects of modularity. Similarly, the use of separate address spaces and the communica- tion of information between address spaces are important topics not discussed here. I consider these notions of modularity largely independent and orthogonal. Interestingly, in each case, sepa- rating a system into modules is easy. The hard problem is to provide safe, convenient, and efficient communication across module boundaries. 8.2 Namespaces [name.namespace] A namespace is a mechanism for expressing logical grouping. That is, if some declarations logi- cally belong together according to some criteria, they can be put in a common namespace to express that fact. For example, the declarations of the parser from the desk calculator (§6.1.1) may be placed in a namespace P Pa ar rs se er r: n na am me es sp pa ac ce e P Pa ar rs se er r { d do ou ub bl le e e ex xp pr r(b bo oo ol l) ; d do ou ub bl le e p pr ri im m(b bo oo ol l g ge et t) { /* ... */ } d do ou ub bl le e t te er rm m(b bo oo ol l g ge et t) { /* ... */ } d do ou ub bl le e e ex xp pr r(b bo oo ol l g ge et t) { /* ... */ } } The function e ex xp pr r() must be declared first and then later defined to break the dependency loop described in §6.1.1. The input part of the desk calculator could be also placed in its own namespace: n na am me es sp pa ac ce e L Le ex xe er r { e en nu um m T To ok ke en n_ _v va al lu ue e { N NA AM ME E, N NU UM MB BE ER R, E EN ND D, P PL LU US S=´+´, M MI IN NU US S=´-´, M MU UL L=´*´, D DI IV V=´/´, P PR RI IN NT T=´;´, A AS SS SI IG GN N=´=´, L LP P=´(´, R RP P=´)´ }; T To ok ke en n_ _v va al lu ue e c cu ur rr r_ _t to ok k; d do ou ub bl le e n nu um mb be er r_ _v va al lu ue e; s st tr ri in ng g s st tr ri in ng g_ _v va al lu ue e; T To ok ke en n_ _v va al lu ue e g ge et t_ _t to ok ke en n() { /* ... */ } } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.168 Namespaces and Exceptions Chapter 8 This use of namespaces makes it reasonably obvious what the lexer and the parser provide to a user. However, had I included the source code for the functions, this structure would have been obscured. If function bodies are included in the declaration of a realistically-sized namespace, you typically have to wade through pages or screenfuls of information to find what services are offered, that is, to find the interface. An alternative to relying on separately specified interfaces is to provide a tool that extracts an interface from a module that includes implementation details. I don’t consider that a good solution. Specifying interfaces is a fundamental design activity (see §23.4.3.4), a module can provide differ- ent interfaces to different users, and often an interface is designed long before the implementation details are made concrete. Here is a version of the P Pa ar rs se er r with the interface separated from the implementation: n na am me es sp pa ac ce e P Pa ar rs se er r { d do ou ub bl le e p pr ri im m(b bo oo ol l) ; d do ou ub bl le e t te er rm m(b bo oo ol l) ; d do ou ub bl le e e ex xp pr r(b bo oo ol l) ; } d do ou ub bl le e P Pa ar rs se er r: :p pr ri im m(b bo oo ol l g ge et t) { /* ... */ } d do ou ub bl le e P Pa ar rs se er r: :t te er rm m(b bo oo ol l g ge et t) { /* ... */ } d do ou ub bl le e P Pa ar rs se er r: :e ex xp pr r(b bo oo ol l g ge et t) { /* ... */ } Note that as a result of separating the implementation of the interface, each function now has exactly one declaration and one definition. Users will see only the interface containing declarations. The implementation ± in this case, the function bodies ± will be placed ‘‘somewhere else’’ where a user need not look. As shown, a member can be declared within a namespace definition and defined later using the namespace-name::member-name notation. Members of a namespace must be introduced using this notation: n na am me es sp pa ac ce e n na am me es sp pa ac ce e-n na am me e { / / declaration and definitions } We cannot declare a new member of a namespace outside a namespace definition using the quali- fier syntax. For example: v vo oi id d P Pa ar rs se er r: :l lo og gi ic ca al l(b bo oo ol l) ; / / error: no logical() in Parser The idea is to make it reasonably easy to find all names in a namespace declaration and also to catch errors such as misspellings and type mismatches. For example: d do ou ub bl le e P Pa ar rs se er r: :t tr re em m(b bo oo ol l) ; / / error: no trem() in Parser d do ou ub bl le e P Pa ar rs se er r: :p pr ri im m(i in nt t) ; / / error: Parser::prim() takes a bool argument A namespace is a scope. Thus, ‘‘namespace’’ is a very fundamental and relatively simple concept. The larger a program is, the more useful namespaces are to express logical separations of its parts. Ordinary local scopes, global scopes, and classes are namespaces (§C.10.3). Ideally, every entity in a program belongs to some recognizable logical unit (‘‘module’’). Therefore, every declaration in a nontrivial program should ideally be in some namespace named to The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.2 Namespaces 169 indicate its logical role in the program. The exception is m ma ai in n(), which must be global in order for the run-time environment to recognize it as special (§8.3.3). 8.2.1 Qualified Names [name.qualified] A namespace is a scope. The usual scope rules hold for namespaces, so if a name is previously declared in the namespace or in an enclosing scope, it can be used without further fuss. A name from another namespace can be used when qualified by the name of its namespace. For example: d do ou ub bl le e P Pa ar rs se er r: :t te er rm m(b bo oo ol l g ge et t) / / note Parser:: qualification { d do ou ub bl le e l le ef ft t = p pr ri im m(g ge et t) ; / / no qualification needed f fo or r (;;) s sw wi it tc ch h (L Le ex xe er r: :c cu ur rr r_ _t to ok k) { / / note Lexer:: qualification c ca as se e L Le ex xe er r: :M MU UL L: / / note Lexer:: qualification l le ef ft t *= p pr ri im m(t tr ru ue e) ; / / no qualification needed / / ... } / / ... } The P Pa ar rs se er r qualifier is necessary to state that this t te er rm m() is the one declared in P Pa ar rs se er r and not some unrelated global function. Because t te er rm m() is a member of P Pa ar rs se er r, it need not use a qualifier for p pr ri im m(). However, had the L Le ex xe er r qualifier not been present, c cu ur rr r_ _t to ok k would have been consid- ered undeclared because the members of namespace L Le ex xe er r are not in scope from within the P Pa ar rs se er r namespace. 8.2.2 Using Declarations [name.using.dcl] When a name is frequently used outside its namespace, it can be a bother to repeatedly qualify it with its namespace name. Consider: d do ou ub bl le e P Pa ar rs se er r: :p pr ri im m(b bo oo ol l g ge et t) / / handle primaries { i if f (g ge et t) L Le ex xe er r: :g ge et t_ _t to ok ke en n() ; s sw wi it tc ch h (L Le ex xe er r: :c cu ur rr r_ _t to ok k) { c ca as se e L Le ex xe er r: :N NU UM MB BE ER R: / / floating-point constant L Le ex xe er r: :g ge et t_ _t to ok ke en n() ; r re et tu ur rn n L Le ex xe er r: :n nu um mb be er r_ _v va al lu ue e; c ca as se e L Le ex xe er r: :N NA AM ME E: { d do ou ub bl le e& v v = t ta ab bl le e[L Le ex xe er r: :s st tr ri in ng g_ _v va al lu ue e] ; i if f (L Le ex xe er r: :g ge et t_ _t to ok ke en n() == L Le ex xe er r: :A AS SS SI IG GN N) v v = e ex xp pr r(t tr ru ue e) ; r re et tu ur rn n v v; } c ca as se e L Le ex xe er r: :M MI IN NU US S: / / unary minus r re et tu ur rn n -p pr ri im m(t tr ru ue e) ; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.170 Namespaces and Exceptions Chapter 8 c ca as se e L Le ex xe er r: :L LP P: { d do ou ub bl le e e e = e ex xp pr r(t tr ru ue e) ; i if f (L Le ex xe er r: :c cu ur rr r_ _t to ok k != L Le ex xe er r: :R RP P) r re et tu ur rn n E Er rr ro or r: :e er rr ro or r(") e ex xp pe ec ct te ed d") ; L Le ex xe er r: :g ge et t_ _t to ok ke en n() ; / / eat ’)’ r re et tu ur rn n e e; } c ca as se e L Le ex xe er r: :E EN ND D: r re et tu ur rn n 1 1; d de ef fa au ul lt t: r re et tu ur rn n E Er rr ro or r: :e er rr ro or r("p pr ri im ma ar ry y e ex xp pe ec ct te ed d") ; } } The repeated qualification L Le ex xe er r is tedious and distracting. This redundancy can be eliminated by a using-declaration to state in one place that the g ge et t_ _t to ok ke en n used in this scope is L Le ex xe er r’s g ge et t_ _t to ok ke en n. For example: d do ou ub bl le e P Pa ar rs se er r: :p pr ri im m(b bo oo ol l g ge et t) / / handle primaries { u us si in ng g L Le ex xe er r: :g ge et t_ _t to ok ke en n; / / use Lexer’s get_token u us si in ng g L Le ex xe er r: :c cu ur rr r_ _t to ok k; / / use Lexer’s curr_tok u us si in ng g E Er rr ro or r: :e er rr ro or r; / / use Error’s error i if f (g ge et t) g ge et t_ _t to ok ke en n() ; s sw wi it tc ch h (c cu ur rr r_ _t to ok k) { c ca as se e L Le ex xe er r: :N NU UM MB BE ER R: / / floating-point constant g ge et t_ _t to ok ke en n() ; r re et tu ur rn n L Le ex xe er r: :n nu um mb be er r_ _v va al lu ue e; c ca as se e L Le ex xe er r: :N NA AM ME E: { d do ou ub bl le e& v v = t ta ab bl le e[L Le ex xe er r: :s st tr ri in ng g_ _v va al lu ue e] ; i if f (g ge et t_ _t to ok ke en n() == L Le ex xe er r: :A AS SS SI IG GN N) v v = e ex xp pr r(t tr ru ue e) ; r re et tu ur rn n v v; } c ca as se e L Le ex xe er r: :M MI IN NU US S: / / unary minus r re et tu ur rn n -p pr ri im m(t tr ru ue e) ; c ca as se e L Le ex xe er r: :L LP P: { d do ou ub bl le e e e = e ex xp pr r(t tr ru ue e) ; i if f (c cu ur rr r_ _t to ok k != L Le ex xe er r: :R RP P) r re et tu ur rn n e er rr ro or r(") e ex xp pe ec ct te ed d") ; g ge et t_ _t to ok ke en n() ; / / eat ’)’ r re et tu ur rn n e e; } c ca as se e L Le ex xe er r: :E EN ND D: r re et tu ur rn n 1 1; d de ef fa au ul lt t: r re et tu ur rn n e er rr ro or r("p pr ri im ma ar ry y e ex xp pe ec ct te ed d") ; } } A using-declaration introduces a local synonym. It is often a good idea to keep local synonyms as local as possible to avoid confusion. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.2.2 Using Declarations 171 However, all parser functions use similar sets of names from other modules. We can therefore place the using-declarations in the P Pa ar rs se er r’s namespace definition: n na am me es sp pa ac ce e P Pa ar rs se er r { d do ou ub bl le e p pr ri im m(b bo oo ol l) ; d do ou ub bl le e t te er rm m(b bo oo ol l) ; d do ou ub bl le e e ex xp pr r(b bo oo ol l) ; u us si in ng g L Le ex xe er r: :g ge et t_ _t to ok ke en n; / / use Lexer’s get_token u us si in ng g L Le ex xe er r: :c cu ur rr r_ _t to ok k; / / use Lexer’s curr_tok u us si in ng g E Er rr ro or r: :e er rr ro or r; / / use Error’s error } This allows us to simplify the P Pa ar rs se er r functions almost to our original version (§6.1.1): d do ou ub bl le e P Pa ar rs se er r: :t te er rm m(b bo oo ol l g ge et t) / / multiply and divide { d do ou ub bl le e l le ef ft t = p pr ri im m(g ge et t) ; f fo or r (;;) s sw wi it tc ch h (c cu ur rr r_ _t to ok k) { c ca as se e L Le ex xe er r: :M MU UL L: l le ef ft t *= p pr ri im m(t tr ru ue e) ; b br re ea ak k; c ca as se e L Le ex xe er r: :D DI IV V: i if f (d do ou ub bl le e d d = p pr ri im m(t tr ru ue e)) { l le ef ft t /= d d; b br re ea ak k; } r re et tu ur rn n e er rr ro or r("d di iv vi id de e b by y 0 0") ; d de ef fa au ul lt t: r re et tu ur rn n l le ef ft t; } } I could have introduced the token names into the P Pa ar rs se er r’s namespace. However, I left them explicitly qualified as a reminder of P Pa ar rs se er r’s dependency on L Le ex xe er r. 8.2.3 Using Directives [name.using.dir] What if our aim were to simplify the P Pa ar rs se er r functions to be exactly our original versions? This would be a reasonable aim for a large program that was being converted to using namespaces from a previous version with less explicit modularity. A using-directive makes names from a namespace available almost as if they had been declared outside their namespace (§8.2.8). For example: n na am me es sp pa ac ce e P Pa ar rs se er r { d do ou ub bl le e p pr ri im m(b bo oo ol l) ; d do ou ub bl le e t te er rm m(b bo oo ol l) ; d do ou ub bl le e e ex xp pr r(b bo oo ol l) ; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.172 Namespaces and Exceptions Chapter 8 u us si in ng g n na am me es sp pa ac ce e L Le ex xe er r; / / make all names from Lexer available u us si in ng g n na am me es sp pa ac ce e E Er rr ro or r; / / make all names from Error available } This allows us to write P Pa ar rs se er r’s functions exactly as we originally did (§6.1.1): d do ou ub bl le e P Pa ar rs se er r: :t te er rm m(b bo oo ol l g ge et t) / / multiply and divide { d do ou ub bl le e l le ef ft t = p pr ri im m(g ge et t) ; f fo or r (;;) s sw wi it tc ch h (c cu ur rr r_ _t to ok k) { / / Lexer’s curr_tok c ca as se e M MU UL L: / / Lexer’s MUL l le ef ft t *= p pr ri im m(t tr ru ue e) ; b br re ea ak k; c ca as se e D DI IV V: / / Lexer’s DIV i if f (d do ou ub bl le e d d = p pr ri im m(t tr ru ue e)) { l le ef ft t /= d d; b br re ea ak k; } r re et tu ur rn n e er rr ro or r("d di iv vi id de e b by y 0 0") ; / / Error’s error d de ef fa au ul lt t: r re et tu ur rn n l le ef ft t; } } Global using-directives are a tool for transition (§8.2.9) and are otherwise best avoided. In a name- space, a u us si in ng g-d di ir re ec ct ti iv ve e is a tool for namespace composition (§8.2.8). In a function (only), a u us si in ng g-d di ir re ec ct ti iv ve e can be safely used as a notational convenience (§8.3.3.1). 8.2.4 Multiple Interfaces [name.multi] It should be clear that the namespace definition we evolved for P Pa ar rs se er r is not the interface that the P Pa ar rs se er r presents to its users. Instead, it is the set of declarations that is needed to write the individ- ual parser functions conveniently. The P Pa ar rs se er r’s interface to its users should be far simpler: n na am me es sp pa ac ce e P Pa ar rs se er r { d do ou ub bl le e e ex xp pr r(b bo oo ol l) ; } Fortunately, the two namespace-definitions for P Pa ar rs se er r can coexist so that each can be used where it is most appropriate. We see the namespace P Pa ar rs se er r used to provide two things: [1] The common environment for the functions implementing the parser [2] The external interface offered by the parser to its users Thus, the driver code, m ma ai in n(), should see only: n na am me es sp pa ac ce e P Pa ar rs se er r { / / interface for users d do ou ub bl le e e ex xp pr r(b bo oo ol l) ; } The functions implementing the parser should see whichever interface we decided on as the best for expressing those functions’ shared environment. That is: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.2.4 Multiple Interfaces 173 n na am me es sp pa ac ce e P Pa ar rs se er r { / / interface for implementers d do ou ub bl le e p pr ri im m(b bo oo ol l) ; d do ou ub bl le e t te er rm m(b bo oo ol l) ; d do ou ub bl le e e ex xp pr r(b bo oo ol l) ; u us si in ng g L Le ex xe er r: :g ge et t_ _t to ok ke en n; / / use Lexer’s get_token u us si in ng g L Le ex xe er r: :c cu ur rr r_ _t to ok k; / / use Lexer’s curr_tok u us si in ng g E Er rr ro or r: :e er rr ro or r; / / use Error’s error } or graphically: P Pa ar rs se er r’ D Dr ri iv ve er r P Pa ar rs se er r . . P Pa ar rs se er r implementation The arrows represent ‘‘relies on the interface provided by’’ relations. P Pa ar rs se er r´ is the small interface offered to users. The name P Pa ar rs se er r´ (Parser prime) is not a C++ identifier. It was chosen deliberately to indicate that this interface doesn’t have a separate name in the program. The lack of a separate name need not lead to confusion because programmers natu- rally invent different and obvious names for the different interfaces and because the physical layout of the program (see §9.3.2) naturally provides separate (file) names. The interface offered to implementers is larger than the interface offered to users. Had this interface been for a realistically-sized module in a real system, it would change more often than the interface seen by users. It is important that the users of a module (in this case, m ma ai in n() using P Pa ar rs se er r) are insulated from such changes. We don’t need to use two separate namespaces to express the two different interfaces, but if we wanted to, we could. Designing interfaces is one of the most fundamental design activities and one in which major benefits can be gained and lost. Consequently, it is worthwhile to consider what we are really trying to achieve and to discuss a number of alternatives. Please keep in mind that the solution presented is the simplest of those we consider, and often the best. Its main weaknesses are that the two interfaces don’t have separate names and that the compiler doesn’t necessarily have sufficient information to check the consistency of the two defini- tions of the namespace. However, even though the compiler doesn’t always get the opportunity to check the consistency, it usually does. Furthermore, the linker catches most errors missed by the compiler. The solution presented here is the one I use for the discussion of physical modularity (§9.3) and the one I recommend in the absence of further logical constraints (see also §8.2.7). 8.2.4.1 Interface Design Alternatives [name.alternatives] The purpose of interfaces is to minimize dependencies between different parts of a program. Mini- mal interfaces lead to systems that are easier to understand, have better data hiding properties, are easier to modify, and compile faster. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.174 Namespaces and Exceptions Chapter 8 When dependencies are considered, it is important to remember that compilers and program- mers tend to take a somewhat simple-minded approach to them: ‘‘If a definition is in scope at point X, then anything written at point X depends on anything stated in that definition.’’ Typically, things are not really that bad because most definitions are irrelevant to most code. Given the defi- nitions we have used, consider: n na am me es sp pa ac ce e P Pa ar rs se er r { / / interface for implementers / / ... d do ou ub bl le e e ex xp pr r(b bo oo ol l) ; / / ... } i in nt t m ma ai in n() { / / ... P Pa ar rs se er r: :e ex xp pr r(f fa al ls se e) ; / / ... } The function m ma ai in n() depends on P Pa ar rs se er r: :e ex xp pr r() only, but it takes time, brain power, computa- tion, etc., to figure that out. Consequently, for realistically-sized programs people and compilation systems often play it safe and assume that where there might be a dependency, there is one. This is typically a perfectly reasonable approach. Thus, our aim is to express our program so that the set of potential dependencies is reduced to the set of actual dependencies. First, we try the obvious: define a user interface to the parser in terms of the implementer inter- face we already have: n na am me es sp pa ac ce e P Pa ar rs se er r { / / interface for implementers / / ... d do ou ub bl le e e ex xp pr r(b bo oo ol l) ; / / ... } n na am me es sp pa ac ce e P Pa ar rs se er r_ _i in nt te er rf fa ac ce e { / / interface for users u us si in ng g P Pa ar rs se er r: :e ex xp pr r; } Clearly, users of P Pa ar rs se er r_ _i in nt te er rf fa ac ce e depend only, and indirectly, on P Pa ar rs se er r: :e ex xp pr r(). However, a crude look at the dependency graph gives us this: P Pa ar rs se er r_ _i in nt te er rf fa ac ce e . . D Dr ri iv ve er r P Pa ar rs se er r . . P Pa ar rs se er r implementation The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.2.4.1 Interface Design Alternatives 175 Now the d dr ri iv ve er r appears vulnerable to any change in the P Pa ar rs se er r interface from which it was sup- posed to be insulated. Even this appearance of a dependency is undesirable, so we explicitly restrict P Pa ar rs se er r_ _i in nt te er rf fa ac ce e’s dependency on P Pa ar rs se er r by having only the relevant part of the imple- menter interface to parser (that was called P Pa ar rs se er r´ earlier) in scope where we define P Pa ar rs se er r_ _i in nt te er rf fa ac ce e: n na am me es sp pa ac ce e P Pa ar rs se er r { / / interface for users d do ou ub bl le e e ex xp pr r(b bo oo ol l) ; } n na am me es sp pa ac ce e P Pa ar rs se er r_ _i in nt te er rf fa ac ce e { / / separately named interface for users u us si in ng g P Pa ar rs se er r: :e ex xp pr r; } or graphically: P Pa ar rs se er r’ P Pa ar rs se er r P Pa ar rs se er r_ _i in nt te er rf fa ac ce e . . D Dr ri iv ve er r . . P Pa ar rs se er r implementation To ensure the consistency of P Pa ar rs se er r and P Pa ar rs se er r´, we again rely on the compilation system as a whole, rather than on just the compiler working on a single compilation unit. This solution differs from the one in §8.2.4 only by the extra namespace P Pa ar rs se er r_ _i in nt te er rf fa ac ce e. If we wanted to, we could give P Pa ar rs se er r_ _i in nt te er rf fa ac ce e a concrete representation by giving it its own e ex xp pr r() function: n na am me es sp pa ac ce e P Pa ar rs se er r_ _i in nt te er rf fa ac ce e { d do ou ub bl le e e ex xp pr r(b bo oo ol l) ; } Now P Pa ar rs se er r need not be in scope in order to define P Pa ar rs se er r_ _i in nt te er rf fa ac ce e. It needs to be in scope only where P Pa ar rs se er r_ _i in nt te er rf fa ac ce e: :e ex xp pr r() is defined: d do ou ub bl le e P Pa ar rs se er r_ _i in nt te er rf fa ac ce e: :e ex xp pr r(b bo oo ol l g ge et t) { r re et tu ur rn n P Pa ar rs se er r: :e ex xp pr r(g ge et t) ; } This last variant can be represented graphically like this: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.176 Namespaces and Exceptions Chapter 8 P Pa ar rs se er r_ _i in nt te er rf fa ac ce e P Pa ar rs se er r . . D Dr ri iv ve er r . . P Pa ar rs se er r implementation P Pa ar rs se er r_ _i in nt te er rf fa ac ce e implementation Now all dependencies are minimized. Everything is concrete and properly named. However, for most problems I face, this solution is also massive overkill. 8.2.5 Avoiding Name Clashes [name.clash] Namespaces are intended to express logical structure. The simplest such structure is the distinction between code written by one person vs. code written by someone else. This simple distinction can be of great practical importance. When we use only a single global scope, it is unnecessarily difficult to compose a program out of separate parts. The problem is that the supposedly-separate parts each define the same names. When combined into the same program, these names clash. Consider: / / my.h: c ch ha ar r f f(c ch ha ar r) ; i in nt t f f(i in nt t) ; c cl la as ss s S St tr ri in ng g { /* ... */ }; / / your.h: c ch ha ar r f f(c ch ha ar r) ; d do ou ub bl le e f f(d do ou ub bl le e) ; c cl la as ss s S St tr ri in ng g { /* ... */ }; Given these definitions, a third party cannot easily use both m my y.h h and y yo ou ur r.h h. The obvious solu- tion is to wrap each set of declarations in its own namespace: n na am me es sp pa ac ce e M My y { c ch ha ar r f f(c ch ha ar r) ; i in nt t f f(i in nt t) ; c cl la as ss s S St tr ri in ng g { /* ... */ }; } n na am me es sp pa ac ce e Y Yo ou ur r { c ch ha ar r f f(c ch ha ar r) ; d do ou ub bl le e f f(d do ou ub bl le e) ; c cl la as ss s S St tr ri in ng g { /* ... */ }; } Now we can use declarations from M My y and Y Yo ou ur r through explicit qualification (§8.2.1), using- declarations (§8.2.2), or using-directives (§8.2.3). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.2.5.1 Unnamed Namespaces 177 8.2.5.1 Unnamed Namespaces [name.unnamed] It is often useful to wrap a set of declarations in a namespace simply to protect against the possibil- ity of name clashes. That is, the aim is to preserve locality of code rather than to present an inter- face to users. For example: #i in nc cl lu ud de e "h he ea ad de er r.h h" n na am me es sp pa ac ce e M Mi in ne e { i in nt t a a; v vo oi id d f f() { /* ... */ } i in nt t g g() { /* ... */ } } Since we don’t want the name M Mi in ne e to be known outside a local context, it simply becomes a bother to invent a redundant global name that might accidentally clash with someone else’s names. In that case, we can simply leave the namespace without a name: #i in nc cl lu ud de e "h he ea ad de er r.h h" n na am me es sp pa ac ce e { i in nt t a a; v vo oi id d f f() { /* ... */ } i in nt t g g() { /* ... */ } } Clearly, there has to be some way of accessing members of an unnamed namespace from the out- side. Consequently, an unnamed namespace has an implied using-directive. The previous declara- tion is equivalent to n na am me es sp pa ac ce e $$$ { i in nt t a a; v vo oi id d f f() { /* ... */ } i in nt t g g() { /* ... */ } } u us si in ng g n na am me es sp pa ac ce e $$$; where $$$ is some name unique to the scope in which the namespace is defined. In particular, unnamed namespaces in different translation units are different. As desired, there is no way of naming a member of an unnamed namespace from another translation unit. 8.2.6 Name Lookup [name.koenig] A function taking an argument of type T T is more often than not defined in the same namespace as T T. Consequently, if a function isn’t found in the context of its use, we look in the namespaces of its arguments. For example: n na am me es sp pa ac ce e C Ch hr ro on no o { c cl la as ss s D Da at te e { /* ... */ }; b bo oo ol l o op pe er ra at to or r==(c co on ns st t D Da at te e&, c co on ns st t s st td d: :s st tr ri in ng g&) ; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.178 Namespaces and Exceptions Chapter 8 s st td d: :s st tr ri in ng g f fo or rm ma at t(c co on ns st t D Da at te e&) ; / / make string representation / / ... } v vo oi id d f f(C Ch hr ro on no o: :D Da at te e d d, i in nt t i i) { s st td d: :s st tr ri in ng g s s = f fo or rm ma at t(d d) ; / / Chrono::format() s st td d: :s st tr ri in ng g t t = f fo or rm ma at t(i i) ; / / error: no format() in scope } This lookup rule saves the programmer a lot of typing compared to using explicit qualification, yet it doesn’t pollute the namespace the way a using-directive (§8.2.3) can. It is especially useful for operator operands (§11.2.4) and template arguments (§C.13.8.4), where explicit qualification can be quite cumbersome. Note that the namespace itself needs to be in scope and the function must be declared before it can be found and used. Naturally, a function can take arguments from more than one namespace. For example: v vo oi id d f f(C Ch hr ro on no o: :D Da at te e d d, s st td d: :s st tr ri in ng g s s) { i if f (d d == s s) { / / ... } e el ls se e i if f (d d == "A Au ug gu us st t 4 4, 1 19 91 14 4") { / / ... } } In such cases, we look for the function in the scope of the call (as ever) and in the namespaces of every argument (including each argument’s class and base classes) and do the usual overload reso- lution (§7.4) of all functions we find. In particular, for the call d d==s s, we look for o op pe er ra at to or r== in the scope surrounding f f(), in the s st td d namespace (where == is defined for s st tr ri in ng g), and in the C Ch hr ro on no o namespace. There is a s st td d: :o op pe er ra at to or r==(), but it doesn’t take a D Da at te e argument, so we use C Ch hr ro on no o: :o op pe er ra at to or r==(), which does. See also §11.2.4. When a class member invokes a function, other members of the same class and its base classes are preferred over functions potentially found based on the argument types (§11.2.4). 8.2.7 Namespace Aliases [name.alias] If users give their namespaces short names, the names of different namespaces will clash: n na am me es sp pa ac ce e A A { / / short name, will clash (eventually) / / ... } A A: :S St tr ri in ng g s s1 1 = "G Gr ri ie eg g"; A A: :S St tr ri in ng g s s2 2 = "N Ni ie el ls se en n"; However, long namespace names can be impractical in real code: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.2.7 Namespace Aliases 179 n na am me es sp pa ac ce e A Am me er ri ic ca an n_ _T Te el le ep ph ho on ne e_ _a an nd d_ _T Te el le eg gr ra ap ph h { / / too long / / ... } A Am me er ri ic ca an n_ _T Te el le ep ph ho on ne e_ _a an nd d_ _T Te el le eg gr ra ap ph h: :S St tr ri in ng g s s3 3 = "G Gr ri ie eg g"; A Am me er ri ic ca an n_ _T Te el le ep ph ho on ne e_ _a an nd d_ _T Te el le eg gr ra ap ph h: :S St tr ri in ng g s s4 4 = "N Ni ie el ls se en n"; This dilemma can be resolved by providing a short alias for a longer namespace name: / / use namespace alias to shorten names: n na am me es sp pa ac ce e A AT TT T = A Am me er ri ic ca an n_ _T Te el le ep ph ho on ne e_ _a an nd d_ _T Te el le eg gr ra ap ph h; A AT TT T: :S St tr ri in ng g s s3 3 = "G Gr ri ie eg g"; A AT TT T: :S St tr ri in ng g s s4 4 = "N Ni ie el ls se en n"; Namespace aliases also allow a user to refer to ‘‘the library’’ and have a single declaration defining what library that really is. For example: n na am me es sp pa ac ce e L Li ib b = F Fo ou un nd da at ti io on n_ _l li ib br ra ar ry y_ _v v2 2r r1 11 1; / / ... L Li ib b: :s se et t s s; L Li ib b: :S St tr ri in ng g s s5 5 = "S Si ib be el li iu us s"; This can immensely simplify the task of replacing one version of a library with another. By using L Li ib b rather than F Fo ou un nd da at ti io on n_ _l li ib br ra ar ry y_ _v v2 2r r1 11 1 directly, you can update to version ‘‘v3r02’’ by chang- ing the initialization of the alias L Li ib b and recompiling. The recompile will catch source level incom- patibilities. On the other hand, overuse of aliases (of any kind) can lead to confusion. 8.2.8 Namespace Composition [name.compose] Often, we want to compose an interface out of existing interfaces. For example: n na am me es sp pa ac ce e H Hi is s_ _s st tr ri in ng g { c cl la as ss s S St tr ri in ng g { /* ... */ }; S St tr ri in ng g o op pe er ra at to or r+(c co on ns st t S St tr ri in ng g&, c co on ns st t S St tr ri in ng g&) ; S St tr ri in ng g o op pe er ra at to or r+(c co on ns st t S St tr ri in ng g&, c co on ns st t c ch ha ar r*) ; v vo oi id d f fi il ll l(c ch ha ar r) ; / / ... } n na am me es sp pa ac ce e H He er r_ _v ve ec ct to or r { t te em mp pl la at te e c cl la as ss s V Ve ec ct to or r { /* ... */ }; / / ... } n na am me es sp pa ac ce e M My y_ _l li ib b { u us si in ng g n na am me es sp pa ac ce e H Hi is s_ _s st tr ri in ng g; u us si in ng g n na am me es sp pa ac ce e H He er r_ _v ve ec ct to or r; v vo oi id d m my y_ _f fc ct t(S St tr ri in ng g&) ; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.180 Namespaces and Exceptions Chapter 8 Given this, we can now write the program in terms of M My y_ _l li ib b: v vo oi id d f f() { M My y_ _l li ib b: :S St tr ri in ng g s s = "B By yr ro on n"; / / finds My_lib::His_string::String / / ... } u us si in ng g n na am me es sp pa ac ce e M My y_ _l li ib b; v vo oi id d g g(V Ve ec ct to or r& v vs s) { / / ... m my y_ _f fc ct t(v vs s[5 5]) ; / / ... } If an explicitly qualified name (such as M My y_ _l li ib b: :S St tr ri in ng g) isn’t declared in the namespace men- tioned, the compiler looks in namespaces mentioned in using-directives (such as H Hi is s_ _s st tr ri in ng g). Only if we need to define something, do we need to know the real namespace of an entity: v vo oi id d M My y_ _l li ib b: :f fi il ll l() / / error: no fill() declared in My_lib { / / ... } v vo oi id d H Hi is s_ _s st tr ri in ng g: :f fi il ll l() / / ok: fill() declared in His_string { / / ... } v vo oi id d M My y_ _l li ib b: :m my y_ _f fc ct t(M My y_ _l li ib b: :V Ve ec ct to or r& v v) / / ok { / / ... } Ideally, a namespace should [1] express a logically coherent set of features, [2] not give users access to unrelated features, and [3] not impose a significant notational burden on users. The composition techniques presented here and in the following subsections ± together with the #i in nc cl lu ud de e mechanism (§9.2.1) ± provide strong support for this. 8.2.8.1 Selection [name.select] Occasionally, we want access to only a few names from a namespace. We could do that by writing a namespace declaration containing only those names we want. For example, we could declare a version of H Hi is s_ _s st tr ri in ng g that provided the S St tr ri in ng g itself and the concatenation operator only: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.2.8.1 Selection 181 n na am me es sp pa ac ce e H Hi is s_ _s st tr ri in ng g { / / part of His_string only c cl la as ss s S St tr ri in ng g { /* ... */ }; S St tr ri in ng g o op pe er ra at to or r+(c co on ns st t S St tr ri in ng g&, c co on ns st t S St tr ri in ng g&) ; S St tr ri in ng g o op pe er ra at to or r+(c co on ns st t S St tr ri in ng g&, c co on ns st t c ch ha ar r*) ; } However, unless I am the designer or maintainer of H Hi is s_ _s st tr ri in ng g, this can easily get messy. A change to the ‘‘real’’ definition of H Hi is s_ _s st tr ri in ng g will not be reflected in this declaration. Selection of features from a namespace is more explicitly made with using-declarations: n na am me es sp pa ac ce e M My y_ _s st tr ri in ng g { u us si in ng g H Hi is s_ _s st tr ri in ng g: :S St tr ri in ng g; u us si in ng g H Hi is s_ _s st tr ri in ng g: :o op pe er ra at to or r+; / / use any + from His_string } A using-declaration brings every declaration with a given name into scope. In particular, a single using-declaration can bring in every variant of an overloaded function. In this way, if the maintainer of H Hi is s_ _s st tr ri in ng g adds a member function to S St tr ri in ng g or an overloaded version of the concatenation operator, that change will automatically become available to users of M My y_ _s st tr ri in ng g. Conversely, if a feature is removed from H Hi is s_ _s st tr ri in ng g or has its interface changed, affected uses of M My y_ _s st tr ri in ng g will be detected by the compiler (see also §15.2.2). 8.2.8.2 Composition and Selection [name.comp] Combining composition (by using-directives) with selection (by using-declarations) yields the flexibility needed for most real-world examples. With these mechanisms, we can provide access to a variety of facilities in such a way that we resolve name clashes and ambiguities arising from their composition. For example: n na am me es sp pa ac ce e H Hi is s_ _l li ib b { c cl la as ss s S St tr ri in ng g { /* ... */ }; t te em mp pl la at te e c cl la as ss s V Ve ec ct to or r { /* ... */ }; / / ... } n na am me es sp pa ac ce e H He er r_ _l li ib b { t te em mp pl la at te e c cl la as ss s V Ve ec ct to or r { /* ... */ }; c cl la as ss s S St tr ri in ng g { /* ... */ }; / / ... } n na am me es sp pa ac ce e M My y_ _l li ib b { u us si in ng g n na am me es sp pa ac ce e H Hi is s_ _l li ib b; / / everything from His_lib u us si in ng g n na am me es sp pa ac ce e H He er r_ _l li ib b; / / everything from Her_lib u us si in ng g H Hi is s_ _l li ib b: :S St tr ri in ng g; / / resolve potential clash in favor of His_lib u us si in ng g H He er r_ _l li ib b: :V Ve ec ct to or r; / / resolve potential clash in favor of Her_lib t te em mp pl la at te e c cl la as ss s L Li is st t { /* ... */ }; / / additional stuff / / ... } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.182 Namespaces and Exceptions Chapter 8 When looking into a namespace, names explicitly declared there (including names declared by using-declarations) take priority over names made accessible in another scope by a using-directive (see also §C.10.1). Consequently, a user of M My y_ _l li ib b will see the name clashes for S St tr ri in ng g and V Ve ec ct to or r resolved in favor of H Hi is s_ _l li ib b: :S St tr ri in ng g and H He er r_ _l li ib b: :V Ve ec ct to or r. Also, M My y_ _l li ib b: :L Li is st t will be used by default independently of whether H Hi is s_ _l li ib b or H He er r_ _l li ib b are providing a L Li is st t. Usually, I prefer to leave a name unchanged when including it into a new namespace. In that way, I don’t have to remember two different names for the same entity. However, sometimes a new name is needed or simply nice to have. For example: n na am me es sp pa ac ce e L Li ib b2 2 { u us si in ng g n na am me es sp pa ac ce e H Hi is s_ _l li ib b; / / everything from His_lib u us si in ng g n na am me es sp pa ac ce e H He er r_ _l li ib b; / / everything from Her_lib u us si in ng g H Hi is s_ _l li ib b: :S St tr ri in ng g; / / resolve potential clash in favor of His_lib u us si in ng g H He er r_ _l li ib b: :V Ve ec ct to or r; / / resolve potential clash in favor of Her_lib t ty yp pe ed de ef f H He er r_ _l li ib b: :S St tr ri in ng g H He er r_ _s st tr ri in ng g; / / rename t te em mp pl la at te e c cl la as ss s H Hi is s_ _v ve ec c / / ‘‘rename’’ : p pu ub bl li ic c H Hi is s_ _l li ib b: :V Ve ec ct to or r { /* ... */ }; t te em mp pl la at te e c cl la as ss s L Li is st t { /* ... */ }; / / additional stuff / / ... } There is no specific language mechanism for renaming. Instead, the general mechanisms for defin- ing new entities are used. 8.2.9 Namespaces and Old Code [name.get] Millions of lines of C and C++ code rely on global names and existing libraries. How can we use namespaces to alleviate problems in such code? Redesigning existing code isn’t always a viable option. Fortunately, it is possible to use C libraries as if they were defined in a namespace. How- ever, this cannot be done for libraries written in C++ (§9.2.4). On the other hand, namespaces are designed so that they can be introduced with minimal disruption into an older C++ program. 8.2.9.1 Namespaces and C [name.c] Consider the canonical first C program: #i in nc cl lu ud de e i in nt t m ma ai in n() { p pr ri in nt tf f("H He el ll lo o, w wo or rl ld d!\ \n n") ; } Breaking this program wouldn’t be a good idea. Making standard libraries special cases isn’t a good idea either. Consequently, the language rules for namespaces are designed to make it rela- tively easy to take a program written without namespaces and turn it into a more explicitly struc- tured one using namespaces. In fact, the calculator program (§6.1) is an example of this. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.2.9.1 Namespaces and C 183 The using-directive is the key to achieving this. For example, the declarations of the standard C I/O facilities from the C header s st td di io o.h h are wrapped in a namespace like this: / / stdio.h: n na am me es sp pa ac ce e s st td d { / / ... i in nt t p pr ri in nt tf f(c co on ns st t c ch ha ar r* ... ) ; / / ... } u us si in ng g n na am me es sp pa ac ce e s st td d; This achieves backwards compatibility. Also, a new header file c cs st td di io o is defined for people who don’t want the names implicitly available: / / cstdio: n na am me es sp pa ac ce e s st td d { / / ... i in nt t p pr ri in nt tf f(c co on ns st t c ch ha ar r* ... ) ; / / ... } C++ standard library implementers who worry about replication of declarations will, of course, define s st td di io o.h h by including c cs st td di io o: / / stdio.h: #i in nc cl lu ud de e u us si in ng g n na am me es sp pa ac ce e s st td d; I consider nonlocal using-directives primarily a transition tool. Most code referring to names from other namespaces can be expressed more clearly with explicit qualification and using-declarations. The relationship between namespaces and linkage is described in §9.2.4. 8.2.9.2 Namespaces and Overloading [name.over] Overloading (§7.4) works across namespaces. This is essential to allow us to migrate existing libraries to use namespaces with minimal source code changes. For example: / / old A.h: v vo oi id d f f(i in nt t) ; / / ... / / old B.h: v vo oi id d f f(c ch ha ar r) ; / / ... / / old user.c: #i in nc cl lu ud de e "A A.h h" #i in nc cl lu ud de e "B B.h h" The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.184 Namespaces and Exceptions Chapter 8 v vo oi id d g g() { f f(´a a´) ; / / calls the f() from B.h } This program can be upgraded to a version using namespaces without changing the actual code: / / new A.h: n na am me es sp pa ac ce e A A { v vo oi id d f f(i in nt t) ; / / ... } / / new B.h: n na am me es sp pa ac ce e B B { v vo oi id d f f(c ch ha ar r) ; / / ... } / / new user.c: #i in nc cl lu ud de e "A A.h h" #i in nc cl lu ud de e "B B.h h" u us si in ng g n na am me es sp pa ac ce e A A; u us si in ng g n na am me es sp pa ac ce e B B; v vo oi id d g g() { f f(´a a´) ; / / calls the f() from B.h } Had we wanted to keep u us se er r.c c completely unchanged, we would have placed the using-directives in the header files. 8.2.9.3 Namespaces Are Open [name.open] A namespace is open; that is, you can add names to it from several namespace declarations. For example: n na am me es sp pa ac ce e A A { i in nt t f f() ; / / now A has member f() } n na am me es sp pa ac ce e A A { i in nt t g g() ; / / now A has two members, f() and g() } In this way, we can support large program fragments within a single namespace the way an older library or application lives within the single global namespace. To do this, we must distribute the namespace definition over several header and source code files. As shown by the calculator exam- ple (§8.2.4), the openness of namespaces allows us to present different interfaces to different kinds The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.2.9.3 Namespaces Are Open 185 of users by presenting different parts of a namespace. This openness is also an aid to transition. For example, / / my header: v vo oi id d f f() ; / / my function / / ... #i in nc cl lu ud de e i in nt t g g() ; / / my function / / ... can be rewritten without reordering of the declarations: / / my header: n na am me es sp pa ac ce e M Mi in ne e { v vo oi id d f f() ; / / my function / / ... } #i in nc cl lu ud de e n na am me es sp pa ac ce e M Mi in ne e { i in nt t g g() ; / / my function / / ... } When writing new code, I prefer to use many smaller namespaces (see §8.2.8) rather than putting really major pieces of code into a single namespace. However, that is often impractical when con- verting major pieces of software to use namespaces. When defining a previously declared member of a namespace, it is safer to use the M Mi in ne e: : syn- tax than to re-open M Mi in ne e. For example: v vo oi id d M Mi in ne e: :f ff f() / / error: no ff() declared in Mine { / / ... } A compiler catches this error. However, because new functions can be defined within a namespace, a compiler cannot catch the equivalent error in a re-opened namespace: n na am me es sp pa ac ce e M Mi in ne e { / / re-opening Mine to define functions v vo oi id d f ff f() / / oops! no ff() declared in Mine; ff() is added to Mine by this definition { / / ... } / / ... } The compiler has no way of knowing that you didn’t want that new f ff f(). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.186 Namespaces and Exceptions Chapter 8 8.3 Exceptions [name.except] When a program is composed of separate modules, and especially when those modules come from separately developed libraries, error handling needs to be separated into two distinct parts: [1] The reporting of error conditions that cannot be resolved locally [2] The handling of errors detected elsewhere The author of a library can detect run-time errors but does not in general have any idea what to do about them. The user of a library may know how to cope with such errors but cannot detect them ± or else they would be handled in the user’s code and not left for the library to find. In the calculator example, we bypassed this problem by designing the program as a whole. By doing that, we could fit error handling into our overall framework. However, when we separate the logical parts of the calculator into separate namespaces, we see that every namespace depends on namespace E Er rr ro or r (§8.2.2) and that the error handling in E Er rr ro or r relies on every module behaving appropriately after an error. Let’s assume that we don’t have the freedom to design the calculator as a whole and don’t want the tight coupling between E Er rr ro or r and all other modules. Instead, assume that the parser, etc., are written without knowledge of how a driver might like to handle errors. Even though e er rr ro or r() was very simple, it embodied a strategy for error handling: n na am me es sp pa ac ce e E Er rr ro or r { i in nt t n no o_ _o of f_ _e er rr ro or rs s; d do ou ub bl le e e er rr ro or r(c co on ns st t c ch ha ar r* s s) { s st td d: :c ce er rr r << "e er rr ro or r: " << s s << ´\ \n n´; n no o_ _o of f_ _e er rr ro or rs s++; r re et tu ur rn n 1 1; } } The e er rr ro or r() function writes out an error message, supplies a default value that allows its caller to continue a computation, and keeps track of a simple error state. Importantly, every part of the pro- gram knows that e er rr ro or r() exists, how to call it, and what to expect from it. For a program com- posed of separately-developed libraries, that would be too much to assume. Exceptions are C++’s means of separating error reporting from error handling. In this section, exceptions are briefly described in the context of their use in the calculator example. Chapter 14 provides a more extensive discussion of exceptions and their uses. 8.3.1 Throw and Catch [name.throw] The notion of an exception is provided to help deal with error reporting. For example: s st tr ru uc ct t R Ra an ng ge e_ _e er rr ro or r { i in nt t i i; R Ra an ng ge e_ _e er rr ro or r(i in nt t i ii i) { i i = i ii i; } / / constructor (§2.5.2, §10.2.3) }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.3.1 Throw and Catch 187 c ch ha ar r t to o_ _c ch ha ar r(i in nt t i i) { i if f (i i: :m mi in n() || n nu um me er ri ic c_ _l li im mi it ts s: :m ma ax x()> s st tr ri in ng g_ _v va al lu ue e; r re et tu ur rn n c cu ur rr r_ _t to ok k=N NA AM ME E; } t th hr ro ow w E Er rr ro or r: :S Sy yn nt ta ax x_ _e er rr ro or r("b ba ad d t to ok ke en n") ; } } d do ou ub bl le e P Pa ar rs se er r: :p pr ri im m(b bo oo ol l g ge et t) / / handle primaries { / / ... c ca as se e L Le ex xe er r: :L LP P: { d do ou ub bl le e e e = e ex xp pr r(t tr ru ue e) ; i if f (c cu ur rr r_ _t to ok k != L Le ex xe er r: :R RP P) t th hr ro ow w E Er rr ro or r: :S Sy yn nt ta ax x_ _e er rr ro or r("‘)´ e ex xp pe ec ct te ed d") ; g ge et t_ _t to ok ke en n() ; / / eat ’)’ r re et tu ur rn n e e; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.3.3 Exceptions in the Calculator 191 c ca as se e L Le ex xe er r: :E EN ND D: r re et tu ur rn n 1 1; d de ef fa au ul lt t: t th hr ro ow w E Er rr ro or r: :S Sy yn nt ta ax x_ _e er rr ro or r("p pr ri im ma ar ry y e ex xp pe ec ct te ed d") ; } } When a syntax error is detected, t th hr ro ow w is used to transfer control to a handler defined in some (direct or indirect) caller. The t th hr ro ow w operator also passes a value to the handler. For example, t th hr ro ow w S Sy yn nt ta ax x_ _e er rr ro or r("p pr ri im ma ar ry y e ex xp pe ec ct te ed d") ; passes a S Sy yn nt ta ax x_ _e er rr ro or r object containing a pointer to the string p pr ri im ma ar ry y e ex xp pe ec ct te ed d to the handler. Reporting a divide-by-zero error doesn’t require any data to be passed along: d do ou ub bl le e P Pa ar rs se er r: :t te er rm m(b bo oo ol l g ge et t) / / multiply and divide { / / ... c ca as se e L Le ex xe er r: :D DI IV V: i if f (d do ou ub bl le e d d = p pr ri im m(t tr ru ue e)) { l le ef ft t /= d d; b br re ea ak k; } t th hr ro ow w E Er rr ro or r: :Z Ze er ro o_ _d di iv vi id de e() ; / / ... } The driver can now be defined to handle Z Ze er ro o_ _d di iv vi id de e and S Sy yn nt ta ax x_ _e er rr ro or r exceptions. For example: i in nt t m ma ai in n(i in nt t a ar rg gc c, c ch ha ar r* a ar rg gv v[]) { / / ... w wh hi il le e (*i in np pu ut t) { t tr ry y { L Le ex xe er r: :g ge et t_ _t to ok ke en n() ; i if f (L Le ex xe er r: :c cu ur rr r_ _t to ok k == L Le ex xe er r: :E EN ND D) b br re ea ak k; i if f (L Le ex xe er r: :c cu ur rr r_ _t to ok k == L Le ex xe er r: :P PR RI IN NT T) c co on nt ti in nu ue e; c co ou ut t << P Pa ar rs se er r: :e ex xp pr r(f fa al ls se e) << ´\ \n n´; } c ca at tc ch h(E Er rr ro or r: :Z Ze er ro o_ _d di iv vi id de e) { c ce er rr r << "a at tt te em mp pt t t to o d di iv vi id de e b by y z ze er ro o\ \n n"; s sk ki ip p() ; } c ca at tc ch h(E Er rr ro or r: :S Sy yn nt ta ax x_ _e er rr ro or r e e) { c ce er rr r << "s sy yn nt ta ax x e er rr ro or r:" << e e.p p << "\ \n n"; s sk ki ip p() ; } } i if f (i in np pu ut t != &c ci in n) d de el le et te e i in np pu ut t; r re et tu ur rn n n no o_ _o of f_ _e er rr ro or rs s; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.192 Namespaces and Exceptions Chapter 8 The function s sk ki ip p() tries to bring the parser into a well-defined state after an error by skipping tokens until it finds an end-of-line or a semicolon. It, n no o_ _o of f_ _e er rr ro or rs s,and i in np pu ut t are obvious candi- dates for a D Dr ri iv ve er r namespace: n na am me es sp pa ac ce e D Dr ri iv ve er r { i in nt t n no o_ _o of f_ _e er rr ro or rs s; s st td d: :i is st tr re ea am m* i in np pu ut t; v vo oi id d s sk ki ip p() ; } v vo oi id d D Dr ri iv ve er r: :s sk ki ip p() { n no o_ _o of f_ _e er rr ro or rs s++; w wh hi il le e (*i in np pu ut t) { c ch ha ar r c ch h; i in np pu ut t->g ge et t(c ch h) ; s sw wi it tc ch h (c ch h) { c ca as se e ´\ \n n´: c ca as se e ´;´: i in np pu ut t->g ge et t(c ch h) ; r re et tu ur rn n; } } } The code for s sk ki ip p() is deliberately written at a lower level of abstraction than the parser code so as to avoid being caught by exceptions from the parser while handling parser exceptions. I retained the idea of counting the number of errors and reporting that number as the program’s return value. It is often useful to know if a program encountered an error even if it was able to recover from it. I did not put m ma ai in n() in the D Dr ri iv ve er r namespace. The global m ma ai in n() is the initial function of a program (§3.2); a m ma ai in n() in another namespace has no special meaning. 8.3.3.1 Alternative Error-Handling Strategies [name.strategy] The original error-handling code was shorter and more elegant than the version using exceptions. However, it achieved that elegance by tightly coupling all parts of the program. That approach doesn’t scale well to programs composed of separately developed libraries. We could consider eliminating the separate error-handling function s sk ki ip p() by introducing a state variable in m ma ai in n(). For example: i in nt t m ma ai in n(i in nt t a ar rg gc c, c ch ha ar r* a ar rg gv v[]) / / example of poor style { / / ... b bo oo ol l i in n_ _e er rr ro or r = f fa al ls se e; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.3.3.1 Alternative Error-Handling Strategies 193 w wh hi il le e (*D Dr ri iv ve er r: :i in np pu ut t) { t tr ry y { L Le ex xe er r: :g ge et t_ _t to ok ke en n() ; i if f (L Le ex xe er r: :c cu ur rr r_ _t to ok k == L Le ex xe er r: :E EN ND D) b br re ea ak k; i if f (L Le ex xe er r: :c cu ur rr r_ _t to ok k == L Le ex xe er r: :P PR RI IN NT T) { i in n_ _e er rr ro or r = f fa al ls se e; c co on nt ti in nu ue e; } i if f (i in n_ _e er rr ro or r == f fa al ls se e) c co ou ut t << P Pa ar rs se er r: :e ex xp pr r(f fa al ls se e) << ´\ \n n´; } c ca at tc ch h(E Er rr ro or r: :Z Ze er ro o_ _d di iv vi id de e) { c ce er rr r << "a at tt te em mp pt t t to o d di iv vi id de e b by y z ze er ro o\ \n n"; i in n_ _e er rr ro or r = t tr ru ue e; } c ca at tc ch h(E Er rr ro or r: :S Sy yn nt ta ax x_ _e er rr ro or r e e) { c ce er rr r << "s sy yn nt ta ax x e er rr ro or r:" << e e.p p << "\ \n n"; i in n_ _e er rr ro or r = t tr ru ue e; } } i if f (D Dr ri iv ve er r: :i in np pu ut t != s st td d: :c ci in n) d de el le et te e D Dr ri iv ve er r: :i in np pu ut t; r re et tu ur rn n D Dr ri iv ve er r: :n no o_ _o of f_ _e er rr ro or rs s; } I consider this a bad idea for several reasons: [1] State variables are a common source of confusion and errors, especially if they are allowed to proliferate and affect larger sections of a program. In particular, I consider the version of m ma ai in n() using i in n_ _e er rr ro or r less readable than the version using s sk ki ip p(). [2] It is generally a good strategy to keep error handling and ‘‘normal’’ code separate. [3] Doing error handling using the same level of abstraction as the code that caused the error is hazardous; the error-handling code might repeat the same error that triggered the error han- dling in the first place. I leave it as an exercise to find how that can happen for the version of m ma ai in n() using i in n_ _e er rr ro or r (§8.5[7]). [4] It is more work to modify the ‘‘normal’’ code to add error-handling code than to add sepa- rate error-handling routines. Exception handling is intended for dealing with nonlocal problems. If an error can be handled locally, it almost always should be. For example, there is no reason to use an exception to handle the too-many-arguments error: i in nt t m ma ai in n(i in nt t a ar rg gc c, c ch ha ar r* a ar rg gv v[]) { u us si in ng g n na am me es sp pa ac ce e s st td d; u us si in ng g n na am me es sp pa ac ce e D Dr ri iv ve er r; s sw wi it tc ch h (a ar rg gc c) { c ca as se e 1 1: / / read from standard input i in np pu ut t = &c ci in n; b br re ea ak k; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.194 Namespaces and Exceptions Chapter 8 c ca as se e 2 2: / / read argument string i in np pu ut t = n ne ew w i is st tr ri in ng gs st tr re ea am m(a ar rg gv v[1 1]) ; b br re ea ak k; d de ef fa au ul lt t: c ce er rr r << "t to oo o m ma an ny y a ar rg gu um me en nt ts s\ \n n"; r re et tu ur rn n 1 1; } / / as before } Exceptions are discussed further in Chapter 14. 8.4 Advice [name.advice] [1] Use namespaces to express logical structure; §8.2. [2] Place every nonlocal name, except m ma ai in n(), in some namespace; §8.2. [3] Design a namespace so that you can conveniently use it without accidentally gaining access to unrelated namespaces; §8.2.4. [4] Avoid very short names for namespaces; §8.2.7. [5] If necessary, use namespace aliases to abbreviate long namespaces names; §8.2.7. [6] Avoid placing heavy notational burdens on users of your namespaces; §8.2.2, §8.2.3. [7] Use the N Na am me es sp pa ac ce e: :m me em mb be er r notation when defining namespace members; §8.2.8. [8] Use u us si in ng g n na am me es sp pa ac ce e only for transition or within a local scope; §8.2.9. [9] Use exceptions to decouple the treatment of ‘‘errors’’ from the code dealing with the ordinary processing; §8.3.3. [10] Use user-defined rather than built-in types as exceptions; §8.3.2. [11] Don’t use exceptions when local control structures are sufficient; §8.3.3.1. 8.5 Exercises [name.exercises] 1. (∗2.5) Write a doubly-linked list of s st tr ri in ng g module in the style of the S St ta ac ck k module from §2.4. Exercise it by creating a list of names of programming languages. Provide a s so or rt t() function for that list, and provide a function that reverses the order of the strings in it. 2. (∗2) Take some not-too-large program that uses at least one library that does not use name- spaces and modify it to use a namespace for that library. Hint: §8.2.9. 3. (∗2) Modify the desk calculator program into a module in the style of §2.4 using namespaces. Don’t use any global using-directives. Keep a record of the mistakes you made. Suggest ways of avoiding such mistakes in the future. 4. (∗1) Write a program that throws an exception in one function and catches it in another. 5. (∗2) Write a program consisting of functions calling each other to a calling depth of 10. Give each function an argument that determines at which level an exception is thrown. Have m ma ai in n() catch these exceptions and print out which exception is caught. Don’t forget the case in which an exception is caught in the function that throws it. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 8.5 Exercises 195 6. (∗2) Modify the program from §8.5[5] to measure if there is a difference in the cost of catching exceptions depending on where in a class stack the exception is thrown. Add a string object to each function and measure again. 7. (∗1) Find the error in the first version of m ma ai in n() in §8.3.3.1. 8. (∗2) Write a function that either returns a value or that throws that value based on an argument. Measure the difference in run-time between the two ways. 9. (∗2) Modify the calculator version from §8.5[3] to use exceptions. Keep a record of the mis- takes you make. Suggest ways of avoiding such mistakes in the future. 10. (∗2.5) Write p pl lu us s(), m mi in nu us s(), m mu ul lt ti ip pl ly y(), and d di iv vi id de e() functions that check for possible overflow and underflow and that throw exceptions if such errors happen. 11. (∗2) Modify the calculator to use the functions from §8.5[10]. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.196 Namespaces and Exceptions Chapter 8 The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 9 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Source Files and Programs Form must follow function. ± Le Corbusier Separate compilation Ð linking Ð header files Ð standard library headers Ð the one- definition rule Ð linkage to non-C++ code Ð linkage and pointers to functions Ð using headers to express modularity Ð single-header organization Ð multiple-header organi- zation Ð include guards Ð programs Ð advice Ð exercises. 9.1 Separate Compilation [file.separate] A file is the traditional unit of storage (in a file system) and the traditional unit of compilation. There are systems that do not store, compile, and present C++ programs to the programmer as sets of files. However, the discussion here will concentrate on systems that employ the traditional use of files. Having a complete program in one file is usually impossible. In particular, the code for the standard libraries and the operating system is typically not supplied in source form as part of a user’s program. For realistically-sized applications, even having all of the user’s own code in a sin- gle file is both impractical and inconvenient. The way a program is organized into files can help emphasize its logical structure, help a human reader understand the program, and help the compiler to enforce that logical structure. Where the unit of compilation is a file, all of a file must be recom- piled whenever a change (however small) has been made to it or to something on which it depends. For even a moderately sized program, the amount of time spent recompiling can be significantly reduced by partitioning the program into files of suitable size. A user presents a source file to the compiler. The file is then preprocessed; that is, macro pro- cessing (§7.8) is done and #i in nc cl lu ud de e directives bring in headers (§2.4.1, §9.2.1). The result of pre- processing is called a translation unit. This unit is what the compiler proper works on and what the C++ language rules describe. In this book, I differentiate between source file and translation unit The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.198 Source Files and Programs Chapter 9 only where necessary to distinguish what the programmer sees from what the compiler considers. To enable separate compilation, the programmer must supply declarations providing the type information needed to analyze a translation unit in isolation from the rest of the program. The declarations in a program consisting of many separately compiled parts must be consistent in exactly the same way the declarations in a program consisting of a single source file must be. Your system will have tools to help ensure this. In particular, the linker can detect many kinds of incon- sistencies. The linker is the program that binds together the separately compiled parts. A linker is sometimes (confusingly) called a loader. Linking can be done completely before a program starts to run. Alternatively, new code can be added to the program (‘‘dynamically linked’’) later. The organization of a program into source files is commonly called the physical structure of a program. The physical separation of a program into separate files should be guided by the logical structure of the program. The same dependency concerns that guide the composition of programs out of namespaces guide its composition into source files. However, the logical and physical struc- ture of a program need not be identical. For example, it can be useful to use several source files to store the functions from a single namespace, to store a collection of namespace definitions in a sin- gle file, and to scatter the definition of a namespace over several files (§8.2.4). Here, we will first consider some technicalities relating to linking and then discuss two ways of breaking the desk calculator (§6.1, §8.2) into files. 9.2 Linkage [file.link] Names of functions, classes, templates, variables, namespaces, enumerations, and enumerators must be used consistently across all translation units unless they are explicitly specified to be local. It is the programmer’s task to ensure that every namespace, class, function, etc. is properly declared in every translation unit in which it appears and that all declarations referring to the same entity are consistent. For example, consider two files: / / file1.c: i in nt t x x = 1 1; i in nt t f f() { /* do something */ } / / file2.c: e ex xt te er rn n i in nt t x x; i in nt t f f() ; v vo oi id d g g() { x x = f f() ; } The x x and f f() used by g g() in f fi il le e2 2.c c are the ones defined in f fi il le e1 1.c c. The keyword e ex xt te er rn n indi- cates that the declaration of x x in f fi il le e2 2.c c is (just) a declaration and not a definition (§4.9). Had x x been initialized, e ex xt te er rn n would simply be ignored because a declaration with an initializer is always a definition. An object must be defined exactly once in a program. It may be declared many times, but the types must agree exactly. For example: / / file1.c: i in nt t x x = 1 1; i in nt t b b = 1 1; e ex xt te er rn n i in nt t c c; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 9.2 Linkage 199 / / file2.c: i in nt t x x; / / meaning int x = 0; e ex xt te er rn n d do ou ub bl le e b b; e ex xt te er rn n i in nt t c c; There are three errors here: x x is defined twice, b b is declared twice with different types, and c c is declared twice but not defined. These kinds of errors (linkage errors) cannot be detected by a com- piler that looks at only one file at a time. Most, however, are detectable by the linker. Note that a variable defined without an initializer in the global or a namespace scope is initialized by default. This is not the case for local variables (§4.9.5, §10.4.2) or objects created on the free store (§6.2.6). For example, the following program fragment contains two errors: / / file1.c: i in nt t x x; i in nt t f f() { r re et tu ur rn n x x; } / / file2.c: i in nt t x x; i in nt t g g() { r re et tu ur rn n f f() ; } The call of f f() in f fi il le e2 2.c c is an error because f f() has not been declared in f fi il le e2 2.c c. Also, the pro- gram will not link because x x is defined twice. Note that these are not errors in C (§B.2.2). A name that can be used in translation units different from the one in which it was defined is said to have external linkage. All the names in the previous examples have external linkage. A name that can be referred to only in the translation unit in which it is defined is said to have internal linkage. An i in nl li in ne e function (§7.1.1, §10.2.9) must be defined ± by identical definitions (§9.2.3) ± in every translation unit in which it is used. Consequently, the following example isn’t just bad taste; it is illegal: / / file1.c: i in nl li in ne e i in nt t f f(i in nt t i i) { r re et tu ur rn n i i; } / / file2.c: i in nl li in ne e i in nt t f f(i in nt t i i) { r re et tu ur rn n i i+1 1; } Unfortunately, this error is hard for an implementation to catch, and the following ± otherwise per- fectly logical ± combination of external linkage and inlining is banned to make life simpler for compiler writers: / / file1.c: e ex xt te er rn n i in nl li in ne e i in nt t g g(i in nt t i i) ; i in nt t h h(i in nt t i i) { r re et tu ur rn n g g(i i) ; } / / error: g() undefined in this translation unit / / file2.c: e ex xt te er rn n i in nl li in ne e i in nt t g g(i in nt t i i) { r re et tu ur rn n i i+1 1; } By default, c co on ns st ts (§5.4) and t ty yp pe ed de ef fs (§4.9.7) have internal linkage. Consequently, this example is legal (although potentially confusing): The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.200 Source Files and Programs Chapter 9 / / file1.c: t ty yp pe ed de ef f i in nt t T T; c co on ns st t i in nt t x x = 7 7; / / file2.c: t ty yp pe ed de ef f v vo oi id d T T; c co on ns st t i in nt t x x = 8 8; Global variables that are local to a single compilation unit are a common source of confusion and are best avoided. To ensure consistency, you should usually place global c co on ns st ts and i in nl li in ne es in header files only (§9.2.1). A c co on ns st t can be given external linkage by an explicit declaration: / / file1.c: e ex xt te er rn n c co on ns st t i in nt t a a = 7 77 7; / / file2.c: e ex xt te er rn n c co on ns st t i in nt t a a; v vo oi id d g g() { c co ou ut t << a a << ´\ \n n´; } Here, g g() will print 7 77 7. An unnamed namespace (§8.2.5) can be used to make names local to a compilation unit. The effect of an unnamed namespace is very similar to that of internal linkage. For example: / / file 1.c: n na am me es sp pa ac ce e { c cl la as ss s X X { /* ... */ }; v vo oi id d f f() ; i in nt t i i; / / ... } / / file2.c: c cl la as ss s X X { /* ... */ }; v vo oi id d f f() ; i in nt t i i; / / ... The function f f() in f fi il le e1 1.c c is not the same function as the f f() in f fi il le e2 2.c c. Having a name local to a translation unit and also using that same name elsewhere for an entity with external linkage is asking for trouble. In C and older C++ programs, the keyword s st ta at ti ic c is (confusingly) used to mean ‘‘use internal linkage’’ (§B.2.3). Don’t use s st ta at ti ic c except inside functions (§7.1.2) and classes (§10.2.4). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 9.2.1 Header Files 201 9.2.1 Header Files [file.header] The types in all declarations of the same object, function, class, etc., must be consistent. Conse- quently, the source code submitted to the compiler and later linked together must be consistent. One imperfect but simple method of achieving consistency for declarations in different translation units is to #i in nc cl lu ud de e header files containing interface information in source files containing exe- cutable code and/or data definitions. The #i in nc cl lu ud de e mechanism is a text manipulation facility for gathering source program fragments together into a single unit (file) for compilation. The directive #i in nc cl lu ud de e "t to o_ _b be e_ _i in nc cl lu ud de ed d" replaces the line in which the #i in nc cl lu ud de e appears with the contents of the file t to o_ _b be e_ _i in nc cl lu ud de ed d. The content should be C++ source text because the compiler will proceed to read it. To include standard library headers, use the angle brackets < and > around the name instead of quotes. For example: #i in nc cl lu ud de e / / from standard include directory #i in nc cl lu ud de e "m my yh he ea ad de er r.h h" / / from current directory Unfortunately, spaces are significant within the < > or " " of an include directive: #i in nc cl lu ud de e < i io os st tr re ea am m > / / will not find It may seem extravagant to recompile a file each time it is included somewhere, but the included files typically contain only declarations and not code needing extensive analysis by the compiler. Furthermore, most modern C++ implementations provide some form of precompiling of header files to minimize the work needed to handle repeated compilation of the same header. As a rule of thumb, a header may contain:_ _______________________________________________________________________ Named namespaces n na am me es sp pa ac ce e N N { /* . .. .. . */ } Type definitions s st tr ru uc ct t P Po oi in nt t { i in nt t x x, y y; }; Template declarations t te em mp pl la at te e c cl la as ss s Z Z; Template definitions t te em mp pl la at te e c cl la as ss s V V { /* . .. .. . */ }; Function declarations e ex xt te er rn n i in nt t s st tr rl le en n(c co on ns st t c ch ha ar r*); Inline function definitions i in nl li in ne e c ch ha ar r g ge et t(c ch ha ar r* p p) { r re et tu ur rn n *p p++; } Data declarations e ex xt te er rn n i in nt t a a; Constant definitions c co on ns st t f fl lo oa at t p pi i = 3 3. .1 14 41 15 59 93 3; Enumerations e en nu um m L Li ig gh ht t { r re ed d, y ye el ll lo ow w, g gr re ee en n }; Name declarations c cl la as ss s M Ma at tr ri ix x; Include directives #i in nc cl lu ud de e Macro definitions #d de ef fi in ne e V VE ER RS SI IO ON N 1 12 2 Conditional compilation directives #i if fd de ef f _ __ _c cp pl lu us sp pl lu us s Comments /* c ch he ec ck k f fo or r e en nd d o of f f fi il le e */_ _______________________________________________________________________                                   This rule of thumb for what may be placed in a header is not a language requirement. It is simply a reasonable way of using the #i in nc cl lu ud de e mechanism to express the physical structure of a program. Conversely, a header should never contain: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.202 Source Files and Programs Chapter 9 _ _____________________________________________________________________ Ordinary function definitions c ch ha ar r g ge et t(c ch ha ar r* p p) { r re et tu ur rn n *p p++; } Data definitions i in nt t a a; Aggregate definitions s sh ho or rt t t tb bl l[] = { 1 1, 2 2, 3 3 }; Unnamed namespaces n na am me es sp pa ac ce e { /* . .. .. . */ } Exported template definitions e ex xp po or rt t t te em mp pl la at te e f f(T T t t) { /* . .. .. . */ }_ _____________________________________________________________________             Header files are conventionally suffixed by .h h, and files containing function or data definitions are suffixed by .c c. They are therefore often referred to as ‘‘.h files’’ and ‘‘.c files,’’ respectively. Other conventions, such as .C C, .c cx xx x, .c cp pp p, and .c cc c, are also found. The manual for your com- piler will be quite specific about this issue. The reason for recommending that the definition of simple constants, but not the definition of aggregates, be placed in header files is that it is hard for implementations to avoid replication of aggregates presented in several translation units. Furthermore, the simple cases are far more com- mon and therefore more important for generating good code. It is wise not to be too clever about the use of #i in nc cl lu ud de e. My recommendation is to #i in nc cl lu ud de e only complete declarations and definitions and to do so only in the global scope, in linkage specifi- cation blocks, and in namespace definitions when converting old code (§9.2.2). As usual, it is wise to avoid macro magic. One of my least favorite activities is tracking down an error caused by a name being macro-substituted into something completely different by a macro defined in an indi- rectly #i in nc cl lu ud de ed header that I have never even heard of. 9.2.2 Standard Library Headers [file.std.header] The facilities of the standard library are presented through a set of standard headers (§16.1.2). No suffix is needed for standard library headers; they are known to be headers because they are included using the #i in nc cl lu ud de e<...> syntax rather than #i in nc cl lu ud de e"...". The absence of a .h h suf- fix does not imply anything about how the header is stored. A header such as may be stored as a text file called m ma ap p.h h in a standard directory. On the other hand, standard headers are not required to be stored in a conventional manner. An implementation is allowed to take advan- tage of knowledge of the standard library definition to optimize the standard library implementation and the way standard headers are handled. For example, an implementation might have knowledge of the standard math library (§22.3) built in and treat #i in nc cl lu ud de e as a switch that makes the standard math functions available without reading any file. For each C standard-library header , there is a corresponding standard C++ header . For example, #i in nc cl lu ud de e provides what #i in nc cl lu ud de e does. A typical s st td di io o.h h will look something like this: #i if fd de ef f _ __ _c cp pl lu us sp pl lu us s / / for C++ compliers only (§9.2.4) n na am me es sp pa ac ce e s st td d { / / the standard library is defined in namespace std (§8.2.9) e ex xt te er rn n "C C" { / / stdio functions have C linkage (§9.2.4) #e en nd di if f / / ... i in nt t p pr ri in nt tf f(c co on ns st t c ch ha ar r* ...) ; / / ... The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 9.2.2 Standard Library Headers 203 #i if fd de ef f _ __ _c cp pl lu us sp pl lu us s } } u us si in ng g n na am me es sp pa ac ce e s st td d; / / make stdio available in global namespace #e en nd di if f That is, the actual declarations are (most likely) shared, but linkage and namespace issues must be addressed to allow C and C++ to share a header. 9.2.3 The One-Definition Rule [file.odr] A given class, enumeration, and template, etc., must be defined exactly once in a program. From a practical point of view, this means that there must be exactly one definition of, say, a class residing in a single file somewhere. Unfortunately, the language rule cannot be that simple. For example, the definition of a class may be composed through macro expansion (ugh!), while a definition of a class may be textually included in two source files by #i in nc cl lu ud de e directives (§9.2.1). Worse, a ‘‘file’’ isn’t a concept that is part of the C and C++ language definitions; there exist imple- mentations that do not store programs in source files. Consequently, the rule in the standard that says that there must be a unique definition of a class, template, etc., is phrased in a somewhat more complicated and subtle manner. This rule is com- monly referred to as ‘‘the one-definition rule,’’ the ODR. That is, two definitions of a class, tem- plate, or inline function are accepted as examples of the same unique definition if and only if [1] they appear in different translation units, and [2] they are token-for-token identical, and [3] the meanings of those tokens are the same in both translation units. For example: / / file1.c: s st tr ru uc ct t S S { i in nt t a a; c ch ha ar r b b; }; v vo oi id d f f(S S*) ; / / file2.c: s st tr ru uc ct t S S { i in nt t a a; c ch ha ar r b b; }; v vo oi id d f f(S S* p p) { /* ... */ } The ODR says that this example is valid and that S S refers to the same class in both source files. However, it is unwise to write out a definition twice like that. Someone maintaining f fi il le e2 2.c c will naturally assume that the definition of S S in f fi il le e2 2.c c is the only definition of S S and so feel free to change it. This could introduce a hard-to-detect error. The intent of the ODR is to allow inclusion of a class definition in different translation units from a common source file. For example: / / file s.h: s st tr ru uc ct t S S { i in nt t a a; c ch ha ar r b b; }; v vo oi id d f f(S S*) ; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.204 Source Files and Programs Chapter 9 / / file1.c: #i in nc cl lu ud de e "s s.h h" / / use f() here / / file2.c: #i in nc cl lu ud de e "s s.h h" v vo oi id d f f(S S* p p) { /* ... */ } or graphically: s st tr ru uc ct t S S { i in nt t a a; c ch ha ar r b b; }; v vo oi id d f f(S S*); #i in nc cl lu ud de e " "s s. .h h" " // use f() here #i in nc cl lu ud de e " "s s. .h h" " v vo oi id d f f(S S* p p) { /* . .. .. . */ } s s. .h h: : f fi il le e1 1. .c c: : f fi il le e2 2. .c c: : Here are examples of the three ways of violating the ODR: / / file1.c: s st tr ru uc ct t S S1 1 { i in nt t a a; c ch ha ar r b b; }; s st tr ru uc ct t S S1 1 { i in nt t a a; c ch ha ar r b b; }; / / error: double definition This is an error because a s st tr ru uc ct t may not be defined twice in a single translation unit. / / file1.c: s st tr ru uc ct t S S2 2 { i in nt t a a; c ch ha ar r b b; }; / / file2.c: s st tr ru uc ct t S S2 2 { i in nt t a a; c ch ha ar r b bb b; }; / / error This is an error because S S2 2 is used to name classes that differ in a member name. / / file1.c: t ty yp pe ed de ef f i in nt t X X; s st tr ru uc ct t S S3 3 { X X a a; c ch ha ar r b b; }; / / file2.c: t ty yp pe ed de ef f c ch ha ar r X X; s st tr ru uc ct t S S3 3 { X X a a; c ch ha ar r b b; }; / / error Here the two definitions of S S3 3 are token-for-token identical, but the example is an error because the meaning of the name X X has sneakily been made to differ in the two files. Checking against inconsistent class definitions in separate translation units is beyond the ability of most C++ implementations. Consequently, declarations that violate the ODR can be a source of subtle errors. Unfortunately, the technique of placing shared definitions in headers and #i in nc cl lu ud di in ng g them doesn’t protect against this last form of ODR violation. Local typedefs and macros can change the meaning of #i in nc cl lu ud de ed declarations: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 9.2.3 The One-Definition Rule 205 / / file s.h: s st tr ru uc ct t S S { P Po oi in nt t a a; c ch ha ar r b b; }; / / file1.c: #d de ef fi in ne e P Po oi in nt t i in nt t #i in nc cl lu ud de e "s s.h h" / / ... / / file2.c: c cl la as ss s P Po oi in nt t { /* ... */ }; #i in nc cl lu ud de e "s s.h h" / / ... The best defense against this kind of hackery is to make headers as self-contained as possible. For example, if class P Po oi in nt t had been declared in the s s.h h header the error would have been detected. A template definition can be #i in nc cl lu ud de ed in several translation units as long as the ODR is adhered to. In addition, an exported template can be used given only a declaration: / / file1.c: e ex xp po or rt t t te em mp pl la at te e T T t tw wi ic ce e(T T t t) { r re et tu ur rn n t t+t t; } / / file2.c: t te em mp pl la at te e T T t tw wi ic ce e(T T t t) ; / / declaration i in nt t g g(i in nt t i i) { r re et tu ur rn n t tw wi ic ce e(i i) ; } The keyword e ex xp po or rt t means ‘‘accessible from another translation unit’’ (§13.7). 9.2.4 Linkage to Non-C++ Code [file.c] Typically, a C++ program contains parts written in other languages. Similarly, it is common for C++ code fragments to be used as parts of programs written mainly in some other language. Coop- eration can be difficult between program fragments written in different languages and even between fragments written in the same language but compiled with different compilers. For example, differ- ent languages and different implementations of the same language may differ in their use of machine registers to hold arguments, the layout of arguments put on a stack, the layout of built-in types such as strings and integers, the form of names passed by the compiler to the linker, and the amount of type checking required from the linker. To help, one can specify a linkage convention to be used in an e ex xt te er rn n declaration. For example, this declares the C and C++ standard library func- tion s st tr rc cp py y() and specifies that it should be linked according to the C linkage conventions: e ex xt te er rn n "C C" c ch ha ar r* s st tr rc cp py y(c ch ha ar r*, c co on ns st t c ch ha ar r*) ; The effect of this declaration differs from the effect of the ‘‘plain’’ declaration e ex xt te er rn n c ch ha ar r* s st tr rc cp py y(c ch ha ar r*, c co on ns st t c ch ha ar r*) ; only in the linkage convention used for calling s st tr rc cp py y(). The e ex xt te er rn n " "C C" " directive is particularly useful because of the close relationship between C and C++. Note that the C C in e ex xt te er rn n " "C C" " names a linkage convention and not a language. Often, e ex xt te er rn n " "C C" " is used to link to Fortran and assembler routines that happen to conform to the conventions of a C implementation. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.206 Source Files and Programs Chapter 9 An e ex xt te er rn n " "C C" " directive specifies the linkage convention (only) and does not affect the seman- tics of calls to the function. In particular, a function declared e ex xt te er rn n " "C C" " still obeys the C++ type checking and argument conversion rules and not the weaker C rules. For example: e ex xt te er rn n "C C" i in nt t f f() ; i in nt t g g() { r re et tu ur rn n f f(1 1) ; / / error: no argument expected } Adding e ex xt te er rn n " "C C" " to a lot of declarations can be a nuisance. Consequently, there is a mechanism to specify linkage to a group of declarations. For example: e ex xt te er rn n "C C" { c ch ha ar r* s st tr rc cp py y(c ch ha ar r*, c co on ns st t c ch ha ar r*) ; i in nt t s st tr rc cm mp p(c co on ns st t c ch ha ar r*, c co on ns st t c ch ha ar r*) ; i in nt t s st tr rl le en n(c co on ns st t c ch ha ar r*) ; / / ... } This construct, commonly called a linkage block, can be used to enclose a complete C header to make a header suitable for C++ use. For example: e ex xt te er rn n "C C" { #i in nc cl lu ud de e } This technique is commonly used to produce a C++ header from a C header. Alternatively, condi- tional compilation (§7.8.1) can be used to create a common C and C++ header: #i if fd de ef f _ __ _c cp pl lu us sp pl lu us s e ex xt te er rn n "C C" { #e en nd di if f c ch ha ar r* s st tr rc cp py y(c ch ha ar r*, c co on ns st t c ch ha ar r*) ; i in nt t s st tr rc cm mp p(c co on ns st t c ch ha ar r*, c co on ns st t c ch ha ar r*) ; i in nt t s st tr rl le en n(c co on ns st t c ch ha ar r*) ; / / ... #i if fd de ef f _ __ _c cp pl lu us sp pl lu us s } #e en nd di if f The predefined macro name _ __ _c cp pl lu us sp pl lu us s is used to ensure that the C++ constructs are edited out when the file is used as a C header. Any declaration can appear within a linkage block: e ex xt te er rn n "C C" { / / any declaration here, for example: i in nt t g g1 1; / / definition e ex xt te er rn n i in nt t g g2 2; / / declaration, not definition } In particular, the scope and storage class of variables are not affected, so g g1 1 is still a global variable The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 9.2.4 Linkage to Non-C++ Code 207 ± and is still defined rather than just declared. To declare but not define a variable, you must apply the keyword e ex xt te er rn n directly in the declaration. For example: e ex xt te er rn n "C C" i in nt t g g3 3; / / declaration, not definition This looks odd at first glance. However, it is a simple consequence of keeping the meaning unchanged when adding " "C C" " to an extern declaration and the meaning of a file unchanged when enclosing it in a linkage block. A name with C linkage can be declared in a namespace. The namespace will affect the way the name is accessed in the C++ program, but not the way a linker sees it. The p pr ri in nt tf f() from s st td d is a typical example: #i in nc cl lu ud de e v vo oi id d f f() { s st td d: :p pr ri in nt tf f("H He el ll lo o, ") ; / / ok p pr ri in nt tf f("w wo or rl ld d!\ \n n") ; / / error: no global printf() } Even when called s st td d: :p pr ri in nt tf f, it is still the same old C p pr ri in nt tf f() (§21.8). Note that this allows us to include libraries with C linkage into a namespace of our choice rather than polluting the global namespace. Unfortunately, the same flexibility is not available to us for headers defining functions with C++ linkage in the global namespace. The reason is that linkage of C++ entities must take namespaces into account so that the object files generated will reflect the use or lack of use of namespaces. 9.2.5 Linkage and Pointers to Functions [file.ptof] When mixing C and C++ code fragments in one program, we sometimes want to pass pointers to functions defined in one language to functions defined in the other. If the two implementations of the two languages share linkage conventions and function-call mechanisms, such passing of point- ers to functions is trivial. However, such commonality cannot in general be assumed, so care must be taken to ensure that a function is called the way it expects to be called. When linkage is specified for a declaration, the specified linkage applies to all function types, function names, and variable names introduced by the declaration(s). This makes all kinds of strange ± and occasionally essential ± combinations of linkage possible. For example: t ty yp pe ed de ef f i in nt t (*F FT T)(c co on ns st t v vo oi id d*, c co on ns st t v vo oi id d*) ; / / FT has C++ linkage e ex xt te er rn n "C C" { t ty yp pe ed de ef f i in nt t (*C CF FT T)(c co on ns st t v vo oi id d*, c co on ns st t v vo oi id d*) ; / / CFT has C linkage v vo oi id d q qs so or rt t(v vo oi id d* p p, s si iz ze e_ _t t n n, s si iz ze e_ _t t s sz z, C CF FT T c cm mp p) ; / / cmp has C linkage } v vo oi id d i is so or rt t(v vo oi id d* p p, s si iz ze e_ _t t n n, s si iz ze e_ _t t s sz z, F FT T c cm mp p) ; / / cmp has C++ linkage v vo oi id d x xs so or rt t(v vo oi id d* p p, s si iz ze e_ _t t n n, s si iz ze e_ _t t s sz z, C CF FT T c cm mp p) ; / / cmp has C linkage e ex xt te er rn n "C C" v vo oi id d y ys so or rt t(v vo oi id d* p p, s si iz ze e_ _t t n n, s si iz ze e_ _t t s sz z, F FT T c cm mp p) ; / / cmp has C++ linkage i in nt t c co om mp pa ar re e(c co on ns st t v vo oi id d*, c co on ns st t v vo oi id d*) ; / / compare() has C++ linkage e ex xt te er rn n "C C" i in nt t c cc cm mp p(c co on ns st t v vo oi id d*, c co on ns st t v vo oi id d*) ; / / ccmp() has C linkage The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.208 Source Files and Programs Chapter 9 v vo oi id d f f(c ch ha ar r* v v, i in nt t s sz z) { q qs so or rt t(v v,s sz z,1 1,&c co om mp pa ar re e) ; / / error q qs so or rt t(v v,s sz z,1 1,&c cc cm mp p) ; / / ok i is so or rt t(v v,s sz z,1 1,&c co om mp pa ar re e) ; / / ok i is so or rt t(v v,s sz z,1 1,&c cc cm mp p) ; / / error } An implementation in which C and C++ use the same calling conventions might accept the cases marked error as a language extension. 9.3 Using Header Files [file.using] To illustrate the use of headers, I present a few alternative ways of expressing the physical structure of the calculator program (§6.1, §8.2). 9.3.1 Single Header File [file.single] The simplest solution to the problem of partitioning a program into several files is to put the defini- tions in a suitable number of .c c files and to declare the types needed for them to communicate in a single .h h file that each .c c file #i in nc cl lu ud de es. For the calculator program, we might use five .c c files ± l le ex xe er r.c c, p pa ar rs se er r.c c, t ta ab bl le e.c c, e er rr ro or r.c c, and m ma ai in n.c c ± to hold function and data definitions, plus the header d dc c.h h to hold the declarations of every name used in more than one .c c file. The header d dc c.h h would look like this: / / dc.h: n na am me es sp pa ac ce e E Er rr ro or r { s st tr ru uc ct t Z Ze er ro o_ _d di iv vi id de e { }; s st tr ru uc ct t S Sy yn nt ta ax x_ _e er rr ro or r { c co on ns st t c ch ha ar r* p p; S Sy yn nt ta ax x_ _e er rr ro or r(c co on ns st t c ch ha ar r* q q) { p p = q q; } }; } #i in nc cl lu ud de e n na am me es sp pa ac ce e L Le ex xe er r { e en nu um m T To ok ke en n_ _v va al lu ue e { N NA AM ME E, N NU UM MB BE ER R, E EN ND D, P PL LU US S=´+´, M MI IN NU US S=´-´, M MU UL L=´*´, D DI IV V=´/´, P PR RI IN NT T=´;´, A AS SS SI IG GN N=´=´, L LP P=´(´, R RP P=´)´ }; e ex xt te er rn n T To ok ke en n_ _v va al lu ue e c cu ur rr r_ _t to ok k; e ex xt te er rn n d do ou ub bl le e n nu um mb be er r_ _v va al lu ue e; e ex xt te er rn n s st td d: :s st tr ri in ng g s st tr ri in ng g_ _v va al lu ue e; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 9.3.1 Single Header File 209 T To ok ke en n_ _v va al lu ue e g ge et t_ _t to ok ke en n() ; } n na am me es sp pa ac ce e P Pa ar rs se er r { d do ou ub bl le e p pr ri im m(b bo oo ol l g ge et t) ; / / handle primaries d do ou ub bl le e t te er rm m(b bo oo ol l g ge et t) ; / / multiply and divide d do ou ub bl le e e ex xp pr r(b bo oo ol l g ge et t) ; / / add and subtract u us si in ng g L Le ex xe er r: :g ge et t_ _t to ok ke en n; u us si in ng g L Le ex xe er r: :c cu ur rr r_ _t to ok k; } #i in nc cl lu ud de e e ex xt te er rn n s st td d: :m ma ap p t ta ab bl le e; n na am me es sp pa ac ce e D Dr ri iv ve er r { e ex xt te er rn n i in nt t n no o_ _o of f_ _e er rr ro or rs s; e ex xt te er rn n s st td d: :i is st tr re ea am m* i in np pu ut t; v vo oi id d s sk ki ip p() ; } The keyword e ex xt te er rn n is used for every declaration of a variable to ensure that multiple definitions do not occur as we #i in nc cl lu ud de e d dc c.h h in the various .c c files. The corresponding definitions are found in the appropriate .c c files. Leaving out the actual code, l le ex xe er r.c c will look something like this: / / lexer.c: #i in nc cl lu ud de e "d dc c.h h" #i in nc cl lu ud de e #i in nc cl lu ud de e L Le ex xe er r: :T To ok ke en n_ _v va al lu ue e L Le ex xe er r: :c cu ur rr r_ _t to ok k; d do ou ub bl le e L Le ex xe er r: :n nu um mb be er r_ _v va al lu ue e; s st td d: :s st tr ri in ng g L Le ex xe er r: :s st tr ri in ng g_ _v va al lu ue e; L Le ex xe er r: :T To ok ke en n_ _v va al lu ue e L Le ex xe er r: :g ge et t_ _t to ok ke en n() { /* ... */ } Using headers in this manner ensures that every declaration in a header will at some point be included in the file containing its definition. For example, when compiling l le ex xe er r.c c the compiler will be presented with: n na am me es sp pa ac ce e L Le ex xe er r { / / from dc.h / / ... T To ok ke en n_ _v va al lu ue e g ge et t_ _t to ok ke en n() ; } / / ... L Le ex xe er r: :T To ok ke en n_ _v va al lu ue e L Le ex xe er r: :g ge et t_ _t to ok ke en n() { /* ... */ } This ensures that the compiler will detect any inconsistencies in the types specified for a name. For example, had g ge et t_ _t to ok ke en n() been declared to return a T To ok ke en n_ _v va al lu ue e, but defined to return an i in nt t, the compilation of l le ex xe er r.c c would have failed with a type-mismatch error. If a definition is missing, The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.210 Source Files and Programs Chapter 9 the linker will catch the problem. If a declaration is missing, some .c c file will fail to compile. File p pa ar rs se er r.c c will look like this: / / parser.c: #i in nc cl lu ud de e "d dc c.h h" d do ou ub bl le e P Pa ar rs se er r: :p pr ri im m(b bo oo ol l g ge et t) { /* ... */ } d do ou ub bl le e P Pa ar rs se er r: :t te er rm m(b bo oo ol l g ge et t) { /* ... */ } d do ou ub bl le e P Pa ar rs se er r: :e ex xp pr r(b bo oo ol l g ge et t) { /* ... */ } File t ta ab bl le e.c c will look like this: / / table.c: #i in nc cl lu ud de e "d dc c.h h" s st td d: :m ma ap p t ta ab bl le e; The symbol table is simply a variable of the standard library m ma ap p type. This defines t ta ab bl le e to be global. In a realistically-sized program, this kind of minor pollution of the global namespace builds up and eventually causes problems. I left this sloppiness here simply to get an opportunity to warn against it. Finally, file m ma ai in n.c c will look like this: / / main.c: #i in nc cl lu ud de e "d dc c.h h" #i in nc cl lu ud de e i in nt t D Dr ri iv ve er r: :n no o_ _o of f_ _e er rr ro or rs s = 0 0; s st td d: :i is st tr re ea am m* D Dr ri iv ve er r: :i in np pu ut t = 0 0; v vo oi id d D Dr ri iv ve er r: :s sk ki ip p() { /* ... */ } i in nt t m ma ai in n(i in nt t a ar rg gc c, c ch ha ar r* a ar rg gv v[]) { /* ... */ } To be recognized as the m ma ai in n() of the program, m ma ai in n() must be a global function, so no name- space is used here. The physical structure of the system can be presented like this: t ta ab bl le e. .c c . . p pa ar rs se er r. .c c . . d dr ri iv ve er r. .c c . . l le ex xe er r. .c c . . dc.h < >. .< > . .< > . .< >. .< > .. Note that the headers on the top are all headers for standard library facilities. For many forms of program analysis, these libraries can be ignored because they are well known and stable. For tiny The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 9.3.1 Single Header File 211 programs, the structure can be simplified by moving all #i in nc cl lu ud de e directives to the common header. This single-header style of physical partitioning is most useful when the program is small and its parts are not intended to be used separately. Note that when namespaces are used, the logical structure of the program is still represented within d dc c.h h. If namespaces are not used, the structure is obscured, although comments can be a help. For larger programs, the single header file approach is unworkable in a conventional file-based development environment. A change to the common header forces recompilation of the whole pro- gram, and updates of that single header by several programmers are error-prone. Unless strong emphasis is placed on programming styles relying heavily on namespaces and classes, the logical structure deteriorates as the program grows. 9.3.2 Multiple Header Files [file.multi] An alternative physical organization lets each logical module have its own header defining the facilities it provides. Each .c c file then has a corresponding .h h file specifying what it provides (its interface). Each .c c file includes its own .h h file and usually also other .h h files that specify what it needs from other modules in order to implement the services advertised in the interface. This phys- ical organization corresponds to the logical organization of a module. The interface for users is put into its .h h file, the interface for implementers is put into a file suffixed _ _i im mp pl l.h h, and the module’s definitions of functions, variables, etc. are placed in .c c files. In this way, the parser is represented by three files. The parser’s user interface is provided by p pa ar rs se er r.h h: / / parser.h: n na am me es sp pa ac ce e P Pa ar rs se er r { / / interface for users d do ou ub bl le e e ex xp pr r(b bo oo ol l g ge et t) ; } The shared environment for the functions implementing the parser is presented by p pa ar rs se er r_ _i im mp pl l.h h: / / parser_impl.h: #i in nc cl lu ud de e "p pa ar rs se er r.h h" #i in nc cl lu ud de e "e er rr ro or r.h h" #i in nc cl lu ud de e "l le ex xe er r.h h" n na am me es sp pa ac ce e P Pa ar rs se er r { / / interface for implementers d do ou ub bl le e p pr ri im m(b bo oo ol l g ge et t) ; d do ou ub bl le e t te er rm m(b bo oo ol l g ge et t) ; d do ou ub bl le e e ex xp pr r(b bo oo ol l g ge et t) ; u us si in ng g L Le ex xe er r: :g ge et t_ _t to ok ke en n; u us si in ng g L Le ex xe er r: :c cu ur rr r_ _t to ok k; } The user’s header p pa ar rs se er r.h h is #i in nc cl lu ud de ed to give the compiler a chance to check consistency (§9.3.1). The functions implementing the parser are stored in p pa ar rs se er r.c c together with #i in nc cl lu ud de e directives for the headers that the P Pa ar rs se er r functions need: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.212 Source Files and Programs Chapter 9 / / parser.c: #i in nc cl lu ud de e "p pa ar rs se er r_ _i im mp pl l.h h" #i in nc cl lu ud de e "t ta ab bl le e.h h" d do ou ub bl le e P Pa ar rs se er r: :p pr ri im m(b bo oo ol l g ge et t) { /* ... */ } d do ou ub bl le e P Pa ar rs se er r: :t te er rm m(b bo oo ol l g ge et t) { /* ... */ } d do ou ub bl le e P Pa ar rs se er r: :e ex xp pr r(b bo oo ol l g ge et t) { /* ... */ } Graphically, the parser and the driver’s use of it look like this: p pa ar rs se er r. .h h . . l le ex xe er r. .h h . . e er rr ro or r. .h h . . t ta ab bl le e. .h h . . p pa ar rs se er r_ _i im mp pl l. .h h . . d dr ri iv ve er r. .c c . . p pa ar rs se er r. .c c .. As intended, this is a rather close match to the logical structure described in §8.3.3. To simplify this structure, we could have #i in nc cl lu ud de ed t ta ab bl le e.h h in p pa ar rs se er r_ _i im mp pl l.h h rather than in p pa ar rs se er r.c c. How- ever, t ta ab bl le e.h h is an example of something that is not necessary to express the shared context of the parser functions; it is needed only by their implementation. In fact, it is used by just one function, e ex xp pr r(), so if we were really keen on minimizing dependencies we could place e ex xp pr r() in its own .c c file and #i in nc cl lu ud de e t ta ab bl le e.h h there only: p pa ar rs se er r. .h h . . l le ex xe er r. .h h . . e er rr ro or r. .h h . . t ta ab bl le e. .h h . . p pa ar rs se er r_ _i im mp pl l. .h h . . p pa ar rs se er r. .c c .. e ex xp pr r. .c c .. Such elaboration is not appropriate except for larger modules. For realistically-sized modules, it is common to #i in nc cl lu ud de e extra files where needed for individual functions. Furthermore, it is not uncommon to have more than one _ _i im mp pl l.h h, since different subsets of the module’s functions need different shared contexts. Please note that the _ _i im mp pl l.h h notation is not a standard or even a common convention; it is sim- ply the way I like to name things. Why bother with this more complicated scheme of multiple header files? It clearly requires far less thought simply to throw every declaration into a single header, as was done for d dc c.h h. The multiple-header organization scales to modules several magnitudes larger than our toy parser and to programs several magnitudes larger than our calculator. The fundamental reason for using this type of organization is that it provides a better localization of concerns. When analyzing The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 9.3.2 Multiple Header Files 213 and modifying a large program, it is essential for a programmer to focus on a relatively small chunk of code. The multiple-header organization makes it easy to determine exactly what the parser code depends on and to ignore the rest of the program. The single-header approach forces us to look at every declaration used by any module and decide if it is relevant. The simple fact is that mainte- nance of code is invariably done with incomplete information and from a local perspective. The multiple-header organization allows us to work successfully ‘‘from the inside out’’ with only a local perspective. The single-header approach ± like every other organization centered around a global repository of information ± requires a top-down approach and will forever leave us wonder- ing exactly what depends on what. The better localization leads to less information needed to compile a module, and thus to faster compiles. The effect can be dramatic. I have seen compile times drop by a factor of ten as the result of a simple dependency analysis leading to a better use of headers. 9.3.2.1 Other Calculator Modules [file.multi.etc] The remaining calculator modules can be organized similarly to the parser. However, those mod- ules are so small that they don’t require their own _ _i im mp pl l.h h files. Such files are needed only where a logical module consists of many functions that need a shared context. The error handler was reduced to the set of exception types so that no e er rr ro or r.c c was needed: / / error.h: n na am me es sp pa ac ce e E Er rr ro or r { s st tr ru uc ct t Z Ze er ro o_ _d di iv vi id de e { }; s st tr ru uc ct t S Sy yn nt ta ax x_ _e er rr ro or r { c co on ns st t c ch ha ar r* p p; S Sy yn nt ta ax x_ _e er rr ro or r(c co on ns st t c ch ha ar r* q q) { p p = q q; } }; } The lexer provides a rather large and messy interface: / / lexer.h: #i in nc cl lu ud de e n na am me es sp pa ac ce e L Le ex xe er r { e en nu um m T To ok ke en n_ _v va al lu ue e { N NA AM ME E, N NU UM MB BE ER R, E EN ND D, P PL LU US S=´+´, M MI IN NU US S=´-´, M MU UL L=´*´, D DI IV V=´/´, P PR RI IN NT T=´;´, A AS SS SI IG GN N=´=´, L LP P=´(´, R RP P=´)´ }; e ex xt te er rn n T To ok ke en n_ _v va al lu ue e c cu ur rr r_ _t to ok k; e ex xt te er rn n d do ou ub bl le e n nu um mb be er r_ _v va al lu ue e; e ex xt te er rn n s st td d: :s st tr ri in ng g s st tr ri in ng g_ _v va al lu ue e; T To ok ke en n_ _v va al lu ue e g ge et t_ _t to ok ke en n() ; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.214 Source Files and Programs Chapter 9 In addition to l le ex xe er r.h h, the implementation of the lexer depends on e er rr ro or r.h h, , and the functions determining the kinds of characters declared in : / / lexer.c: #i in nc cl lu ud de e "l le ex xe er r.h h" #i in nc cl lu ud de e "e er rr ro or r.h h" #i in nc cl lu ud de e #i in nc cl lu ud de e L Le ex xe er r: :T To ok ke en n_ _v va al lu ue e L Le ex xe er r: :c cu ur rr r_ _t to ok k; d do ou ub bl le e L Le ex xe er r: :n nu um mb be er r_ _v va al lu ue e; s st td d: :s st tr ri in ng g L Le ex xe er r: :s st tr ri in ng g_ _v va al lu ue e; L Le ex xe er r: :T To ok ke en n_ _v va al lu ue e L Le ex xe er r: :g ge et t_ _t to ok ke en n() { /* ... */ } We could have factored out the #i in nc cl lu ud de e statements for e er rr ro or r.h h as the L Le ex xe er r’s _ _i im mp pl l.h h file. However, I considered that excessive for this tiny program. As usual, we #i in nc cl lu ud de e the interface offered by the module ± in this case, l le ex xe er r.h h ± in the module’s implementation to give the compiler a chance to check consistency. The symbol table is essentially self-contained, although the standard library header could drag in all kinds of interesting stuff to implement an efficient m ma ap p template class: / / table.h: #i in nc cl lu ud de e #i in nc cl lu ud de e e ex xt te er rn n s st td d: :m ma ap p t ta ab bl le e; Because we assume that every header may be #i in nc cl lu ud de ed in several .c c files, we must separate the declaration of t ta ab bl le e from its definition, even though the difference between t ta ab bl le e.c c and t ta ab bl le e.h h is the single keyword e ex xt te er rn n: / / table.c: #i in nc cl lu ud de e "t ta ab bl le e.h h" s st td d: :m ma ap p t ta ab bl le e; Basically, the driver depends on everything: / / main.c: #i in nc cl lu ud de e "p pa ar rs se er r.h h" #i in nc cl lu ud de e "l le ex xe er r.h h" #i in nc cl lu ud de e "e er rr ro or r.h h" #i in nc cl lu ud de e "t ta ab bl le e.h h" n na am me es sp pa ac ce e D Dr ri iv ve er r { i in nt t n no o_ _o of f_ _e er rr ro or rs s; s st td d: :i is st tr re ea am m* i in np pu ut t; v vo oi id d s sk ki ip p() ; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 9.3.2.1 Other Calculator Modules 215 #i in nc cl lu ud de e i in nt t m ma ai in n(i in nt t a ar rg gc c, c ch ha ar r* a ar rg gv v[]) { /* ... */ } Because the D Dr ri iv ve er r namespace is used exclusively by m ma ai in n(), I placed it in m ma ai in n.c c. Alterna- tively, I could have factored it out as d dr ri iv ve er r.h h and #i in nc cl lu ud de ed it. For a larger system, it is usually worthwhile organizing things so that the driver has fewer direct dependencies. Often, is it also worth minimizing what is done in m ma ai in n() by having m ma ai in n() call a driver function placed in a separate source file. This is particularly important for code intended to be used as a library. Then, we cannot rely on code in m ma ai in n() and must be prepared to be called from a variety of functions (§9.6[8]). 9.3.2.2 Use of Headers [file.multi.use] The number of headers to use for a program is a function of many factors. Many of these factors have more to do with the way files are handled on your system than with C++. For example, if your editor does not have facilities for looking at several files at the same time, then using many headers becomes less attractive. Similarly, if opening and reading 20 files of 50 lines each is noticeably more time-consuming than reading a single file of 1000 lines, you might think twice before using the multiple-header style for a small project. A word of caution: a dozen headers plus the standard headers for the program’s execution envi- ronment (which can often be counted in the hundreds) are usually manageable. However, if you partition the declarations of a large program into the logically minimal-sized headers (putting each structure declaration in its own file, etc.), you can easily get an unmanageable mess of hundreds of files even for minor projects. I find that excessive. For large projects, multiple headers are unavoidable. In such projects, hundreds of files (not counting standard headers) are the norm. The real confusion starts when they start to be counted in the thousands. At that scale, the basic techniques discussed here still apply, but their management becomes a Herculean task. Remember that for realistically-sized programs, the single-header style is not an option. Such programs will have multiple headers. The choice between the two styles of organization occurs (repeatedly) for the parts that make up the program. The single-header style and the multiple-header style are not really alternatives to each other. They are complementary techniques that must be considered whenever a significant module is designed and must be reconsidered as a system evolves. It’s crucial to remember that one interface doesn’t serve all equally well. It is usually worthwhile to distinguish between the implementers’ interface and the users’ interface. In addition, many larger systems are structured so that providing a simple interface for the majority of users and a more extensive interface for expert users is a good idea. The expert users’ interfaces (‘‘complete interfaces’’) tend to #i in nc cl lu ud de e many more features than the average user would ever want to know about. In fact, the average users’ interface can often be identified by eliminating features that require the inclusion of headers that define facilities that would be unknown to the average user. The term ‘‘average user’’ is not derogatory. In the fields in which I don’t have to be an expert, I strongly prefer to be an average user. In that way, I minimize hassles. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.216 Source Files and Programs Chapter 9 9.3.3 Include Guards [file.guards] The idea of the multiple-header approach is to represent each logical module as a consistent, self- contained unit. Viewed from the program as a whole, many of the declarations needed to make each logical module complete are redundant. For larger programs, such redundancy can lead to errors, as a header containing class definitions or inline functions gets #i in nc cl lu ud de ed twice in the same compilation unit (§9.2.3). We have two choices. We can [1] reorganize our program to remove the redundancy, or [2] find a way to allow repeated inclusion of headers. The first approach ± which led to the final version of the calculator ± is tedious and impractical for realistically-sized programs. We also need that redundancy to make the individual parts of the pro- gram comprehensible in isolation. The benefits of an analysis of redundant #i in nc cl lu ud de es and the resulting simplifications of the pro- gram can be significant both from a logical point of view and by reducing compile times. How- ever, it can rarely be complete, so some method of allowing redundant #i in nc cl lu ud de es must be applied. Preferably, it must be applied systematically, since there is no way of knowing how thorough an analysis a user will find worthwhile. The traditional solution is to insert include guards in headers. For example: / / error.h: #i if fn nd de ef f C CA AL LC C_ _E ER RR RO OR R_ _H H #d de ef fi in ne e C CA AL LC C_ _E ER RR RO OR R_ _H H n na am me es sp pa ac ce e E Er rr ro or r { / / ... } #e en nd di if f / / CALC_ERROR_H The contents of the file between the #i if fn nd de ef f and #e en nd di if f are ignored by the compiler if C CA AL LC C_ _E ER RR RO OR R_ _H H is defined. Thus, the first time e er rr ro or r.h h is seen during a compilation, its con- tents are read and C CA AL LC C_ _E ER RR RO OR R_ _H H is given a value. Should the compiler be presented with e er rr ro or r.h h again during the compilation, the contents are ignored. This is a piece of macro hackery, but it works and it is pervasive in the C and C++ worlds. The standard headers all have include guards. Header files are included in essentially arbitrary contexts, and there is no namespace protection against macro name clashes. Consequently, I choose rather long and ugly names as my include guards. Once people get used to headers and include guards, they tend to include lots of headers directly and indirectly. Even with C++ implementations that optimize the processing of headers, this can be undesirable. It can cause unnecessarily long compile time, and it can bring l lo ot ts s of declarations and macros into scope. The latter might affect the meaning of the program in unpredictable and adverse ways. Headers should be included only when necessary. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 9.4 Programs 217 9.4 Programs [file.programs] A program is a collection of separately compiled units combined by a linker. Every function, object, type, etc., used in this collection must have a unique definition (§4.9, §9.2.3). The program must contain exactly one function called m ma ai in n() (§3.2). The main computation performed by the program starts with the invocation of m ma ai in n() and ends with a return from m ma ai in n(). The i in nt t returned by m ma ai in n() is passed to whatever system invoked m ma ai in n() as the result of the program. This simple story must be elaborated on for programs that contain global variables (§10.4.9) or that throw an uncaught exception (§14.7). 9.4.1 Initialization of Nonlocal Variables [file.nonlocal] In principle, a variable defined outside any function (that is, global, namespace, and class s st ta at ti ic c variables) is initialized before m ma ai in n() is invoked. Such nonlocal variables in a translation unit are initialized in their declaration order (§10.4.9). If such a variable has no explicit initializer, it is by default initialized to the default for its type (§10.4.2). The default initializer value for built-in types and enumerations is 0 0. For example: d do ou ub bl le e x x = 2 2; / / nonlocal variables d do ou ub bl le e y y; d do ou ub bl le e s sq qx x = s sq qr rt t(x x+y y) ; Here, x x and y y are initialized before s sq qx x, so s sq qr rt t(2 2) is called. There is no guaranteed order of initialization of global variables in different translation units. Consequently, it is unwise to create order dependencies between initializers of global variables in different compilation units. In addition, it is not possible to catch an exception thrown by the ini- tializer of a global variable (§14.7). It is generally best to minimize the use of global variables and in particular to limit the use of global variables requiring complicated initialization. Several techniques exist for enforcing an order of initialization of global variables in different translation units. However, none are both portable and efficient. In particular, dynamically linked libraries do not coexist happily with global variables that have complicated dependencies. Often, a function returning a reference is a good alternative to a global variable. For example: i in nt t& u us se e_ _c co ou un nt t() { s st ta at ti ic c i in nt t u uc c = 0 0; r re et tu ur rn n u uc c; } A call u us se e_ _c co ou un nt t() now acts as a global variable except that it is initialized at its first use (§5.5). For example: v vo oi id d f f() { c co ou ut t << ++u us se e_ _c co ou un nt t() ; / / read and increment / / ... } The initialization of nonlocal static variables is controlled by whatever mechanism an The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.218 Source Files and Programs Chapter 9 implementation uses to start up a C++ program. This mechanism is guaranteed to work properly only if m ma ai in n() is executed. Consequently, one should avoid nonlocal variables that require run- time initialization in C++ code intended for execution as a fragment of a non-C++ program. Note that variables initialized by constant expressions (§C.5) cannot depend on the value of objects from other translation units and do not require run-time initialization. Such variables are therefore safe to use in all cases. 9.4.1.1 Program Termination [file.termination] A program can terminate in several ways: ± By returning from m ma ai in n() ± By calling e ex xi it t() ± By calling a ab bo or rt t() ± By throwing an uncaught exception In addition, there are a variety of ill-behaved and implementation-dependent ways of making a pro- gram crash. If a program is terminated using the standard library function e ex xi it t(), the destructors for con- structed static objects are called (§10.4.9, §10.2.4). However, if the program is terminated using the standard library function a ab bo or rt t(), they are not. Note that this implies that e ex xi it t() does not ter- minate a program immediately. Calling e ex xi it t() in a destructor may cause an infinite recursion. The type of e ex xi it t() is v vo oi id d e ex xi it t(i in nt t) ; Like the return value of m ma ai in n() (§3.2), e ex xi it t()’s argument is returned to ‘‘the system’’ as the value of the program. Zero indicates successful completion. Calling e ex xi it t() means that the local variables of the calling function and its callers will not have their destructors invoked. Throwing an exception and catching it ensures that local objects are properly destroyed (§14.4.7). Also, a call of e ex xi it t() terminates the program without giving the caller of the function that called e ex xi it t() a chance to deal with the problem. It is therefore often best to leave a context by throwing an exception and letting a handler decide what to do next. The C (and C++) standard library function a at te ex xi it t() offers the possibility to have code executed at program termination. For example: v vo oi id d m my y_ _c cl le ea an nu up p() ; v vo oi id d s so om me ew wh he er re e() { i if f (a at te ex xi it t(&m my y_ _c cl le ea an nu up p)==0 0) { / / my_cleanup will be called at normal termination } e el ls se e { / / oops: too many atexit functions } } This strongly resembles the automatic invocation of destructors for global variables at program ter- mination (§10.4.9, §10.2.4). Note that an argument to a at te ex xi it t() cannot take arguments or return a The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 9.4.1.1 Program Termination 219 result. Also, there is an implementation-defined limit to the number of atexit functions; a at te ex xi it t() indicates when that limit is reached by returning a nonzero value. These limitations make a at te ex xi it t() less useful than it appears at first glance. The destructor of an object created before a call of a at te ex xi it t(f f) will be invoked after f f is invoked. The destructor of an object created after a call of a at te ex xi it t(f f) will be invoked before f f is invoked. The e ex xi it t(), a ab bo or rt t(), and a at te ex xi it t() functions are declared in . 9.5 Advice [file.advice] [1] Use header files to represent interfaces and to emphasize logical structure; §9.1, §9.3.2. [2] #i in nc cl lu ud de e a header in the source file that implements its functions; §9.3.1. [3] Don’t define global entities with the same name and similar-but-different meanings in differ- ent translation units; §9.2. [4] Avoid non-inline function definitions in headers; §9.2.1. [5] Use #i in nc cl lu ud de e only at global scope and in namespaces; §9.2.1. [6] #i in nc cl lu ud de e only complete declarations; §9.2.1. [7] Use include guards; §9.3.3. [8] #i in nc cl lu ud de e C headers in namespaces to avoid global names; §9.3.2. [9] Make headers self-contained; §9.2.3. [10] Distinguish between users’ interfaces and implementers’ interfaces; §9.3.2. [11] Distinguish between average users’ interfaces and expert users’ interfaces; §9.3.2. [12] Avoid nonlocal objects that require run-time initialization in code intended for use as part of non-C++ programs; §9.4.1. 9.6 Exercises [file.exercises] 1. (∗2) Find where the standard library headers are kept on your system. List their names. Are any nonstandard headers kept together with the standard ones? Can any nonstandard headers be #i in nc cl lu ud de ed using the <> notation? 2. (∗2) Where are the headers for nonstandard library ‘‘foundation’’ libraries kept? 3. (∗2.5) Write a program that reads a source file and writes out the names of files #i in nc cl lu ud de ed. Indent file names to show files #i in nc cl lu ud de ed d by included files. Try this program on some real source files (to get an idea of the amount of information included). 4. (∗3) Modify the program from the previous exercise to print the number of comment lines, the number of non-comment lines, and the number of non-comment, whitespace-separated words for each file #i in nc cl lu ud de ed. 5. (∗2.5) An external include guard is a construct that tests outside the file it is guarding and i in nc cl lu ud de es only once per compilation. Define such a construct, devise a way of testing it, and dis- cuss its advantages and disadvantages compared to the include guards described in §9.3.3. Is there any significant run-time advantage to external include guards on your system. 6. (∗3) How is dynamic linking achieved on your system. What restrictions are placed on dynami- cally linked code? What requirements are placed on code for it to be dynamically linked? The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.220 Source Files and Programs Chapter 9 7. (∗3) Open and read 100 files containing 1500 characters each. Open and read one file contain- ing 150,000 characters. Hint: See example in §21.5.1. Is there a performance difference? What is the highest number of files that can be simultaneously open on your system? Consider these questions in relation to the use of #i in nc cl lu ud de e files. 8. (∗2) Modify the desk calculator so that it can be invoked from m ma ai in n() or from other functions as a simple function call. 9. (∗2) Draw the ‘‘module dependency diagrams’’ (§9.3.2) for the version of the calculator that used e er rr ro or r() instead of exceptions (§8.2.2). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Part II Abstraction Mechanisms This part describes C++’s facilities for defining and using new types. Techniques com- monly called object-oriented programming and generic programming are presented. Chapters 10 Classes 11 Operator Overloading 12 Derived Classes 13 Templates 14 Exception Handling 15 Class Hierarchies The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.222 Abstraction Mechanisms Part II ‘‘... there is nothing more difficult to carry out, nor more doubtful of success, nor more dangerous to handle, than to initiate a new order of things. For the reformer makes enemies of all those who profit by the old order, and only lukewarm defenders in all those who would profit by the new order...’’ Ð Nicollo Machiavelli (‘‘The Prince’’ §vi) The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 10 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Classes Those types are not "abstract"; they are as real as int and float. ± Doug McIlroy Concepts and classes Ð class members Ð access control Ð constructors Ð s st ta at ti ic c members Ð default copy Ð c co on ns st t member functions Ð t th hi is s Ð s st tr ru uc ct ts Ð in-class func- tion definition Ð concrete classes Ð member functions and helper functions Ð over- loaded operators Ð use of concrete classes Ð destructors Ð default construction Ð local variables Ð user-defined copy Ð n ne ew w and d de el le et te e Ð member objects Ð arrays Ð static storage Ð temporary variables Ð unions Ð advice Ð exercises. 10.1 Introduction [class.intro] The aim of the C++ class concept is to provide the programmer with a tool for creating new types that can be used as conveniently as the built-in types. In addition, derived classes (Chapter 12) and templates (Chapter 13) provide ways of organizing related classes that allow the programmer to take advantage of their relationships. A type is a concrete representation of a concept. For example, the C++ built-in type f fl lo oa at t with its operations +, -, *, etc., provides a concrete approximation of the mathematical concept of a real number. A class is a user-defined type. We design a new type to provide a definition of a concept that has no direct counterpart among the built-in types. For example, we might provide a type T Tr ru un nk k_ _l li in ne e in a program dealing with telephony, a type E Ex xp pl lo os si io on n for a videogame, or a type l li is st t

for a text-processing program. A program that provides types that closely match the concepts of the application tends to be easier to understand and easier to modify than a program that does not. A well-chosen set of user-defined types makes a program more concise. In addition, it makes many sorts of code analysis feasible. In particular, it enables the compiler to detect illegal uses of objects that would otherwise remain undetected until the program is thoroughly tested. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.224 Classes Chapter 10 The fundamental idea in defining a new type is to separate the incidental details of the imple- mentation (e.g., the layout of the data used to store an object of the type) from the properties essen- tial to the correct use of it (e.g., the complete list of functions that can access the data). Such a sep- aration is best expressed by channeling all uses of the data structure and internal housekeeping rou- tines through a specific interface. This chapter focuses on relatively simple ‘‘concrete’’ user-defined types that logically don’t dif- fer much from built-in types. Ideally, such types should not differ from built-in types in the way they are used, only in the way they are created. 10.2 Classes [class.class] A class is a user-defined type. This section introduces the basic facilities for defining a class, creat- ing objects of a class, and manipulating such objects. 10.2.1 Member Functions [class.member] Consider implementing the concept of a date using a s st tr ru uc ct t to define the representation of a D Da at te e and a set of functions for manipulating variables of this type: s st tr ru uc ct t D Da at te e { / / representation i in nt t d d, m m, y y; }; v vo oi id d i in ni it t_ _d da at te e(D Da at te e& d d, i in nt t, i in nt t, i in nt t) ; / / initialize d v vo oi id d a ad dd d_ _y ye ea ar r(D Da at te e& d d, i in nt t n n) ; / / add n years to d v vo oi id d a ad dd d_ _m mo on nt th h(D Da at te e& d d, i in nt t n n) ; / / add n months to d v vo oi id d a ad dd d_ _d da ay y(D Da at te e& d d, i in nt t n n) ; / / add n days to d There is no explicit connection between the data type and these functions. Such a connection can be established by declaring the functions as members: s st tr ru uc ct t D Da at te e { i in nt t d d, m m, y y; v vo oi id d i in ni it t(i in nt t d dd d, i in nt t m mm m, i in nt t y yy y) ; / / initialize v vo oi id d a ad dd d_ _y ye ea ar r(i in nt t n n) ; / / add n years v vo oi id d a ad dd d_ _m mo on nt th h(i in nt t n n) ; / / add n months v vo oi id d a ad dd d_ _d da ay y(i in nt t n n) ; / / add n days }; Functions declared within a class definition (a s st tr ru uc ct t is a kind of class; §10.2.8) are called member functions and can be invoked only for a specific variable of the appropriate type using the standard syntax for structure member access. For example: D Da at te e m my y_ _b bi ir rt th hd da ay y; v vo oi id d f f() { D Da at te e t to od da ay y; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.2.1 Member Functions 225 t to od da ay y.i in ni it t(1 16 6,1 10 0,1 19 99 96 6) ; m my y_ _b bi ir rt th hd da ay y.i in ni it t(3 30 0,1 12 2,1 19 95 50 0) ; D Da at te e t to om mo or rr ro ow w = t to od da ay y; t to om mo or rr ro ow w.a ad dd d_ _d da ay y(1 1) ; / / ... } Because different structures can have member functions with the same name, we must specify the structure name when defining a member function: v vo oi id d D Da at te e: :i in ni it t(i in nt t d dd d, i in nt t m mm m, i in nt t y yy y) { d d = d dd d; m m = m mm m; y y = y yy y; } In a member function, member names can be used without explicit reference to an object. In that case, the name refers to that member of the object for which the function was invoked. For exam- ple, when D Da at te e: :i in ni it t() is invoked for t to od da ay y, m m=m mm m assigns to t to od da ay y.m m. On the other hand, when D Da at te e: :i in ni it t() is invoked for m my y_ _b bi ir rt th hd da ay y, m m=m mm m assigns to m my y_ _b bi ir rt th hd da ay y.m m. A class member function always ‘‘knows’’ for which object it was invoked. The construct c cl la as ss s X X { ... }; is called a class definition because it defines a new type. For historical reasons, a class definition is often referred to as a class declaration. Also, like declarations that are not definitions, a class defi- nition can be replicated in different source files using #i in nc cl lu ud de e without violating the one-definition rule (§9.2.3). 10.2.2 Access Control [class.access] The declaration of D Da at te e in the previous subsection provides a set of functions for manipulating a D Da at te e. However, it does not specify that those functions should be the only ones to depend directly on D Da at te e’s representation and the only ones to directly access objects of class D Da at te e. This restriction can be expressed by using a c cl la as ss s instead of a s st tr ru uc ct t: c cl la as ss s D Da at te e { i in nt t d d, m m, y y; p pu ub bl li ic c: v vo oi id d i in ni it t(i in nt t d dd d, i in nt t m mm m, i in nt t y yy y) ; / / initialize v vo oi id d a ad dd d_ _y ye ea ar r(i in nt t n n) ; / / add n years v vo oi id d a ad dd d_ _m mo on nt th h(i in nt t n n) ; / / add n months v vo oi id d a ad dd d_ _d da ay y(i in nt t n n) ; / / add n days }; The p pu ub bl li ic c label separates the class body into two parts. The names in the first, private, part can be used only by member functions. The second, public, part constitutes the public interface to objects The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.226 Classes Chapter 10 of the class. A s st tr ru uc ct t is simply a c cl la as ss s whose members are public by default (§10.2.8); member functions can be defined and used exactly as before. For example: i in nl li in ne e v vo oi id d D Da at te e: :a ad dd d_ _y ye ea ar r(i in nt t n n) { y y += n n; } However, nonmember functions are barred from using private members. For example: v vo oi id d t ti im me ew wa ar rp p(D Da at te e& d d) { d d.y y -= 2 20 00 0; / / error: Date::y is private } There are several benefits to be obtained from restricting access to a data structure to an explicitly declared list of functions. For example, any error causing a D Da at te e to take on an illegal value (for example, December 36, 1985) must be caused by code in a member function. This implies that the first stage of debugging ± localization ± is completed before the program is even run. This is a special case of the general observation that any change to the behavior of the type D Da at te e can and must be effected by changes to its members. In particular, if we change the representation of a class, we need only change the member functions to take advantage of the new representation. User code directly depends only on the public interface and need not be rewritten (although it may need to be recompiled). Another advantage is that a potential user need examine only the definition of the member functions in order to learn to use a class. The protection of private data relies on restriction of the use of the class member names. It can therefore be circumvented by address manipulation and explicit type conversion. But this, of course, is cheating. C++ protects against accident rather than deliberate circumvention (fraud). Only hardware can protect against malicious use of a general-purpose language, and even that is hard to do in realistic systems. The i in ni it t() function was added partially because it is generally useful to have a function that sets the value of an object and partly because making the data private forces us to provide it. 10.2.3 Constructors [class.ctor] The use of functions such as i in ni it t() to provide initialization for class objects is inelegant and error- prone. Because it is nowhere stated that an object must be initialized, a programmer can forget to do so ± or do so twice (often with equally disastrous results). A better approach is to allow the pro- grammer to declare a function with the explicit purpose of initializing objects. Because such a function constructs values of a given type, it is called a constructor. A constructor is recognized by having the same name as the class itself. For example: c cl la as ss s D Da at te e { / / ... D Da at te e(i in nt t, i in nt t, i in nt t) ; / / constructor }; When a class has a constructor, all objects of that class will be initialized. If the constructor requires arguments, these arguments must be supplied: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.2.3 Constructors 227 D Da at te e t to od da ay y = D Da at te e(2 23 3,6 6,1 19 98 83 3) ; D Da at te e x xm ma as s(2 25 5,1 12 2,1 19 99 90 0) ; / / abbreviated form D Da at te e m my y_ _b bi ir rt th hd da ay y; / / error: initializer missing D Da at te e r re el le ea as se e1 1_ _0 0(1 10 0,1 12 2) ; / / error: 3rd argument missing It is often nice to provide several ways of initializing a class object. This can be done by providing several constructors. For example: c cl la as ss s D Da at te e { i in nt t d d, m m, y y; p pu ub bl li ic c: / / ... D Da at te e(i in nt t, i in nt t, i in nt t) ; / / day, month, year D Da at te e(i in nt t, i in nt t) ; / / day, month, today’s year D Da at te e(i in nt t) ; / / day, today’s month and year D Da at te e() ; / / default Date: today D Da at te e(c co on ns st t c ch ha ar r*) ; / / date in string representation }; Constructors obey the same overloading rules as do other functions (§7.4). As long as the construc- tors differ sufficiently in their argument types, the compiler can select the correct one for each use: D Da at te e t to od da ay y(4 4) ; D Da at te e j ju ul ly y4 4("J Ju ul ly y 4 4, 1 19 98 83 3") ; D Da at te e g gu uy y("5 5 N No ov v") ; D Da at te e n no ow w; / / default initialized as today The proliferation of constructors in the D Da at te e example is typical. When designing a class, a pro- grammer is always tempted to add features just because somebody might want them. It takes more thought to carefully decide what features are really needed and to include only those. However, that extra thought typically leads to smaller and more comprehensible programs. One way of reducing the number of related functions is to use default arguments (§7.5). In the D Da at te e, each argu- ment can be given a default value interpreted as ‘‘pick the default: t to od da ay y.’’ c cl la as ss s D Da at te e { i in nt t d d, m m, y y; p pu ub bl li ic c: D Da at te e(i in nt t d dd d =0 0, i in nt t m mm m =0 0, i in nt t y yy y =0 0) ; / / ... }; D Da at te e: :D Da at te e(i in nt t d dd d, i in nt t m mm m, i in nt t y yy y) { d d = d dd d ? d dd d : t to od da ay y.d d; m m = m mm m ? m mm m : t to od da ay y.m m; y y = y yy y ? y yy y : t to od da ay y.y y; / / check that the Date is valid } When an argument value is used to indicate ‘‘pick the default,’’ the value chosen must be outside the set of possible values for the argument. For d da ay y and m mo on nt th h, this is clearly so, but for y ye ea ar r, zero The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.228 Classes Chapter 10 may not be an obvious choice. Fortunately, there is no year zero on the European calendar; 1AD (y ye ea ar r==1 1) comes immediately after 1BC (y ye ea ar r==-1 1). 10.2.4 Static Members [class.static] The convenience of a default value for D Da at te es was bought at the cost of a significant hidden prob- lem. Our D Da at te e class became dependent on the global variable t to od da ay y. This D Da at te e class can be used only in a context in which t to od da ay y is defined and correctly used by every piece of code. This is the kind of constraint that causes a class to be useless outside the context in which it was first written. Users get too many unpleasant surprises trying to use such context-dependent classes, and mainte- nance becomes messy. Maybe ‘‘just one little global variable’’ isn’t too unmanageable, but that style leads to code that is useless except to its original programmer. It should be avoided. Fortunately, we can get the convenience without the encumbrance of a publicly accessible glo- bal variable. A variable that is part of a class, yet is not part of an object of that class, is called a s st ta at ti ic c member. There is exactly one copy of a s st ta at ti ic c member instead of one copy per object, as for ordinary non-s st ta at ti ic c members. Similarly, a function that needs access to members of a class, yet doesn’t need to be invoked for a particular object, is called a s st ta at ti ic c member function. Here is a redesign that preserves the semantics of default constructor values for D Da at te e without the problems stemming from reliance on a global: c cl la as ss s D Da at te e { i in nt t d d, m m, y y; s st ta at ti ic c D Da at te e d de ef fa au ul lt t_ _d da at te e; p pu ub bl li ic c: D Da at te e(i in nt t d dd d =0 0, i in nt t m mm m =0 0, i in nt t y yy y =0 0) ; / / ... s st ta at ti ic c v vo oi id d s se et t_ _d de ef fa au ul lt t(i in nt t, i in nt t, i in nt t) ; }; We can now define the D Da at te e constructor like this: D Da at te e: :D Da at te e(i in nt t d dd d, i in nt t m mm m, i in nt t y yy y) { d d = d dd d ? d dd d : d de ef fa au ul lt t_ _d da at te e.d d; m m = m mm m ? m mm m : d de ef fa au ul lt t_ _d da at te e.m m; y y = y yy y ? y yy y : d de ef fa au ul lt t_ _d da at te e.y y; / / check that the Date is valid } We can change the default date when appropriate. A static member can be referred to like any other member. In addition, a static member can be referred to without mentioning an object. Instead, its name is qualified by the name of its class. For example: v vo oi id d f f() { D Da at te e: :s se et t_ _d de ef fa au ul lt t(4 4,5 5,1 19 94 45 5) ; } Static members ± both function and data members ± must be defined somewhere. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.2.4 Static Members 229 D Da at te e D Da at te e: :d de ef fa au ul lt t_ _d da at te e(1 16 6,1 12 2,1 17 77 70 0) ; v vo oi id d D Da at te e: :s se et t_ _d de ef fa au ul lt t(i in nt t d d, i in nt t m m, i in nt t y y) { D Da at te e: :d de ef fa au ul lt t_ _d da at te e = D Da at te e(d d,m m,y y) ; } Now the default value is Beethoven’s birth date ± until someone decides otherwise. Note that D Da at te e() serves as a notation for the value of D Da at te e: :d de ef fa au ul lt t_ _d da at te e. For example: D Da at te e c co op py y_ _o of f_ _d de ef fa au ul lt t_ _d da at te e = D Da at te e() ; Consequently, we don’t need a separate function for reading the default date. 10.2.5 Copying Class Objects [class.default.copy] By default, class objects can be copied. In particular, a class object can be initialized with a copy of another object of the same class. This can be done even where constructors have been declared. For example: D Da at te e d d = t to od da ay y; / / initialization by copy By default, the copy of a class object is a copy of each member. If that default is not the behavior wanted for a class X X, a more appropriate behavior can be provided by defining a copy constructor, X X: :X X(c co on ns st t X X&). This is discussed further in §10.4.4.1. Similarly, class objects can by default be copied by assignment. For example: v vo oi id d f f(D Da at te e& d d) { d d = t to od da ay y; } Again, the default semantics is memberwise copy. If that is not the right choice for a class X X, the user can define an appropriate assignment operator (§10.4.4.1). 10.2.6 Constant Member Functions [class.constmem] The D Da at te e defined so far provides member functions for giving a D Da at te e a value and changing it. Unfortunately, we didn’t provide a way of examining the value of a D Da at te e. This problem can easily be remedied by adding functions for reading the day, month, and year: c cl la as ss s D Da at te e { i in nt t d d, m m, y y; p pu ub bl li ic c: i in nt t d da ay y() c co on ns st t { r re et tu ur rn n d d; } i in nt t m mo on nt th h() c co on ns st t { r re et tu ur rn n m m; } i in nt t y ye ea ar r() c co on ns st t; / / ... }; Note the c co on ns st t after the (empty) argument list in the function declarations. It indicates that these functions do not modify the state of a D Da at te e. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.230 Classes Chapter 10 Naturally, the compiler will catch accidental attempts to violate this promise. For example: i in nl li in ne e i in nt t D Da at te e: :y ye ea ar r() c co on ns st t { r re et tu ur rn n y y++; / / error: attempt to change member value in const function } When a c co on ns st t member function is defined outside its class, the c co on ns st t suffix is required: i in nl li in ne e i in nt t D Da at te e: :y ye ea ar r() c co on ns st t / / correct { r re et tu ur rn n y y; } i in nl li in ne e i in nt t D Da at te e: :y ye ea ar r() / / error: const missing in member function type { r re et tu ur rn n y y; } In other words, the c co on ns st t is part of the type of D Da at te e: :d da ay y() and D Da at te e: :y ye ea ar r(). A c co on ns st t member function can be invoked for both c co on ns st t and non-c co on ns st t objects, whereas a non- c co on ns st t member function can be invoked only for non-c co on ns st t objects. For example: v vo oi id d f f(D Da at te e& d d, c co on ns st t D Da at te e& c cd d) { i in nt t i i = d d.y ye ea ar r() ; / / ok d d.a ad dd d_ _y ye ea ar r(1 1) ; / / ok i in nt t j j = c cd d.y ye ea ar r() ; / / ok c cd d.a ad dd d_ _y ye ea ar r(1 1) ; / / error: cannot change value of const cd } 10.2.7 Self-Reference [class.this] The state update functions a ad dd d_ _y ye ea ar r(), a ad dd d_ _m mo on nt th h(), and a ad dd d_ _d da ay y() were defined not to return values. For such a set of related update functions, it is often useful to return a reference to the updated object so that the operations can be chained. For example, we would like to write v vo oi id d f f(D Da at te e& d d) { / / ... d d.a ad dd d_ _d da ay y(1 1).a ad dd d_ _m mo on nt th h(1 1).a ad dd d_ _y ye ea ar r(1 1) ; / / ... } to add a day, a month, and a year to d d. To do this, each function must be declared to return a refer- ence to a D Da at te e: c cl la as ss s D Da at te e { / / ... The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.2.7 Self-Reference 231 D Da at te e& a ad dd d_ _y ye ea ar r(i in nt t n n) ; / / add n years D Da at te e& a ad dd d_ _m mo on nt th h(i in nt t n n) ; / / add n months D Da at te e& a ad dd d_ _d da ay y(i in nt t n n) ; / / add n days }; Each (nonstatic) member function knows what object it was invoked for and can explictly refer to it. For example: D Da at te e& D Da at te e: :a ad dd d_ _y ye ea ar r(i in nt t n n) { i if f (d d==2 29 9 && m m==2 2 && !l le ea ap py ye ea ar r(y y+n n)) { / / beware of February 29 d d = 1 1; m m = 3 3; } y y += n n; r re et tu ur rn n *t th hi is s; } The expression *t th hi is s refers to the object for which a member function is invoked. It is equivalent to Simula’s T TH HI IS S and Smalltalk’s s se el lf f. In a nonstatic member function, the keyword t th hi is s is a pointer to the object for which the func- tion was invoked. In a non-c co on ns st t member function of class X X, the type of t th hi is s is X X *c co on ns st t. The c co on ns st t makes it clear that the user is not supposed to change the value of t th hi is s. In a c co on ns st t member function of class X X, the type of t th hi is s is c co on ns st t X X *c co on ns st t to prevent modification of the object itself (see also §5.4.1). Most uses of t th hi is s are implicit. In particular, every reference to a nonstatic member from within a class relies on an implicit use of t th hi is s to get the member of the appropriate object. For example, the a ad dd d_ _y ye ea ar r function could equivalently, but tediously, have been defined like this: D Da at te e& D Da at te e: :a ad dd d_ _y ye ea ar r(i in nt t n n) { i if f (t th hi is s->d d==2 29 9 && t th hi is s->m m==2 2 && !l le ea ap py ye ea ar r(t th hi is s->y y+n n)) { t th hi is s->d d = 1 1; t th hi is s->m m = 3 3; } t th hi is s->y y += n n; r re et tu ur rn n *t th hi is s; } One common explicit use of t th hi is s is in linked-list manipulation (e.g., §24.3.7.4). 10.2.7.1 Physical and Logical Constness [class.const] Occasionally, a member function is logically c co on ns st t, but it still needs to change the value of a mem- ber. To a user, the function appears not to change the state of its object. However, some detail that the user cannot directly observe is updated. This is often called logical constness. For example, the D Da at te e class might have a function returning a string representation that a user could use for out- put. Constructing this representation could be a relatively expensive operation. Therefore, it would make sense to keep a copy so that repeated requests would simply return the copy, unless the The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.232 Classes Chapter 10 D Da at te e’s value had been changed. Caching values like that is more common for more complicated data structures, but let’s see how it can be achieved for a D Da at te e: c cl la as ss s D Da at te e { b bo oo ol l c ca ac ch he e_ _v va al li id d; s st tr ri in ng g c ca ac ch he e; v vo oi id d c co om mp pu ut te e_ _c ca ac ch he e_ _v va al lu ue e() ; / / fill cache / / ... p pu ub bl li ic c: / / ... s st tr ri in ng g s st tr ri in ng g_ _r re ep p() c co on ns st t; / / string representation }; From a user’s point of view, s st tr ri in ng g_ _r re ep p doesn’t change the state of its D Da at te e, so it clearly should be a c co on ns st t member function. On the other hand, the cache needs to be filled before it can be used. This can be achieved through brute force: s st tr ri in ng g D Da at te e: :s st tr ri in ng g_ _r re ep p() c co on ns st t { i if f (c ca ac ch he e_ _v va al li id d == f fa al ls se e) { D Da at te e* t th h = c co on ns st t_ _c ca as st t(t th hi is s) ; / / cast away const t th h->c co om mp pu ut te e_ _c ca ac ch he e_ _v va al lu ue e() ; t th h->c ca ac ch he e_ _v va al li id d = t tr ru ue e; } r re et tu ur rn n c ca ac ch he e; } That is, the c co on ns st t_ _c ca as st t operator (§15.4.2.1) is used to obtain a pointer of type D Da at te e* to t th hi is s. This is hardly elegant, and it is not guaranteed to work when applied to an object that was originally declared as a c co on ns st t. For example: D Da at te e d d1 1; c co on ns st t D Da at te e d d2 2; s st tr ri in ng g s s1 1 = d d1 1.s st tr ri in ng g_ _r re ep p() ; s st tr ri in ng g s s2 2 = d d2 2.s st tr ri in ng g_ _r re ep p() ; / / undefined behavior In the case of d d1 1, s st tr ri in ng g_ _r re ep p() simply casts back to d d1 1’s original type so that the call will work. However, d d2 2 was defined as a c co on ns st t and the implementation could have applied some form of memory protection to ensure that its value wasn’t corrupted. Consequently, d d2 2.s st tr ri in ng g_ _r re ep p() is not guaranteed to give a single predictable result on all implementations. 10.2.7.2 Mutable [class.mutable] The explicit type conversion ‘‘casting away c co on ns st t’’ and its consequent implementation-dependent behavior can be avoided by declaring the data involved in the cache management to be m mu ut ta ab bl le e: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.2.7.2 Mutable 233 c cl la as ss s D Da at te e { m mu ut ta ab bl le e b bo oo ol l c ca ac ch he e_ _v va al li id d; m mu ut ta ab bl le e s st tr ri in ng g c ca ac ch he e; v vo oi id d c co om mp pu ut te e_ _c ca ac ch he e_ _v va al lu ue e() c co on ns st t; / / fill (mutable) cache / / ... p pu ub bl li ic c: / / ... s st tr ri in ng g s st tr ri in ng g_ _r re ep p() c co on ns st t; / / string representation }; The storage specifier m mu ut ta ab bl le e specifies that a member should be stored in a way that allows updat- ing ± even when it is a member of a c co on ns st t object. In other words, m mu ut ta ab bl le e means ‘‘can never be c co on ns st t.’’ This can be used to simplify the definition of s st tr ri in ng g_ _r re ep p(): s st tr ri in ng g D Da at te e: :s st tr ri in ng g_ _r re ep p() c co on ns st t { i if f (!c ca ac ch he e_ _v va al li id d) { c co om mp pu ut te e_ _c ca ac ch he e_ _v va al lu ue e() ; c ca ac ch he e_ _v va al li id d = t tr ru ue e; } r re et tu ur rn n c ca ac ch he e; } and makes reasonable uses of s st tr ri in ng g_ _r re ep p() valid. For example: D Da at te e d d3 3; c co on ns st t D Da at te e d d4 4; s st tr ri in ng g s s3 3 = d d3 3.s st tr ri in ng g_ _r re ep p() ; s st tr ri in ng g s s4 4 = d d4 4.s st tr ri in ng g_ _r re ep p() ; / / ok! Declaring members m mu ut ta ab bl le e is most appropriate when (only) part of a representation is allowed to change. If most of an object changes while the object remains logically c co on ns st t, it is often better to place the changing data in a separate object and access it indirectly. If that technique is used, the string-with-cache example becomes: s st tr ru uc ct t c ca ac ch he e { b bo oo ol l v va al li id d; s st tr ri in ng g r re ep p; }; c cl la as ss s D Da at te e { c ca ac ch he e* c c; / / initialize in constructor (§10.4.6) v vo oi id d c co om mp pu ut te e_ _c ca ac ch he e_ _v va al lu ue e() c co on ns st t; / / fill what cache refers to / / ... p pu ub bl li ic c: / / ... s st tr ri in ng g s st tr ri in ng g_ _r re ep p() c co on ns st t; / / string representation }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.234 Classes Chapter 10 s st tr ri in ng g D Da at te e: :s st tr ri in ng g_ _r re ep p() c co on ns st t { i if f (!c c->v va al li id d) { c co om mp pu ut te e_ _c ca ac ch he e_ _v va al lu ue e() ; c c->v va al li id d = t tr ru ue e; } r re et tu ur rn n c c->r re ep p; } The programming techniques that support a cache generalize to various forms of lazy evaluation. 10.2.8 Structures and Classes [class.struct] By definition, a s st tr ru uc ct t is a class in which members are by default public; that is, s st tr ru uc ct t s s { ... is simply shorthand for c cl la as ss s s s { p pu ub bl li ic c: ... The access specifier p pr ri iv va at te e: can be used to say that the members following are private, just as p pu ub bl li ic c: says that the members following are public. Except for the different names, the following declarations are equivalent: c cl la as ss s D Da at te e1 1 { i in nt t d d, m m, y y; p pu ub bl li ic c: D Da at te e1 1(i in nt t d dd d, i in nt t m mm m, i in nt t y yy y) ; v vo oi id d a ad dd d_ _y ye ea ar r(i in nt t n n) ; / / add n years }; s st tr ru uc ct t D Da at te e2 2 { p pr ri iv va at te e: i in nt t d d, m m, y y; p pu ub bl li ic c: D Da at te e2 2(i in nt t d dd d, i in nt t m mm m, i in nt t y yy y) ; v vo oi id d a ad dd d_ _y ye ea ar r(i in nt t n n) ; / / add n years }; Which style you use depends on circumstances and taste. I usually prefer to use s st tr ru uc ct t for classes that have all data public. I think of such classes as ‘‘not quite proper types, just data structures.’’ Constructors and access functions can be quite useful even for such structures, but as a shorthand rather than guarantors of properties of the type (invariants, see §24.3.7.1). It is not a requirement to declare data first in a class. In fact, it often makes sense to place data members last to emphasize the functions providing the public user interface. For example: c cl la as ss s D Da at te e3 3 { p pu ub bl li ic c: D Da at te e3 3(i in nt t d dd d, i in nt t m mm m, i in nt t y yy y) ; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.2.8 Structures and Classes 235 v vo oi id d a ad dd d_ _y ye ea ar r(i in nt t n n) ; / / add n years p pr ri iv va at te e: i in nt t d d, m m, y y; }; In real code, where both the public interface and the implementation details typically are more extensive than in tutorial examples, I usually prefer the style used for D Da at te e3 3. Access specifiers can be used many times in a single class declaration. For example: c cl la as ss s D Da at te e4 4 { p pu ub bl li ic c: D Da at te e4 4(i in nt t d dd d, i in nt t m mm m, i in nt t y yy y) ; p pr ri iv va at te e: i in nt t d d, m m, y y; p pu ub bl li ic c: v vo oi id d a ad dd d_ _y ye ea ar r(i in nt t n n) ; / / add n years }; Having more than one public section, as in D Da at te e4 4, tends to be messy. So does having more than one private section. However, allowing many access specifiers in a class is useful for machine- generated code. 10.2.9 In-Class Function Definitions [class.inline] A member function defined within the class definition ± rather than simply declared there ± is taken to be an inline member function. That is, in-class definition of member functions is for small, frequently-used functions. Like the class definition it is part of, a member function defined in-class can be replicated in several translation units using #i in nc cl lu ud de e. Like the class itself, its meaning must be the same wherever it is used (§9.2.3). The style of placing the definition of data members last in a class can lead to a minor problem with public inline functions that refer to the representation. Consider: c cl la as ss s D Da at te e { / / potentially confusing p pu ub bl li ic c: i in nt t d da ay y() c co on ns st t { r re et tu ur rn n d d; } / / return Date::d / / ... p pr ri iv va at te e: i in nt t d d, m m, y y; }; This is perfectly good C++ code because a member function declared within a class can refer to every member of the class as if the class were completely defined before the member function bod- ies were considered. However, this can confuse human readers. Consequently, I usually either place the data first or define the inline member functions after the class itself. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.236 Classes Chapter 10 c cl la as ss s D Da at te e { p pu ub bl li ic c: i in nt t d da ay y() c co on ns st t; / / ... p pr ri iv va at te e: i in nt t d d, m m, y y; }; i in nl li in ne e i in nt t D Da at te e: :d da ay y() c co on ns st t { r re et tu ur rn n d d; } 10.3 Efficient User-Defined Types [class.concrete] The previous section discussed bits and pieces of the design of a D Da at te e class in the context of intro- ducing the basic language features for defining classes. Here, I reverse the emphasis and discuss the design of a simple and efficient D Da at te e class and show how the language features support this design. Small, heavily-used abstractions are common in many applications. Examples are Latin charac- ters, Chinese characters, integers, floating-point numbers, complex numbers, points, pointers, coor- dinates, transforms, (pointer,offset) pairs, dates, times, ranges, links, associations, nodes, (value,unit) pairs, disk locations, source code locations, B BC CD D characters, currencies, lines, rectan- gles, scaled fixed-point numbers, numbers with fractions, character strings, vectors, and arrays. Every application uses several of these. Often, a few of these simple concrete types are used heav- ily. A typical application uses a few directly and many more indirectly from libraries. C++ and other programming languages directly support a few of these abstractions. However, most are not, and cannot be, supported directly because there are too many of them. Furthermore, the designer of a general-purpose programming language cannot foresee the detailed needs of every application. Consequently, mechanisms must be provided for the user to define small concrete types. Such types are called concrete types or concrete classes to distinguish them from abstract classes (§12.3) and classes in class hierarchies (§12.2.4, §12.4). It was an explicit aim of C++ to support the definition and efficient use of such user-defined data types very well. They are a foundation of elegant programming. As usual, the simple and mundane is statistically far more significant than the complicated and sophisticated. In this light, let us build a better date class: c cl la as ss s D Da at te e { p pu ub bl li ic c: / / public interface: e en nu um m M Mo on nt th h { j ja an n=1 1, f fe eb b, m ma ar r, a ap pr r, m ma ay y, j ju un n, j ju ul l, a au ug g, s se ep p, o oc ct t, n no ov v, d de ec c }; c cl la as ss s B Ba ad d_ _d da at te e { }; / / exception class D Da at te e(i in nt t d dd d =0 0, M Mo on nt th h m mm m =M Mo on nt th h(0 0) , i in nt t y yy y =0 0) ; / / 0 means ‘‘pick a default’’ / / functions for examining the Date: i in nt t d da ay y() c co on ns st t; M Mo on nt th h m mo on nt th h() c co on ns st t; i in nt t y ye ea ar r() c co on ns st t; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.3 Efficient User-Defined Types 237 s st tr ri in ng g s st tr ri in ng g_ _r re ep p() c co on ns st t; / / string representation v vo oi id d c ch ha ar r_ _r re ep p(c ch ha ar r s s[]) c co on ns st t; / / C-style string representation s st ta at ti ic c v vo oi id d s se et t_ _d de ef fa au ul lt t(i in nt t, M Mo on nt th h, i in nt t) ; / / functions for changing the Date: D Da at te e& a ad dd d_ _y ye ea ar r(i in nt t n n) ; / / add n years D Da at te e& a ad dd d_ _m mo on nt th h(i in nt t n n) ; / / add n months D Da at te e& a ad dd d_ _d da ay y(i in nt t n n) ; / / add n days p pr ri iv va at te e: i in nt t d d, m m, y y; / / representation s st ta at ti ic c D Da at te e d de ef fa au ul lt t_ _d da at te e; }; This set of operations is fairly typical for a user-defined type: [1] A constructor specifying how objects/variables of the type are to be initialized. [2] A set of functions allowing a user to examine a D Da at te e. These functions are marked c co on ns st t to indicate that they don’t modify the state of the object/variable for which they are called. [3] A set of functions allowing the user to manipulate D Da at te es without actually having to know the details of the representation or fiddle with the intricacies of the semantics. [4] A set of implicitly defined operations to allow D Da at te es to be freely copied. [5] A class, B Ba ad d_ _d da at te e, to be used for reporting errors as exceptions. I defined a M Mo on nt th h type to cope with the problem of remembering, for example, whether the 7th of June is written D Da at te e(6 6,7 7) (American style) or D Da at te e(7 7,6 6) (European style). I also added a mechanism for dealing with default arguments. I considered introducing separate types D Da ay y and Y Ye ea ar r to cope with possible confusion of D Da at te e(1 19 99 95 5,j ju ul l,2 27 7) and D Da at te e(2 27 7,j ju ul l,1 19 99 95 5). However, these types would not be as useful as the M Mo on nt th h type. Almost all such errors are caught at run-time anyway ± the 26th of July year 27 is not a common date in my work. How to deal with historical dates before year 1800 or so is a tricky issue best left to expert historians. Furthermore, the day of the month can’t be properly checked in isolation from its month and year. See §11.7.1 for a way of defining a convenient Y Ye ea ar r type. The default date must be defined as a valid D Da at te e somewhere. For example: D Da at te e D Da at te e: :d de ef fa au ul lt t_ _d da at te e(2 22 2,j ja an n,1 19 90 01 1) ; I omitted the cache technique from §10.2.7.1 as unnecessary for a type this simple. If needed, it can be added as an implementation detail without affecting the user interface. Here is a small ± and contrived ± example of how D Da at te es can be used: v vo oi id d f f(D Da at te e& d d) { D Da at te e l lv vb b_ _d da ay y = D Da at te e(1 16 6,D Da at te e: :d de ec c,d d.y ye ea ar r()) ; i if f (d d.d da ay y()==2 29 9 && d d.m mo on nt th h()==D Da at te e: :f fe eb b) { / / ... } i if f (m mi id dn ni ig gh ht t()) d d.a ad dd d_ _d da ay y(1 1) ; c co ou ut t << "d da ay y a af ft te er r:" << d d+1 1 << ´\ \n n´; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.238 Classes Chapter 10 This assumes that the output operator << and the addition operator + have been declared for D Da at te es. I do that in §10.3.3. Note the D Da at te e: :f fe eb b notation. The function f f() is not a member of D Da at te e, so it must specify that it is referring to D Da at te e’s f fe eb b and not to some other entity. Why is it worthwhile to define a specific type for something as simple as a date? After all, we could define a structure: s st tr ru uc ct t D Da at te e { i in nt t d da ay y, m mo on nt th h, y ye ea ar r; }; and let programmers decide what to do with it. If we did that, though, every user would either have to manipulate the components of D Da at te es directly or provide separate functions for doing so. In effect, the notion of a date would be scattered throughout the system, which would make it hard to understand, document, or change. Inevitably, providing a concept as only a simple structure causes extra work for every user of the structure. Also, even though the D Da at te e type seems simple, it takes some thought to get right. For example, incrementing a D Da at te e must deal with leap years, with the fact that months are of different lengths, and so on (note: §10.6[1]). Also, the day-month-and-year representation is rather poor for many applications. If we decided to change it, we would need to modify only a designated set of func- tions. For example, to represent a D Da at te e as the number of days before or after January 1, 1970, we would need to change only D Da at te e’s member functions (§10.6[2]). 10.3.1 Member Functions [class.memfct] Naturally, an implementation for each member function must be provided somewhere. For exam- ple, here is the definition of D Da at te e’s constructor: D Da at te e: :D Da at te e(i in nt t d dd d, M Mo on nt th h m mm m, i in nt t y yy y) { i if f (y yy y == 0 0) y yy y = d de ef fa au ul lt t_ _d da at te e.y ye ea ar r() ; i if f (m mm m == 0 0) m mm m = d de ef fa au ul lt t_ _d da at te e.m mo on nt th h() ; i if f (d dd d == 0 0) d dd d = d de ef fa au ul lt t_ _d da at te e.d da ay y() ; i in nt t m ma ax x; s sw wi it tc ch h (m mm m) { c ca as se e f fe eb b: m ma ax x = 2 28 8+l le ea ap py ye ea ar r(y yy y) ; b br re ea ak k; c ca as se e a ap pr r: c ca as se e j ju un n: c ca as se e s se ep p: c ca as se e n no ov v: m ma ax x = 3 30 0; b br re ea ak k; c ca as se e j ja an n: c ca as se e m ma ar r: c ca as se e m ma ay y: c ca as se e j ju ul l: c ca as se e a au ug g: c ca as se e o oc ct t: c ca as se e d de ec c: m ma ax x = 3 31 1; b br re ea ak k; d de ef fa au ul lt t: t th hr ro ow w B Ba ad d_ _d da at te e() ; / / someone cheated } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.3.1 Member Functions 239 i if f (d dd d<1 1 || m ma ax x> is defined for D Da at te e: v vo oi id d f fi il ll l(v ve ec ct to or r& a aa a) { w wh hi il le e (c ci in n) { D Da at te e d d; t tr ry y { c ci in n >> d d; } c ca at tc ch h (D Da at te e: :B Ba ad d_ _d da at te e) { / / my error handling c co on nt ti in nu ue e; } a aa a.p pu us sh h_ _b ba ac ck k(d d) ; / / see §3.7.3 } } As is common for such simple concrete types, the definitions of member functions vary between the trivial and the not-too-complicated. For example: i in nl li in ne e i in nt t D Da at te e: :d da ay y() c co on ns st t { r re et tu ur rn n d d; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.240 Classes Chapter 10 D Da at te e& D Da at te e: :a ad dd d_ _m mo on nt th h(i in nt t n n) { i if f (n n==0 0) r re et tu ur rn n *t th hi is s; i if f (n n>0 0) { i in nt t d de el lt ta a_ _y y = n n/1 12 2; i in nt t m mm m = m m+n n%1 12 2; i if f (1 12 2 < m mm m) { / / note: int(dec)==12 d de el lt ta a_ _y y++; m mm m -= 1 12 2; } / / handle the cases where Month(mm) doesn’t have day d y y += d de el lt ta a_ _y y; m m = M Mo on nt th h(m mm m) ; r re et tu ur rn n *t th hi is s; } / / handle negative n r re et tu ur rn n *t th hi is s; } 10.3.2 Helper Functions [class.helper] Typically, a class has a number of functions associated with it that need not be defined in the class itself because they don’t need direct access to the representation. For example: i in nt t d di if ff f(D Da at te e a a, D Da at te e b b) ; / / number of days in the range [a,b) or [b,a) b bo oo ol l l le ea ap py ye ea ar r(i in nt t y y) ; D Da at te e n ne ex xt t_ _w we ee ek kd da ay y(D Da at te e d d) ; D Da at te e n ne ex xt t_ _s sa at tu ur rd da ay y(D Da at te e d d) ; Defining such functions in the class itself would complicate the class interface and increase the number of functions that would potentially need to be examined when a change to the representa- tion was considered. How are such functions ‘‘associated’’ with class D Da at te e? Traditionally, their declarations were simply placed in the same file as the declaration of class D Da at te e, and users who needed D Da at te es would make them all available by including the file that defined the interface (§9.2.1). For example: #i in nc cl lu ud de e "D Da at te e.h h" In addition to using a specific D Da at te e.h h header, or as an alternative, we can make the association explicit by enclosing the class and its helper functions in a namespace (§8.2): n na am me es sp pa ac ce e C Ch hr ro on no o { / / facilities for dealing with time c cl la as ss s D Da at te e { /* ... */}; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.3.2 Helper Functions 241 i in nt t d di if ff f(D Da at te e a a, D Da at te e b b) ; b bo oo ol l l le ea ap py ye ea ar r(i in nt t y y) ; D Da at te e n ne ex xt t_ _w we ee ek kd da ay y(D Da at te e d d) ; D Da at te e n ne ex xt t_ _s sa at tu ur rd da ay y(D Da at te e d d) ; / / ... } The C Ch hr ro on no o namespace would naturally also contain related classes, such as T Ti im me e and S St to op pw wa at tc ch h, and their helper functions. Using a namespace to hold a single class is usually an over-elaboration that leads to inconvenience. 10.3.3 Overloaded Operators [class.over] It is often useful to add functions to enable conventional notation. For example, the o op pe er ra at to or r== function defines the equality operator == to work for D Da at te es: i in nl li in ne e b bo oo ol l o op pe er ra at to or r==(D Da at te e a a, D Da at te e b b) / / equality { r re et tu ur rn n a a.d da ay y()==b b.d da ay y() && a a.m mo on nt th h()==b b.m mo on nt th h() && a a.y ye ea ar r()==b b.y ye ea ar r() ; } Other obvious candidates are: b bo oo ol l o op pe er ra at to or r!=(D Da at te e, D Da at te e) ; / / inequality b bo oo ol l o op pe er ra at to or r<(D Da at te e, D Da at te e) ; / / less than b bo oo ol l o op pe er ra at to or r>(D Da at te e, D Da at te e) ; / / greater than / / ... D Da at te e& o op pe er ra at to or r++(D Da at te e& d d) ; / / increase Date by one day D Da at te e& o op pe er ra at to or r--(D Da at te e& d d) ; / / decrease Date by one day D Da at te e& o op pe er ra at to or r+=(D Da at te e& d d, i in nt t n n) ; / / add n days D Da at te e& o op pe er ra at to or r-=(D Da at te e& d d, i in nt t n n) ; / / subtract n days D Da at te e o op pe er ra at to or r+(D Da at te e d d, i in nt t n n) ; / / add n days D Da at te e o op pe er ra at to or r-(D Da at te e d d, i in nt t n n) ; / / subtract n days o os st tr re ea am m& o op pe er ra at to or r<<(o os st tr re ea am m&, D Da at te e d d) ; / / output d i is st tr re ea am m& o op pe er ra at to or r>>(i is st tr re ea am m&, D Da at te e& d d) ; / / read into d For D Da at te e, these operators can be seen as mere conveniences. However, for many types ± such as complex numbers (§11.3), vectors (§3.7.1), and function-like objects (§18.4) ± the use of conven- tional operators is so firmly entrenched in people’s minds that their definition is almost mandatory. Operator overloading is discussed in Chapter 11. 10.3.4 The Significance of Concrete Classes [class.significance] I call simple user-defined types, such as D Da at te e, concrete types to distinguish them from abstract classes (§2.5.4) and class hierarchies (§12.3) and also to emphasize their similarity to built-in types such as i in nt t and c ch ha ar r. They have also been called value types, and their use value-oriented programming. Their model of use and the ‘‘philosophy’’ behind their design are quite different from what is often advertised as object-oriented programming (§2.6.2). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.242 Classes Chapter 10 The intent of a concrete type is to do a single, relatively small thing well and efficiently. It is not usually the aim to provide the user with facilities to modify the behavior of a concrete type. In particular, concrete types are not intended to display polymorphic behavior (see §2.5.5, §12.2.6). If you don’t like some detail of a concrete type, you build a new one with the desired behavior. If you want to ‘‘reuse’’ a concrete type, you use it in the implementation of your new type exactly as you would have used an i in nt t. For example: c cl la as ss s D Da at te e_ _a an nd d_ _t ti im me e { p pr ri iv va at te e: D Da at te e d d; T Ti im me e t t; p pu ub bl li ic c: D Da at te e_ _a an nd d_ _t ti im me e(D Da at te e d d, T Ti im me e t t) ; D Da at te e_ _a an nd d_ _t ti im me e(i in nt t d d, D Da at te e: :M Mo on nt th h m m, i in nt t y y, T Ti im me e t t) ; / / ... }; The derived class mechanism discussed in Chapter 12 can be used to define new types from a con- crete class by describing the desired differences. The definition of V Ve ec c from v ve ec ct to or r (§3.7.2) is an example of this. With a reasonably good compiler, a concrete class such as D Da at te e incurs no hidden overhead in time or space. The size of a concrete type is known at compile time so that objects can be allocated on the run-time stack (that is, without free-store operations). The layout of each object is known at compile time so that inlining of operations is trivially achieved. Similarly, layout compatibility with other languages, such as C and Fortran, comes without special effort. A good set of such types can provide a foundation for applications. Lack of suitable ‘‘small efficient types’’ in an application can lead to gross run-time and space inefficiencies when overly general and expensive classes are used. Alternatively, lack of concrete types can lead to obscure programs and time wasted when each programmer writes code to directly manipulate ‘‘simple and frequently used’’ data structures. 10.4 Objects [class.objects] Objects can be created in several ways. Some are local variables, some are global variables, some are members of classes, etc. This section discusses these alternatives, the rules that govern them, the constructors used to initialize objects, and the destructors used to clean up objects before they become unusable. 10.4.1 Destructors [class.dtor] A constructor initializes an object. In other words, it creates the environment in which the member functions operate. Sometimes, creating that environment involves acquiring a resource ± such as a file, a lock, or some memory ± that must be released after use (§14.4.7). Thus, some classes need a function that is guaranteed to be invoked when an object is destroyed in a manner similar to the way a constructor is guaranteed to be invoked when an object is created. Inevitably, such functions are called destructors. They typically clean up and release resources. Destructors are called The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.4.1 Destructors 243 implicitly when an automatic variable goes out of scope, an object on the free store is deleted, etc. Only in very unusual circumstances does the user need to call a destructor explicitly (§10.4.11). The most common use of a destructor is to release memory acquired in a constructor. Consider a simple table of elements of some type N Na am me e. The constructor for T Ta ab bl le e must allocate memory to hold the elements. When the table is somehow deleted, we must ensure that this memory is reclaimed for further use elsewhere. We do this by providing a special function to complement the constructor: c cl la as ss s N Na am me e { c co on ns st t c ch ha ar r* s s; / / ... }; c cl la as ss s T Ta ab bl le e { N Na am me e* p p; s si iz ze e_ _t t s sz z; p pu ub bl li ic c: T Ta ab bl le e(s si iz ze e_ _t t s s = 1 15 5) { p p = n ne ew w N Na am me e[s sz z = s s] ; }/ / constructor ~T Ta ab bl le e() { d de el le et te e[] p p; } / / destructor N Na am me e* l lo oo ok ku up p(c co on ns st t c ch ha ar r *) ; b bo oo ol l i in ns se er rt t(N Na am me e*) ; }; The destructor notation ~T Ta ab bl le e() uses the complement symbol ~ to hint at the destructor’s rela- tion to the T Ta ab bl le e() constructor. A matching constructor/destructor pair is the usual mechanism for implementing the notion of a variably-sized object in C++. Standard library containers, such as m ma ap p, use a variant of this tech- nique for providing storage for their elements, so the following discussion illustrates techniques you rely on every time you use a standard container (including a standard s st tr ri in ng g). The discussion applies to types without a destructor, also. Such types are seen simply as having a destructor that does nothing. 10.4.2 Default Constructors [class.default] Similarly, most types can be considered to have a default constructor. A default constructor is a constructor that can be called without supplying an argument. Because of the default argument 1 15 5, T Ta ab bl le e: :T Ta ab bl le e(s si iz ze e_ _t t) is a default constructor. If a user has declared a default constructor, that one will be used; otherwise, the compiler will try to generate one if needed and if the user hasn’t declared other constructors. A compiler-generated default constructor implicitly calls the default constructors for a class’ members of class type and bases (§12.2.2). For example: s st tr ru uc ct t T Ta ab bl le es s { i in nt t i i; i in nt t v vi i[1 10 0] ; T Ta ab bl le e t t1 1; T Ta ab bl le e v vt t[1 10 0] ; }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.244 Classes Chapter 10 T Ta ab bl le es s t tt t; Here, t tt t will be initialized using a generated default constructor that calls T Ta ab bl le e(1 15 5) for t tt t.t t1 1 and each element of t tt t.v vt t. On the other hand, t tt t.i i and the elements of t tt t.v vi i are not initialized because those objects are not of a class type. The reasons for the dissimilar treatment of classes and built-in types are C compatibility and fear of run-time overhead. Because c co on ns st ts and references must be initialized (§5.5, §5.4), a class containing c co on ns st t or refer- ence members cannot be default-constructed unless the programmer explicitly supplies a construc- tor (§10.4.6.1). For example: s st tr ru uc ct t X X { c co on ns st t i in nt t a a; c co on ns st t i in nt t& r r; }; X X x x; / / error: no default constructor for X Default constructors can be invoked explicitly (§10.4.10). Built-in types also have default con- structors (§6.2.8). 10.4.3 Construction and Destruction [class.ctor.dtor] Consider the different ways an object can be created and how it gets destroyed afterwards. An object can be created as: §10.4.4 A named automatic object, which is created each time its declaration is encountered in the execution of the program and destroyed each time the program exits the block in which it occurs §10.4.5 A free-store object, which is created using the n ne ew w operator and destroyed using the d de el le et te e operator §10.4.6 A nonstatic member object, which is created as a member of another class object and created and destroyed when the object of which it is a member is created and destroyed §10.4.7 An array element, which is created and destroyed when the array of which it is an ele- ment is created and destroyed §10.4.8 A local static object, which is created the first time its declaration is encountered in the execution of the program and destroyed once at the termination of the program §10.4.9 A global, namespace, or class static object, which is created once ‘‘at the start of the program’’ and destroyed once at the termination of the program §10.4.10 A temporary object, which is created as part of the evaluation of an expression and destroyed at the end of the full expression in which it occurs §10.4.11 An object placed in memory obtained from a user-supplied function guided by argu- ments supplied in the allocation operation §10.4.12 A u un ni io on n member, which may not have a constructor or a destructor This list is roughly sorted in order of importance. The following subsections explain these various ways of creating objects and their uses. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.4.4 Local Variables 245 10.4.4 Local Variables [class.local] The constructor for a local variable is executed each time the thread of control passes through the declaration of the local variable. The destructor for a local variable is executed each time the local variable’s block is exited. Destructors for local variables are executed in reverse order of their con- struction. For example: v vo oi id d f f(i in nt t i i) { T Ta ab bl le e a aa a; T Ta ab bl le e b bb b; i if f (i i>0 0) { T Ta ab bl le e c cc c; / / ... } T Ta ab bl le e d dd d; / / ... } Here, a aa a, b bb b, and d dd d are constructed (in that order) each time f f() is called, and d dd d, b bb b, and a aa a are destroyed (in that order) each time we return from f f(). If i i>0 0 for a call, c cc c will be constructed after b bb b and destroyed before d dd d is constructed. 10.4.4.1 Copying Objects [class.copy] If t t1 1 and t t2 2 are objects of a class T Ta ab bl le e, t t2 2=t t1 1 by default means a memberwise copy of t t1 1 into t t2 2 (§10.2.5). Having assignment interpreted this way can cause a surprising (and usually undesired) effect when used on objects of a class with pointer members. Memberwise copy is usually the wrong semantics for copying objects containing resources managed by a constructor/destructor pair. For example: v vo oi id d h h() { T Ta ab bl le e t t1 1; T Ta ab bl le e t t2 2 = t t1 1; / / copy initialization: trouble T Ta ab bl le e t t3 3; t t3 3 = t t2 2; / / copy assignment: trouble } Here, the T Ta ab bl le e default constructor is called twice: once each for t t1 1 and t t3 3. It is not called for t t2 2 because that variable was initialized by copying. However, the T Ta ab bl le e destructor is called three times: once each for t t1 1, t t2 2, and t t3 3! The default interpretation of assignment is memberwise copy, so t t1 1, t t2 2, and t t3 3 will, at the end of h h(), each contain a pointer to the array of names allocated on the free store when t t1 1 was created. No pointer to the array of names allocated when t t3 3 was created remains because it was overwritten by the t t3 3=t t2 2 assignment. Thus, in the absence of automatic garbage collection (§10.4.5), its storage will be lost to the program forever. On the other hand, the array created for t t1 1 appears in t t1 1, t t2 2, and t t3 3, so it will be deleted thrice. The result of that is unde- fined and probably disastrous. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.246 Classes Chapter 10 Such anomalies can be avoided by defining what it means to copy a T Ta ab bl le e: c cl la as ss s T Ta ab bl le e { / / ... T Ta ab bl le e(c co on ns st t T Ta ab bl le e&) ; / / copy constructor T Ta ab bl le e& o op pe er ra at to or r=(c co on ns st t T Ta ab bl le e&) ; / / copy assignment }; The programmer can define any suitable meaning for these copy operations, but the traditional one for this kind of container is to copy the contained elements (or at least to give the user of the con- tainer the appearance that a copy has been done; see §11.12). For example: T Ta ab bl le e: :T Ta ab bl le e(c co on ns st t T Ta ab bl le e& t t) / / copy constructor { p p = n ne ew w N Na am me e[s sz z=t t.s sz z] ; f fo or r (i in nt t i i = 0 0; i i>b bu uf f; } / / ... }; v vo oi id d f f() { I Ib bu uf ff fe er r w wo or rd ds s[1 10 00 0] ; / / each word initialized from cin / / ... } It is usually best to avoid such subtleties. The destructor for each constructed element of an array is invoked when that array is destroyed. This is done implicitly for arrays that are not allocated using n ne ew w. Like C, C++ doesn’t distinguish between a pointer to an individual object and a pointer to the initial element of an array (§5.3). Consequently, the programmer must state whether an array or an individual object is being deleted. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.4.7 Arrays 251 v vo oi id d f f(i in nt t s sz z) { T Ta ab bl le e* t t1 1 = n ne ew w T Ta ab bl le e; T Ta ab bl le e* t t2 2 = n ne ew w T Ta ab bl le e[s sz z] ; T Ta ab bl le e* t t3 3 = n ne ew w T Ta ab bl le e; T Ta ab bl le e* t t4 4 = n ne ew w T Ta ab bl le e[s sz z] ; d de el le et te e t t1 1; / / right d de el le et te e[] t t2 2; / / right d de el le et te e[] t t3 3; / / wrong: trouble d de el le et te e t t4 4; / / wrong: trouble } Exactly how arrays and individual objects are allocated is implementation-dependent. Therefore, different implementations will react differently to incorrect uses of the d de el le et te e and d de el le et te e[] opera- tors. In simple and uninteresting cases like the previous one, a compiler can detect the problem, but generally something nasty will happen at run time. The special destruction operator for arrays, d de el le et te e[], isn’t logically necessary. However, sup- pose the implementation of the free store had been required to hold sufficient information for every object to tell if it was an individual or an array. The user could have been relieved of a burden, but that obligation would have imposed significant time and space overheads on some C++ implemen- tations. As always, if you find C-style arrays too cumbersome, use a class such as v ve ec ct to or r (§3.7.1, §16.3) instead. For example: v vo oi id d g g() { v ve ec ct to or r* p p1 1 = n ne ew w v ve ec ct to or r(1 10 0) ; T Ta ab bl le e* p p2 2 = n ne ew w T Ta ab bl le e; d de el le et te e p p1 1; d de el le et te e p p2 2; } 10.4.8 Local Static Store [class.obj.static] The constructor for a local static object (§7.1.2) is called the first time the thread of control passes through the object’s definition. Consider this: v vo oi id d f f(i in nt t i i) { s st ta at ti ic c T Ta ab bl le e t tb bl l; / / ... i if f (i i) { s st ta at ti ic c T Ta ab bl le e t tb bl l2 2; / / ... } } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.252 Classes Chapter 10 i in nt t m ma ai in n() { f f(0 0) ; f f(1 1) ; f f(2 2) ; / / ... } Here, the constructor is called for t tb bl l once the first time f f() is called. Because t tb bl l is declared s st ta at ti ic c, it does not get destroyed on return from f f() and it does not get constructed a second time when f f() is called again. Because the block containing the declaration of t tb bl l2 2 doesn’t get executed for the call f f(0 0), t tb bl l2 2 doesn’t get constructed until the call f f(1 1). It does not get constructed again when its block is entered a second time. The destructors for local static objects are invoked in the reverse order of their construction when the program terminates (§9.4.1.1). Exactly when is unspecified. 10.4.9 Nonlocal Store [class.global] A variable defined outside any function (that is, global, namespace, and class s st ta at ti ic c variables) is initialized (constructed) before m ma ai in n() is invoked, and any such variable that has been constructed will have its destructor invoked after exit from m ma ai in n(). Dynamic linking complicates this picture slightly by delaying the initialization until the code is linked into the running program. Constructors for nonlocal objects in a translation unit are executed in the order their definitions occur. Consider: c cl la as ss s X X { / / ... s st ta at ti ic c T Ta ab bl le e m me em mt tb bl l; }; T Ta ab bl le e t tb bl l; T Ta ab bl le e X X: :m me em mt tb bl l; n na am me es sp pa ac ce e Z Z { T Ta ab bl le e t tb bl l2 2; } The order of construction is t tb bl l, then X X: :m me em mt tb bl l, and then Z Z: :t tb bl l2 2. Note that a declaration (as opposed to a definition), such as the declaration of m me em mt tb bl l in X X, doesn’t affect the order of con- struction. The destructors are called in the reverse order of construction: Z Z: :t tb bl l2 2, then X X: :m me em mt tb bl l, and then t tb bl l. No implementation-independent guarantees are made about the order of construction of nonlo- cal objects in different compilation units. For example: / / file1.c: T Ta ab bl le e t tb bl l1 1; / / file2.c: T Ta ab bl le e t tb bl l2 2; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.4.9 Nonlocal Store 253 Whether t tb bl l1 1 is constructed before t tb bl l2 2 or vice versa is implementation-dependent. The order isn’t even guaranteed to be fixed in every particular implementation. Dynamic linking, or even a small change in the compilation process, can alter the sequence. The order of destruction is similarly implementation-dependent. Sometimes when you design a library, it is necessary, or simply convenient, to invent a type with a constructor and a destructor with the sole purpose of initialization and cleanup. Such a type would be used once only: to allocate a static object so that the constructor and the destructor are called. For example: c cl la as ss s Z Zl li ib b_ _i in ni it t { Z Zl li ib b_ _i in ni it t() ; / / get Zlib ready for use ~Z Zl li ib b_ _i in ni it t() ; / / clean up after Zlib }; c cl la as ss s Z Zl li ib b { s st ta at ti ic c Z Zl li ib b_ _i in ni it t x x; / / ... }; Unfortunately, it is not guaranteed that such an object is initialized before its first use and destroyed after its last use in a program consisting of separately compiled units. A particular C++ implemen- tation may provide such a guarantee, but most don’t. A programmer may ensure proper initial- ization by implementing the strategy that the implementations usually employ for local static objects: a first-time switch. For example: c cl la as ss s Z Zl li ib b { s st ta at ti ic c b bo oo ol l i in ni it ti ia al li iz ze ed d; s st ta at ti ic c v vo oi id d i in ni it ti ia al li iz ze e() { /* initialize */ i in ni it ti ia al li iz ze ed d = t tr ru ue e; } p pu ub bl li ic c: / / no constructor v vo oi id d f f() { i if f (i in ni it ti ia al li iz ze ed d == f fa al ls se e) i in ni it ti ia al li iz ze e() ; / / ... } / / ... }; If there are many functions that need to test the first-time switch, this can be tedious, but it is often manageable. This technique relies on the fact that statically allocated objects without constructors are initialized to 0 0. The really difficult case is the one in which the first operation may be time- critical so that the overhead of testing and possible initialization can be serious. In that case, further trickery is required (§21.5.2). An alternative approach for a simple object is to present it as a function (§9.4.1): i in nt t& o ob bj j() { s st ta at ti ic c i in nt t x x = 0 0; r re et tu ur rn n x x; } / / initialized upon first use First-time switches do not handle every conceivable situation. For example, it is possible to create objects that refer to each other during construction. Such examples are best avoided. If such The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.254 Classes Chapter 10 objects are necessary, they must be constructed carefully in stages. Also, there is no similarly sim- ple last-time switch construct. Instead, see §9.4.1.1 and §21.5.2. 10.4.10 Temporary Objects [class.temp] Temporary objects most often are the result of arithmetic expressions. For example, at some point in the evaluation of x x*y y+z z the partial result x x*y y must exist somewhere. Except when performance is the issue (§11.6), temporary objects rarely become the concern of the programmer. However, it happens (§11.6, §22.4.7). Unless bound to a reference or used to initialize a named object, a temporary object is destroyed at the end of the full expression in which it was created. A full expression is an expression that is not a subexpression of some other expression. The standard s st tr ri in ng g class has a member function c c_ _s st tr r() that returns a C-style, zero-terminated array of characters (§3.5.1, §20.4.1). Also, the operator + is defined to mean string concatenation. These are very useful facilities for s st tr ri in ng gs s. However, in combination they can cause obscure prob- lems. For example: v vo oi id d f f(s st tr ri in ng g& s s1 1, s st tr ri in ng g& s s2 2, s st tr ri in ng g& s s3 3) { c co on ns st t c ch ha ar r* c cs s = (s s1 1+s s2 2).c c_ _s st tr r() ; c co ou ut t << c cs s; i if f (s st tr rl le en n(c cs s=(s s2 2+s s3 3).c c_ _s st tr r())<8 8 && c cs s[0 0]==´a a´) { / / cs used here } } Probably, your first reaction is ‘‘but don’t do that,’’ and I agree. However, such code does get writ- ten, so it is worth knowing how it is interpreted. A temporary object of class s st tr ri in ng g is created to hold s s1 1+s s2 2. Next, a pointer to a C-style string is extracted from that object. Then ± at the end of the expression ± the temporary object is deleted. Now, where was the C-style string allocated? Probably as part of the temporary object holding s s1 1+s s2 2, and that storage is not guaranteed to exist after that temporary is destroyed. Consequently, c cs s points to deallocated storage. The output operation c co ou ut t<(0 0x xF F0 00 0F F) ; / / significant address X X* p p2 2 = n ne ew w(b bu uf f)X X; / / construct an X at ‘buf;’ invokes: operator new(sizeof(X),buf) The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.256 Classes Chapter 10 Because of this usage, the n ne ew w(b bu uf f)X X syntax for supplying extra arguments to o op pe er ra at to or r n ne ew w() is known as the placement syntax. Note that every o op pe er ra at to or r n ne ew w() takes a size as its first argument and that the size of the object allocated is implicitly supplied (§15.6). The o op pe er ra at to or r n ne ew w() used by the n ne ew w operator is chosen by the usual argument matching rules (§7.4); every o op pe er ra at to or r n ne ew w() has a s si iz ze e_ _t t as its first argument. The ‘‘placement’’ o op pe er ra at to or r n ne ew w() is the simplest such allocator. It is defined in the standard header . The r re ei in nt te er rp pr re et t_ _c ca as st t is the crudest and potentially nastiest of the type conversion operators (§6.2.7). In most cases, it simply yields a value with the same bit pattern as its argument with the type required. Thus, it can be used for the inherently implementation-dependent, dangerous, and occasionally absolutely necessary activity of converting integer values to pointers and vice versa. The placement n ne ew w construct can also be used to allocate memory from a specific arena: c cl la as ss s A Ar re en na a { p pu ub bl li ic c: v vi ir rt tu ua al l v vo oi id d* a al ll lo oc c(s si iz ze e_ _t t) =0 0; v vi ir rt tu ua al l v vo oi id d f fr re ee e(v vo oi id d*) =0 0; / / ... }; v vo oi id d* o op pe er ra at to or r n ne ew w(s si iz ze e_ _t t s sz z, A Ar re en na a* a a) { r re et tu ur rn n a a->a al ll lo oc c(s sz z) ; } Now objects of arbitrary types can be allocated from different A Ar re en na as as needed. For example: e ex xt te er rn n A Ar re en na a* P Pe er rs si is st te en nt t; e ex xt te er rn n A Ar re en na a* S Sh ha ar re ed d; v vo oi id d g g(i in nt t i i) { X X* p p = n ne ew w(P Pe er rs si is st te en nt t) X X(i i) ; / / X in persistent storage X X* q q = n ne ew w(S Sh ha ar re ed d) X X(i i) ; / / X in shared memory / / ... } Placing an object in an area that is not (directly) controlled by the standard free-store manager implies that some care is required when destroying the object. The basic mechanism for that is an explicit call of a destructor: v vo oi id d d de es st tr ro oy y(X X* p p, A Ar re en na a* a a) { p p->~X X() ; / / call destructor a a->f fr re ee e(p p) ; / / free memory } Note that explicit calls of destructors, like the use of special-purpose global allocators, should be avoided wherever possible. Occasionally, they are essential. For example, it would be hard to implement an efficient general container along the lines of the standard library v ve ec ct to or r (§3.7.1, §16.3.8) without using explicit destructor class. However, a novice should think thrice before The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.4.11 Placement of Objects 257 calling a destructor explicitly and also should ask a more experienced colleague before doing so. See §14.4.7 for an explanation of how placement new interacts with exception handling. There is no special syntax for placement of arrays. Nor need there be, since arbitrary types can be allocated by placement new. However, a special o op pe er ra at to or r d de el le et te e() can be defined for arrays (§19.4.5). 10.4.12 Unions [class.union] A named union is defined as a s st tr ru uc ct t, where every member has the same address (see §C.8.2). A union can have member functions but not static members. In general, a compiler cannot know what member of a union is used; that is, the type of the object stored in a union is unknown. Consequently, a union may not have members with construc- tors or destructors. It wouldn’t be possible to protect that object against corruption or to guarantee that the right destructor is called when the union goes out of scope. Unions are best used in low-level code, or as part of the implementation of classes that keep track of what is stored in the union (see §10.6[20]). 10.5 Advice [class.advice] [1] Represent concepts as classes; §10.1. [2] Use public data (s st tr ru uc ct ts) only when it really is just data and no invariant is meaningful for the data members; §10.2.8. [3] A concrete type is the simplest kind of class. Where applicable, prefer a concrete type over more complicated classes and over plain data structures; §10.3. [4] Make a function a member only if it needs direct access to the representation of a class; §10.3.2. [5] Use a namespace to make the association between a class and its helper functions explicit; §10.3.2. [6] Make a member function that doesn’t modify the value of its object a c co on ns st t member function; §10.2.6. [7] Make a function that needs access to the representation of a class but needn’t be called for a specific object a s st ta at ti ic c member function; §10.2.4. [8] Use a constructor to establish an invariant for a class; §10.3.1. [9] If a constructor acquires a resource, its class needs a destructor to release the resource; §10.4.1. [10] If a class has a pointer member, it needs copy operations (copy constructor and copy assign- ment); §10.4.4.1. [11] If a class has a reference member, it probably needs copy operations (copy constructor and copy assignment); §10.4.6.3. [12] If a class needs a copy operation or a destructor, it probably needs a constructor, a destructor, a copy assignment, and a copy constructor; §10.4.4.1. [13] Check for self-assignment in copy assignments; §10.4.4.1. [14] When writing a copy constructor, be careful to copy every element that needs to be copied (beware of default initializers); §10.4.4.1. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.258 Classes Chapter 10 [15] When adding a new member to a class, always check to see if there are user-defined construc- tors that need to be updated to initialize the member; §10.4.6.3. [16] Use enumerators when you need to define integer constants in class declarations; §10.4.6.1. [17] Avoid order dependencies when constructing global and namespace objects; §10.4.9. [18] Use first-time switches to minimize order dependencies; §10.4.9. [19] Remember that temporary objects are destroyed at the end of the full expression in which they are created; §10.4.10. 10.6 Exercises [class.exercises] 1. (∗1) Find the error in D Da at te e: :a ad dd d_ _y ye ea ar r() in §10.2.2. Then find two additional errors in the version in §10.2.7. 2. (∗2.5) Complete and test D Da at te e. Reimplement it with ‘‘number of days after 1/1/1970’’ repre- sentation. 3. (∗2) Find a D Da at te e class that is in commercial use. Critique the facilities it offers. If possible, then discuss that D Da at te e with a real user. 4. (∗1) How do you access s se et t_ _d de ef fa au ul lt t from class D Da at te e from namespace C Ch hr ro on no o (§10.3.2)? Give at least three different ways. 5. (∗2) Define a class H Hi is st to og gr ra am m that keeps count of numbers in some intervals specified as argu- ments to H Hi is st to og gr ra am m’s constructor. Provide functions to print out the histogram. Handle out- of-range values. 6. (∗2) Define some classes for providing random numbers of certain distributions (for example, uniform and exponential). Each class has a constructor specifying parameters for the distribu- tion and a function d dr ra aw w that returns the next value. 7. (∗2.5) Complete class T Ta ab bl le e to hold (name,value) pairs. Then modify the desk calculator pro- gram from §6.1 to use class T Ta ab bl le e instead of m ma ap p. Compare and contrast the two versions. 8. (∗2) Rewrite T Tn no od de e from §7.10[7] as a class with constructors, destructors, etc. Define a tree of T Tn no od de es as a class with constructors, destructors, etc. 9. (∗3) Define, implement, and test a set of integers, class I In nt ts se et t. Provide union, intersection, and symmetric difference operations. 10. (∗1.5) Modify class I In nt ts se et t into a set of nodes, where N No od de e is a structure you define. 11. (∗3) Define a class for analyzing, storing, evaluating, and printing simple arithmetic expressions consisting of integer constants and the operators +, -, *, and /. The public interface should look like this: c cl la as ss s E Ex xp pr r { / / ... p pu ub bl li ic c: E Ex xp pr r(c ch ha ar r*) ; i in nt t e ev va al l() ; v vo oi id d p pr ri in nt t() ; }; The string argument for the constructor E Ex xp pr r: :E Ex xp pr r() is the expression. The function E Ex xp pr r: :e ev va al l() returns the value of the expression, and E Ex xp pr r: :p pr ri in nt t() prints a representation The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 10.6 Exercises 259 of the expression on c co ou ut t. A program might look like this: E Ex xp pr r x x("1 12 23 3/4 4+1 12 23 3*4 4-3 3") ; c co ou ut t << "x x = " << x x.e ev va al l() << "\ \n n"; x x.p pr ri in nt t() ; Define class E Ex xp pr r twice: once using a linked list of nodes as the representation and once using a character string as the representation. Experiment with different ways of printing the expres- sion: fully parenthesized, postfix notation, assembly code, etc. 12. (∗2) Define a class C Ch ha ar r_ _q qu ue eu ue e so that the public interface does not depend on the representa- tion. Implement C Ch ha ar r_ _q qu ue eu ue e (a) as a linked list and (b) as a vector. Do not worry about con- currency. 13. (∗3) Design a symbol table class and a symbol table entry class for some language. Have a look at a compiler for that language to see what the symbol table really looks like. 14. (∗2) Modify the expression class from §10.6[11] to handle variables and the assignment opera- tor =. Use the symbol table class from §10.6[13]. 15. (∗1) Given this program: #i in nc cl lu ud de e i in nt t m ma ai in n() { s st td d: :c co ou ut t << "H He el ll lo o, w wo or rl ld d!\ \n n"; } modify it to produce this output: I In ni it ti ia al li iz ze e H He el ll lo o, w wo or rl ld d! C Cl le ea an n u up p Do not change m ma ai in n() in any way. 16. (∗2) Define a C Ca al lc cu ul la at to or r class for which the calculator functions from §6.1 provide most of the implementation. Create C Ca al lc cu ul la at to or rs and invoke them for input from c ci in n, from command-line arguments, and for strings in the program. Allow output to be delivered to a variety of targets similar to the way input can be obtained from a variety of sources. 17. (∗2) Define two classes, each with a s st ta at ti ic c member, so that the construction of each s st ta at ti ic c member involves a reference to the other. Where might such constructs appear in real code? How can these classes be modified to eliminate the order dependence in the constructors? 18. (∗2.5) Compare class D Da at te e (§10.3) with your solution to §5.9[13] and §7.10[19]. Discuss errors found and likely differences in maintenance of the two solutions. 19. (∗3) Write a function that, given an i is st tr re ea am m and a v ve ec ct to or r, produces a m ma ap p> holding each string and the numbers of the lines on which the string appears. Run the program on a text-file with no fewer than 1,000 lines looking for no fewer than 10 words. 20. (∗2) Take class E En nt tr ry y from §C.8.2 and modify it so that each union member is always used according to its type. . The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.260 Classes Chapter 10 The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 11 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Operator Overloading When I use a word it means just what I choose it to mean ± neither more nor less. ± Humpty Dumpty Notation Ð operator functions Ð binary and unary operators Ð predefined meanings for operators Ð user-defined meanings for operators Ð operators and namespaces Ð a complex type Ð member and nonmember operators Ð mixed-mode arithmetic Ð initialization Ð copying Ð conversions Ð literals Ð helper functions Ð conversion operators Ð ambiguity resolution Ð friends Ð members and friends Ð large objects Ð assignment and initialization Ð subscripting Ð function call Ð dereferencing Ð incre- ment and decrement Ð a string class Ð advice Ð exercises. 11.1 Introduction [over.intro] Every technical field ± and most nontechnical fields ± have developed conventional shorthand notation to make convenient the presentation and discussion involving frequently-used concepts. For example, because of long acquaintance x x+y y*z z is clearer to us than m mu ul lt ti ip pl ly y y y b by y z z a an nd d a ad dd d t th he e r re es su ul lt t t to o x x It is hard to overestimate the importance of concise notation for common operations. Like most languages, C++ supports a set of operators for its built-in types. However, most con- cepts for which operators are conventionally used are not built-in types in C++, so they must be rep- resented as user-defined types. For example, if you need complex arithmetic, matrix algebra, logic signals, or character strings in C++, you use classes to represent these notions. Defining operators The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.262 Operator Overloading Chapter 11 for such classes sometimes allows a programmer to provide a more conventional and convenient notation for manipulating objects than could be achieved using only the basic functional notation. For example, c cl la as ss s c co om mp pl le ex x { / / very simplified complex d do ou ub bl le e r re e, i im m; p pu ub bl li ic c: c co om mp pl le ex x(d do ou ub bl le e r r, d do ou ub bl le e i i) : r re e(r r) , i im m(i i) { } c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x) ; c co om mp pl le ex x o op pe er ra at to or r*(c co om mp pl le ex x) ; }; defines a simple implementation of the concept of complex numbers. A c co om mp pl le ex x is represented by a pair of double-precision floating-point numbers manipulated by the operators + and *. The pro- grammer defines c co om mp pl le ex x: :o op pe er ra at to or r+() and c co om mp pl le ex x: :o op pe er ra at to or r*() to provide meanings for + and *, respectively. For example, if b b and c c are of type c co om mp pl le ex x, b b+c c means b b.o op pe er ra at to or r+(c c). We can now approximate the conventional interpretation of c co om mp pl le ex x expressions: v vo oi id d f f() { c co om mp pl le ex x a a = c co om mp pl le ex x(1 1, 3 3.1 1) ; c co om mp pl le ex x b b = c co om mp pl le ex x(1 1.2 2, 2 2) ; c co om mp pl le ex x c c = b b; a a = b b+c c; b b = b b+c c*a a; c c = a a*b b+c co om mp pl le ex x(1 1,2 2) ; } The usual precedence rules hold, so the second statement means b b=b b+(c c*a a), not b b=(b b+c c)*a a. Many of the most obvious uses of operator overloading are for concrete types (§10.3). How- ever, the usefulness of user-defined operators is not restricted to concrete types. For example, the design of general and abstract interfaces often leads to the use of operators such as ->, [], and (). 11.2 Operator Functions [over.oper] Functions defining meanings for the following operators (§6.2) can be declared: + - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* , -> [] () n ne ew w n ne ew w[] d de el le et te e d de el le et te e[] The following operators cannot be defined by a user: :: (scope resolution; §4.9.4, §10.2.4), . (member selection; §5.7), and .* (member selection through pointer to function; §15.5). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.2 Operator Functions 263 They take a name, rather than a value, as their second operand and provide the primary means of referring to members. Allowing them to be overloaded would lead to subtleties [Stroustrup,1994]. It is not possible to define new operator tokens, but you can use the function-call notation when this set of operators is not adequate. For example, use p po ow w(), not **. These restrictions may seem Draconian, but more flexible rules can easily lead to ambiguities. For example, defining an operator ** to mean exponentiation may seem an obvious and easy task at first glance, but think again. Should ** bind to the left (as in Fortran) or to the right (as in Algol)? Should the expres- sion a a**p p be interpreted as a a*(*p p) or as (a a)**(p p)? The name of an operator function is the keyword o op pe er ra at to or r followed by the operator itself; for example, o op pe er ra at to or r<<. An operator function is declared and can be called like any other function. A use of the operator is only a shorthand for an explicit call of the operator function. For example: v vo oi id d f f(c co om mp pl le ex x a a, c co om mp pl le ex x b b) { c co om mp pl le ex x c c = a a + b b; / / shorthand c co om mp pl le ex x d d = a a.o op pe er ra at to or r+(b b) ; / / explicit call } Given the previous definition of c co om mp pl le ex x, the two initializers are synonymous. 11.2.1 Binary and Unary Operators [over.binary] A binary operator can be defined by either a nonstatic member function taking one argument or a nonmember function taking two arguments. For any binary operator @, a aa a@b bb b can be interpreted as either a aa a.o op pe er ra at to or r@(b bb b) or o op pe er ra at to or r@(a aa a,b bb b). If both are defined, overload resolution (§7.4) determines which, if any, interpretation is used. For example: c cl la as ss s X X { p pu ub bl li ic c: v vo oi id d o op pe er ra at to or r+(i in nt t) ; X X(i in nt t) ; }; v vo oi id d o op pe er ra at to or r+(X X,X X) ; v vo oi id d o op pe er ra at to or r+(X X,d do ou ub bl le e) ; v vo oi id d f f(X X a a) { a a+1 1; / / a.operator+(1) 1 1+a a; / / ::operator+(X(1),a) a a+1 1.0 0; / / ::operator+(a,1.0) } A unary operator, whether prefix or postfix, can be defined by either a nonstatic member function taking no arguments or a nonmember function taking one argument. For any prefix unary operator @, @a aa a can be interpreted as either a aa a.o op pe er ra at to or r@() or o op pe er ra at to or r@(a aa a). If both are defined, over- load resolution (§7.4) determines which, if any, interpretation is used. For any postfix unary opera- tor @, a aa a@ can be interpreted as either a aa a.o op pe er ra at to or r@(i in nt t) or o op pe er ra at to or r@(a aa a,i in nt t). This is explained further in §11.11. If both are defined, overload resolution (§7.4) determines which, if The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.264 Operator Overloading Chapter 11 any, interpretation is used. An operator can be declared only for the syntax defined for it in the grammar (§A.5). For example, a user cannot define a unary % or a ternary +. Consider: c cl la as ss s X X { / / members (with implicit ‘this’ pointer): X X* o op pe er ra at to or r&() ; / / prefix unary & (address of) X X o op pe er ra at to or r&(X X) ; / / binary & (and) X X o op pe er ra at to or r++(i in nt t) ; / / postfix increment (see §11.11) X X o op pe er ra at to or r&(X X,X X) ; / / error: ternary X X o op pe er ra at to or r/() ; / / error: unary / }; / / nonmember functions : X X o op pe er ra at to or r-(X X) ; / / prefix unary minus X X o op pe er ra at to or r-(X X,X X) ; / / binary minus X X o op pe er ra at to or r--(X X&,i in nt t) ; / / postfix decrement X X o op pe er ra at to or r-() ; / / error: no operand X X o op pe er ra at to or r-(X X,X X,X X) ; / / error: ternary X X o op pe er ra at to or r%(X X) ; / / error: unary % Operator [] is described in §11.8, operator () in §11.9, operator -> in §11.10, operators ++ and -- in §11.11, and the allocation and deallocation operators in §6.2.6.2, §10.4.11, and §15.6. 11.2.2 Predefined Meanings for Operators [over.predefined] Only a few assumptions are made about the meaning of a user-defined operator. In particular, o op pe er ra at to or r=, o op pe er ra at to or r[], o op pe er ra at to or r(), and o op pe er ra at to or r-> must be nonstatic member functions; this ensures that their first operands will be lvalues (§4.9.6). The meanings of some built-in operators are defined to be equivalent to some combination of other operators on the same arguments. For example, if a a is an int, ++a a means a a+=1 1, which in turn means a a=a a+1 1. Such relations do not hold for user-defined operators unless the user happens to define them that way. For example, a compiler will not generate a definition of Z Z: :o op pe er ra at to or r+=() from the definitions of Z Z: :o op pe er ra at to or r+() and Z Z: :o op pe er ra at to or r=(). Because of historical accident, the operators = (assignment), & (address-of), and , (sequencing; §6.2.2) have predefined meanings when applied to class objects. These predefined meanings can be made inaccessible to general users by making them private: c cl la as ss s X X { p pr ri iv va at te e: v vo oi id d o op pe er ra at to or r=(c co on ns st t X X&) ; v vo oi id d o op pe er ra at to or r&() ; v vo oi id d o op pe er ra at to or r,(c co on ns st t X X&) ; / / ... }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.2.2 Predefined Meanings for Operators 265 v vo oi id d f f(X X a a, X X b b) { a a = b b; / / error: operator= private &a a; / / error: operator& private a a,b b; / / error: operator, private } Alternatively, they can be given new meanings by suitable definitions. 11.2.3 Operators and User-Defined Types [over.user] An operator function must either be a member or take at least one argument of a user-defined type (functions redefining the n ne ew w and d de el le et te e operators need not). This rule ensures that a user cannot change the meaning of an expression unless the expression contains an object of a user-defined type. In particular, it is not possible to define an operator function that operates exclusively on pointers. This ensures that C++ is extensible but not mutable (with the exception of operators =, &, and , for class objects). An operator function intended to accept a basic type as its first operand cannot be a member function. For example, consider adding a complex variable a aa a to the integer 2 2: a aa a+2 2 can, with a suitably declared member function, be interpreted as a aa a.o op pe er ra at to or r+(2 2), but 2 2+a aa a cannot because there is no class i in nt t for which to define + to mean 2 2.o op pe er ra at to or r+(a aa a). Even if there were, two dif- ferent member functions would be needed to cope with 2 2+a aa a and a aa a+2 2. Because the compiler does not know the meaning of a user-defined +, it cannot assume that it is commutative and so interpret 2 2+a aa a as a aa a+2 2. This example is trivially handled using nonmember functions (§11.3.2, §11.5). Enumerations are user-defined types so that we can define operators for them. For example: e en nu um m D Da ay y { s su un n, m mo on n, t tu ue e, w we ed d, t th hu u, f fr ri i, s sa at t }; D Da ay y& o op pe er ra at to or r++(D Da ay y& d d) { r re et tu ur rn n d d = (s sa at t==d d) ? s su un n : D Da ay y(d d+1 1) ; } Every expression is checked for ambiguities. Where a user-defined operator provides a possible interpretation, the expression is checked according to the rules in §7.4. 11.2.4 Operators in Namespaces [over.namespace] An operator is either a member of a class or defined in some namespace (possibly the global name- space). Consider this simplified version of string I/O from the standard library: n na am me es sp pa ac ce e s st td d { / / simplified std c cl la as ss s o os st tr re ea am m { / / ... o os st tr re ea am m& o op pe er ra at to or r<<(c co on ns st t c ch ha ar r*) ; }; e ex xt te er rn n o os st tr re ea am m c co ou ut t; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.266 Operator Overloading Chapter 11 c cl la as ss s s st tr ri in ng g { / / ... }; o os st tr re ea am m& o op pe er ra at to or r<<(o os st tr re ea am m&, c co on ns st t s st tr ri in ng g&) ; } i in nt t m ma ai in n() { c ch ha ar r* p p = "H He el ll lo o"; s st td d: :s st tr ri in ng g s s = "w wo or rl ld d"; s st td d: :c co ou ut t << p p << ", " << s s << "!\ \n n"; } Naturally, this writes out H He el ll lo o, w wo or rl ld d! But why? Note that I didn’t make everything from s st td d accessible by writing: u us si in ng g n na am me es sp pa ac ce e s st td d; Instead, I used the s st td d: : prefix for s st tr ri in ng g and c co ou ut t. In other words, I was at my best behavior and didn’t pollute the global namespace or in other ways introduce unnecessary dependencies. The output operator for C-style strings (c ch ha ar r*) is a member of s st td d: :o os st tr re ea am m, so by definition s st td d: :c co ou ut t << p p means s st td d: :c co ou ut t.o op pe er ra at to or r<<(p p) However, s st td d: :o os st tr re ea am m doesn’t have a member function to output a s st td d: :s st tr ri in ng g, so s st td d: :c co ou ut t << s s means o op pe er ra at to or r<<(s st td d: :c co ou ut t,s s) Operators defined in namespaces can be found based on their operand types just like functions can be found based on their argument types (§8.2.6). In particular, c co ou ut t is in namespace s st td d, so s st td d is considered when looking for a suitable definition of <<. In that way, the compiler finds and uses: s st td d: :o op pe er ra at to or r<<(s st td d: :o os st tr re ea am m&, c co on ns st t s st td d: :s st tr ri in ng g&) For a binary operator @, x x@y y where x x is of type X X and y y is of type Y Y is resolved like this: [1] If X X is a class, determine whether class X X or a base of X X defines o op pe er ra at to or r@ as a member; if so, that is the @ to try to use. [2] Otherwise, ± look for declarations of @ in the context surrounding x x@y y; and ± if X X is defined in namespace N N, look for declarations of @ in N N; and ± if Y Y is defined in namespace M M, look for declarations of @ in M M. If declarations of o op pe er ra at to or r@ are found in the surrounding context, in N N, or in M M, we try to use those operators. In either case, declarations for several o op pe er ra at to or r@s may be found and overload resolution rules The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.2.4 Operators in Namespaces 267 (§7.4) are used to find the best match, if any. This lookup mechanism is applied only if the opera- tor has at least one operand of a user-defined type. Therefore, user-defined conversions (§11.3.2, §11.4) will be considered. Note that a t ty yp pe ed de ef f name is just a synonym and not a user-defined type (§4.9.7). 11.3 A Complex Number Type [over.complex] The implementation of complex numbers presented in the introduction is too restrictive to please anyone. For example, from looking at a math textbook we would expect this to work: v vo oi id d f f() { c co om mp pl le ex x a a = c co om mp pl le ex x(1 1,2 2) ; c co om mp pl le ex x b b = 3 3; c co om mp pl le ex x c c = a a+2 2.3 3; c co om mp pl le ex x d d = 2 2+b b; c co om mp pl le ex x e e = -b b-c c; b b = c c*2 2*c c; } In addition, we would expect to be provided with a few additional operators, such as == for com- parison and << for output, and a suitable set of mathematical functions, such as s si in n() and s sq qr rt t(). Class c co om mp pl le ex x is a concrete type, so its design follows the guidelines from §10.3. In addition, users of complex arithmetic rely so heavily on operators that the definition of c co om mp pl le ex x brings into play most of the basic rules for operator overloading. 11.3.1 Member and Nonmember Operators [over.member] I prefer to minimize the number of functions that directly manipulate the representation of an object. This can be achieved by defining only operators that inherently modify the value of their first argument, such as +=, in the class itself. Operators that simply produce a new value based on the values of its arguments, such as +, are then defined outside the class and use the essential opera- tors in their implementation: c cl la as ss s c co om mp pl le ex x { d do ou ub bl le e r re e, i im m; p pu ub bl li ic c: c co om mp pl le ex x& o op pe er ra at to or r+=(c co om mp pl le ex x a a) ; / / needs access to representation / / ... }; c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x a a, c co om mp pl le ex x b b) { c co om mp pl le ex x r r = a a; r re et tu ur rn n r r += b b; / / access representation through += } Given these declarations, we can write: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.268 Operator Overloading Chapter 11 v vo oi id d f f(c co om mp pl le ex x x x, c co om mp pl le ex x y y, c co om mp pl le ex x z z) { c co om mp pl le ex x r r1 1 = x x+y y+z z; / / r1 = operator+(x,operator+(y,z)) c co om mp pl le ex x r r2 2 = x x; / / r2 = x r r2 2 += y y; / / r2.operator+=(y) r r2 2 += z z; / / r2.operator+=(z) } Except for possible efficiency differences, the computations of r r1 1 and r r2 2 are equivalent. Composite assignment operators such as += and *= tend to be simpler to define than their ‘‘simple’’ counterparts + and *. This surprises most people at first, but it follows from the fact that three objects are involved in a + operation (the two operands and the result), whereas only two objects are involved in a += operation. In the latter case, run-time efficiency is improved by elimi- nating the need for temporary variables. For example: i in nl li in ne e c co om mp pl le ex x& c co om mp pl le ex x: :o op pe er ra at to or r+=(c co om mp pl le ex x a a) { r re e += a a.r re e; i im m += a a.i im m; r re et tu ur rn n *t th hi is s; } does not require a temporary variable to hold the result of the addition and is simple for a compiler to inline perfectly. A good optimizer will generate close to optimal code for uses of the plain + operator also. However, we don’t always have a good optimizer and not all types are as simple as c co om mp pl le ex x, so §11.5 discusses ways of defining operators with direct access to the representation of classes. 11.3.2 Mixed-Mode Arithmetic [over.mixed] To cope with c co om mp pl le ex x d d = 2 2+b b; we need to define operator + to accept operands of different types. In Fortran terminology, we need mixed-mode arithmetic. We can achieve that simply by adding appropriate versions of the operators: c cl la as ss s c co om mp pl le ex x { d do ou ub bl le e r re e, i im m; p pu ub bl li ic c: c co om mp pl le ex x& o op pe er ra at to or r+=(c co om mp pl le ex x a a) { r re e += a a.r re e; i im m += a a.i im m; r re et tu ur rn n *t th hi is s; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.3.2 Mixed-Mode Arithmetic 269 c co om mp pl le ex x& o op pe er ra at to or r+=(d do ou ub bl le e a a) { r re e += a a; r re et tu ur rn n *t th hi is s; } / / ... }; c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x a a, c co om mp pl le ex x b b) { c co om mp pl le ex x r r = a a; r re et tu ur rn n r r += b b; / / calls complex::operator+=(complex) } c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x a a, d do ou ub bl le e b b) { c co om mp pl le ex x r r = a a; r re et tu ur rn n r r += b b; / / calls complex::operator+=(double) } c co om mp pl le ex x o op pe er ra at to or r+(d do ou ub bl le e a a, c co om mp pl le ex x b b) { c co om mp pl le ex x r r = b b; r re et tu ur rn n r r += a a; / / calls complex::operator+=(double) } Adding a d do ou ub bl le e to a complex number is a simpler operation than adding a c co om mp pl le ex x. This is reflected in these definitions. The operations taking d do ou ub bl le e operands do not touch the imaginary part of a complex number and thus will be more efficient. Given these declarations, we can write: v vo oi id d f f(c co om mp pl le ex x x x, c co om mp pl le ex x y y) { c co om mp pl le ex x r r1 1 = x x+y y; / / calls operator+(complex,complex) c co om mp pl le ex x r r2 2 = x x+2 2; / / calls operator+(complex,double) c co om mp pl le ex x r r3 3 = 2 2+x x; / / calls operator+(double,complex) } 11.3.3 Initialization [over.ctor] To cope with assignments and initialization of c co om mp pl le ex x variables with scalars, we need a conver- sion of a scalar (integer or floating-point number) to a c co om mp pl le ex x. For example: c co om mp pl le ex x b b = 3 3; / / should mean b.re=3, b.im=0 A constructor taking a single argument specifies a conversion from its argument type to the constructor’s type. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.270 Operator Overloading Chapter 11 c cl la as ss s c co om mp pl le ex x { d do ou ub bl le e r re e, i im m; p pu ub bl li ic c: c co om mp pl le ex x(d do ou ub bl le e r r) :r re e(r r) , i im m(0 0) { } / / ... }; The constructor specifies the traditional embedding of the real line in the complex plane. A constructor is a prescription for creating a value of a given type. The constructor is used when a value of a type is expected and when such a value can be created by a constructor from the value supplied as an initializer or assigned value. Thus, a constructor requiring a single argument need not be called explicitly. For example, c co om mp pl le ex x b b = 3 3; means c co om mp pl le ex x b b = c co om mp pl le ex x(3 3) ; A user-defined conversion is implicitly applied only if it is unique (§7.4). See §11.7.1 for a way of specifying constructors that can only be explicitly invoked. Naturally, we still need the constructor that takes two doubles, and a default constructor initial- izing a c co om mp pl le ex x to (0 0,0 0) is also useful: c cl la as ss s c co om mp pl le ex x { d do ou ub bl le e r re e, i im m; p pu ub bl li ic c: c co om mp pl le ex x() : r re e(0 0) , i im m(0 0) { } c co om mp pl le ex x(d do ou ub bl le e r r) : r re e(r r) , i im m(0 0) { } c co om mp pl le ex x(d do ou ub bl le e r r, d do ou ub bl le e i i) : r re e(r r) , i im m(i i) { } / / ... }; Using default arguments, we can abbreviate: c cl la as ss s c co om mp pl le ex x { d do ou ub bl le e r re e, i im m; p pu ub bl li ic c: c co om mp pl le ex x(d do ou ub bl le e r r =0 0, d do ou ub bl le e i i =0 0) : r re e(r r) , i im m(i i) { } / / ... }; When a constructor is explicitly declared for a type, it is not possible to use an initializer list (§5.7, §4.9.5) as the initializer. For example: c co om mp pl le ex x z z1 1 = { 3 3 }; / / error: complex has a constructor c co om mp pl le ex x z z2 2 = { 3 3, 4 4 }; / / error: complex has a constructor The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.3.4 Copying 271 11.3.4 Copying [over.copy] In addition to the explicitly declared constructors, c co om mp pl le ex x by default gets a copy constructor defined (§10.2.5). A default copy constructor simply copies all members. To be explicit, we could equivalently have written: c cl la as ss s c co om mp pl le ex x { d do ou ub bl le e r re e, i im m; p pu ub bl li ic c: c co om mp pl le ex x(c co on ns st t c co om mp pl le ex x& c c) : r re e(c c.r re e) , i im m(c c.i im m) { } / / ... }; However, for types where the default copy constructor has the right semantics, I prefer to rely on that default. It is less verbose than anything I can write, and people should understand the default. Also, compilers know about the default and its possible optimization opportunities. Furthermore, writing out the memberwise copy by hand is tedious and error-prone for classes with many data members (§10.4.6.3). I use a reference argument for the copy constructor because I must. The copy constructor defines what copying means ± including what copying an argument means ± so writing c co om mp pl le ex x: :c co om mp pl le ex x(c co om mp pl le ex x c c) : r re e(c c.r re e) , i im m(c c.i im m) { } / / error is an error because any call would have involved an infinite recursion. For other functions taking c co om mp pl le ex x arguments, I use value arguments rather than reference arguments. Here, the designer has a choice. From a user’s point of view, there is little difference between a function that takes a c co om mp pl le ex x argument and one that takes a c co on ns st t c co om mp pl le ex x& argument. This issue is discussed further in §11.6. In principle, copy constructors are used in simple initializations such as c co om mp pl le ex x x x = 2 2; / / create complex(2); then initialize x with it c co om mp pl le ex x y y = c co om mp pl le ex x(2 2,0 0) ; / / create complex(2,0); then initialize y with it However, the calls to the copy constructor are trivially optimized away. We could equivalently have written: c co om mp pl le ex x x x(2 2) ; / / initialize x by 2 c co om mp pl le ex x y y(2 2,0 0) ; / / initialize x by (2,0) For arithmetic types, such as c co om mp pl le ex x, I like the look of the version using = better. It is possible to restrict the set of values accepted by the = style of initialization compared to the ()style by making the copy constructor private (§11.2.2) or by declaring a constructor e ex xp pl li ic ci it t (§11.7.1). Similar to initialization, assignment of two objects of the same class is by default defined as memberwise assignment (§10.2.5). We could explicitly define c co om mp pl le ex x: :o op pe er ra at to or r= to do that. However, for a simple type like c co om mp pl le ex x there is no reason to do so. The default is just right. The copy constructor ± whether user-defined or compiler-generated ± is used not only for the initialization of variables, but also for argument passing, value return, and exception handling (see §11.7). The semantics of these operations is defined to be the semantics of initialization (§7.1, §7.3, §14.2.1). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.272 Operator Overloading Chapter 11 11.3.5 Constructors and Conversions [over.conv] We defined three versions of each of the four standard arithmetic operators: c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x,c co om mp pl le ex x) ; c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x,d do ou ub bl le e) ; c co om mp pl le ex x o op pe er ra at to or r+(d do ou ub bl le e,c co om mp pl le ex x) ; / / ... This can get tedious, and what is tedious easily becomes error-prone. What if we had three alterna- tives for the type of each argument for each function? We would need three versions of each single-argument function, nine versions of each two-argument function, twenty-seven versions of each three-argument function, etc. Often these variants are very similar. In fact, almost all variants involve a simple conversion of arguments to a common type followed by a standard algorithm. The alternative to providing different versions of a function for each combination of arguments is to rely on conversions. For example, our c co om mp pl le ex x class provides a constructor that converts a d do ou ub bl le e to a c co om mp pl le ex x. Consequently, we could simply declare only one version of the equality operator for c co om mp pl le ex x: b bo oo ol l o op pe er ra at to or r==(c co om mp pl le ex x,c co om mp pl le ex x) ; v vo oi id d f f(c co om mp pl le ex x x x, c co om mp pl le ex x y y) { x x==y y; / / means operator==(x,y) x x==3 3; / / means operator==(x,complex(3)) 3 3==y y; / / means operator==(complex(3),y) } There can be reasons for preferring to define separate functions. For example, in some cases the conversion can impose overheads, and in other cases, a simpler algorithm can be used for specific argument types. Where such issues are not significant, relying on conversions and providing only the most general variant of a function ± plus possibly a few critical variants ± contains the combi- natorial explosion of variants that can arise from mixed-mode arithmetic. Where several variants of a function or an operator exist, the compiler must pick ‘‘the right’’ variant based on the argument types and the available (standard and user-defined) conversions. Unless a best match exists, an expression is ambiguous and is an error (see §7.4). An object constructed by explicit or implicit use of a constructor is automatic and will be destroyed at the first opportunity (see §10.4.10). No implicit user-defined conversions are applied to the left-hand side of a . (or a ->). This is the case even when the . is implicit. For example: v vo oi id d g g(c co om mp pl le ex x z z) { 3 3+z z; / / ok: complex(3)+z 3 3.o op pe er ra at to or r+=(z z) ; / / error: 3 is not a class object 3 3+=z z; / / error: 3 is not a class object } Thus, you can express the notion that an operator requires an lvalue as their left-hand operand by making that operator a member. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.3.6 Literals 273 11.3.6 Literals [over.literals] It is not possible to define literals of a class type in the sense that 1 1.2 2 and 1 12 2e e3 3 are literals of type d do ou ub bl le e. However, literals of the basic types can often be used instead if class member functions are used to provide an interpretation for them. Constructors taking a single argument provide a general mechanism for this. When constructors are simple and inline, it is quite reasonable to think of con- structor invocations with literal arguments as literals. For example, I think of c co om mp pl le ex x(3 3) as a lit- eral of type c co om mp pl le ex x, even though technically it isn’t. 11.3.7 Additional Member Functions [over.additional] So far, we have provided class c co om mp pl le ex x with constructors and arithmetic operators only. That is not quite sufficient for real use. In particular, we often need to be able to examine the value of the real and imaginary parts: c cl la as ss s c co om mp pl le ex x { d do ou ub bl le e r re e, i im m; p pu ub bl li ic c: d do ou ub bl le e r re ea al l() c co on ns st t { r re et tu ur rn n r re e; } d do ou ub bl le e i im ma ag g() c co on ns st t { r re et tu ur rn n i im m; } / / ... }; Unlike the other members of c co om mp pl le ex x, r re ea al l() and i im ma ag g() do not modify the value of a c co om mp pl le ex x, so they can be declared c co on ns st t. Given r re ea al l() and i im ma ag g(), we can define all kinds of useful operations without granting them direct access to the representation of c co om mp pl le ex x. For example: i in nl li in ne e b bo oo ol l o op pe er ra at to or r==(c co om mp pl le ex x a a, c co om mp pl le ex x b b) { r re et tu ur rn n a a.r re ea al l()==b b.r re ea al l() && a a.i im ma ag g()==b b.i im ma ag g() ; } Note that we need only to be able to read the real and imaginary parts; writing them is less often needed. If we must do a ‘‘partial update,’’ we can: v vo oi id d f f(c co om mp pl le ex x& z z, d do ou ub bl le e d d) { / / ... z z = c co om mp pl le ex x(z z.r re ea al l() ,d d) ; / / assign d to z.im } A good optimizer generates a single assignment for that statement. 11.3.8 Helper Functions [over.helpers] If we put all the bits and pieces together, the c co om mp pl le ex x class becomes: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.274 Operator Overloading Chapter 11 c cl la as ss s c co om mp pl le ex x { d do ou ub bl le e r re e, i im m; p pu ub bl li ic c: c co om mp pl le ex x(d do ou ub bl le e r r =0 0, d do ou ub bl le e i i =0 0) : r re e(r r) , i im m(i i) { } d do ou ub bl le e r re ea al l() c co on ns st t { r re et tu ur rn n r re e; } d do ou ub bl le e i im ma ag g() c co on ns st t { r re et tu ur rn n i im m; } c co om mp pl le ex x& o op pe er ra at to or r+=(c co om mp pl le ex x) ; c co om mp pl le ex x& o op pe er ra at to or r+=(d do ou ub bl le e) ; / / ± =, *=, and /= }; In addition, we must provide a number of helper functions: c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x,c co om mp pl le ex x) ; c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x,d do ou ub bl le e) ; c co om mp pl le ex x o op pe er ra at to or r+(d do ou ub bl le e,c co om mp pl le ex x) ; / / ± , *, and / c co om mp pl le ex x o op pe er ra at to or r-(c co om mp pl le ex x) ; / / unary minus c co om mp pl le ex x o op pe er ra at to or r+(c co om mp pl le ex x) ; / / unary plus b bo oo ol l o op pe er ra at to or r==(c co om mp pl le ex x,c co om mp pl le ex x) ; b bo oo ol l o op pe er ra at to or r!=(c co om mp pl le ex x,c co om mp pl le ex x) ; i is st tr re ea am m& o op pe er ra at to or r>>(i is st tr re ea am m&,c co om mp pl le ex x&) ; / / input o os st tr re ea am m& o op pe er ra at to or r<<(o os st tr re ea am m&,c co om mp pl le ex x) ; / / output Note that the members r re ea al l() and i im ma ag g() are essential for defining the comparisons. The defini- tion of most of the following helper functions similarly relies on r re ea al l() and i im ma ag g(). We might provide functions to allow users to think in terms of polar coordinates: c co om mp pl le ex x p po ol la ar r(d do ou ub bl le e r rh ho o, d do ou ub bl le e t th he et ta a) ; c co om mp pl le ex x c co on nj j(c co om mp pl le ex x) ; d do ou ub bl le e a ab bs s(c co om mp pl le ex x) ; d do ou ub bl le e a ar rg g(c co om mp pl le ex x) ; d do ou ub bl le e n no or rm m(c co om mp pl le ex x) ; d do ou ub bl le e r re ea al l(c co om mp pl le ex x) ; / / for notational convenience d do ou ub bl le e i im ma ag g(c co om mp pl le ex x) ; / / for notational convenience Finally, we must provide an appropriate set of standard mathematical functions: c co om mp pl le ex x a ac co os s(c co om mp pl le ex x) ; c co om mp pl le ex x a as si in n(c co om mp pl le ex x) ; c co om mp pl le ex x a at ta an n(c co om mp pl le ex x) ; / / ... From a user’s point of view, the complex type presented here is almost identical to the c co om mp pl le ex x found in in the standard library (§22.5). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.4 Conversion Operators 275 11.4 Conversion Operators [over.conversion] Using a constructor to specify type conversion is convenient but has implications that can be unde- sirable. A constructor cannot specify [1] an implicit conversion from a user-defined type to a basic type (because the basic types are not classes), or [2] a conversion from a new class to a previously defined class (without modifying the decla- ration for the old class). These problems can be handled by defining a conversion operator for the source type. A member function X X: :o op pe er ra at to or r T T(), where T T is a type name, defines a conversion from X X to T T. For exam- ple, one could define a 6-bit non-negative integer, T Ti in ny y, that can mix freely with integers in arith- metic operations: c cl la as ss s T Ti in ny y { c ch ha ar r v v; v vo oi id d a as ss si ig gn n(i in nt t i i) { i if f (i i&~0 07 77 7) t th hr ro ow w B Ba ad d_ _r ra an ng ge e() ; v v=i i; } p pu ub bl li ic c: c cl la as ss s B Ba ad d_ _r ra an ng ge e { }; T Ti in ny y(i in nt t i i) { a as ss si ig gn n(i i) ; } T Ti in ny y& o op pe er ra at to or r=(i in nt t i i) { a as ss si ig gn n(i i) ; r re et tu ur rn n *t th hi is s; } o op pe er ra at to or r i in nt t() c co on ns st t { r re et tu ur rn n v v; } / / conversion to int function }; The range is checked whenever a T Ti in ny y is initialized by an i in nt t and whenever an i in nt t is assigned to one. No range check is needed when we copy a T Ti in ny y, so the default copy constructor and assign- ment are just right. To enable the usual integer operations on T Ti in ny y variables, we define the implicit conversion from T Ti in ny y to i in nt t, T Ti in ny y: :o op pe er ra at to or r i in nt t(). Note that the type being converted to is part of the name of the operator and cannot be repeated as the return value of the conversion function: T Ti in ny y: :o op pe er ra at to or r i in nt t() c co on ns st t { r re et tu ur rn n v v; } / / right i in nt t T Ti in ny y: :o op pe er ra at to or r i in nt t() c co on ns st t { r re et tu ur rn n v v; } / / error In this respect also, a conversion operator resembles a constructor. Whenever a T Ti in ny y appears where an i in nt t is needed, the appropriate i in nt t is used. For example: i in nt t m ma ai in n() { T Ti in ny y c c1 1 = 2 2; T Ti in ny y c c2 2 = 6 62 2; T Ti in ny y c c3 3 = c c2 2-c c1 1; / / c3 = 60 T Ti in ny y c c4 4 = c c3 3; / / no range check (not necessary) i in nt t i i = c c1 1+c c2 2; / / i = 64 c c1 1 = c c1 1+c c2 2; / / range error: c1 can’t be 64 i i = c c3 3-6 64 4; / / i = ± 4 c c2 2 = c c3 3-6 64 4; / / range error: c2 can’t be ± 4 c c3 3 = c c4 4; / / no range check (not necessary) } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.276 Operator Overloading Chapter 11 Conversion functions appear to be particularly useful for handling data structures when reading (implemented by a conversion operator) is trivial, while assignment and initialization are distinctly less trivial. The i is st tr re ea am m and o os st tr re ea am m types rely on a conversion function to enable statements such as w wh hi il le e (c ci in n>>x x) c co ou ut t<>x x returns an i is st tr re ea am m&. That value is implicitly converted to a value indi- cating the state of c ci in n. This value can then be tested by the w wh hi il le e (see §21.3.3). However, it is typ- ically not a good idea to define an implicit conversion from one type to another in such a way that information is lost in the conversion. In general, it is wise to be sparing in the introduction of conversion operators. When used in excess, they lead to ambiguities. Such ambiguities are caught by the compiler, but they can be a nuisance to resolve. Probably the best idea is initially to do conversions by named functions, such as X X: :m ma ak ke e_ _i in nt t(). If such a function becomes popular enough to make explicit use inelegant, it can be replaced by a conversion operator X X: :o op pe er ra at to or r i in nt t(). If both user-defined conversions and user-defined operators are defined, it is possible to get ambiguities between the user-defined operators and the built-in operators. For example: i in nt t o op pe er ra at to or r+(T Ti in ny y,T Ti in ny y) ; v vo oi id d f f(T Ti in ny y t t, i in nt t i i) { t t+i i; / / error, ambiguous: operator+(t,Tiny(i)) or int(t)+i ? } It is therefore often best to rely on user-defined conversions or user-defined operators for a given type, but not both. 11.4.1 Ambiguities [over.ambig] An assignment of a value of type V V to an object of class X X is legal if there is an assignment operator X X: :o op pe er ra at to or r=(Z Z) so that V V is Z Z or there is a unique conversion of V V to Z Z. Initialization is treated equivalently. In some cases, a value of the desired type can be constructed by repeated use of constructors or conversion operators. This must be handled by explicit conversions; only one level of user-defined implicit conversion is legal. In some cases, a value of the desired type can be constructed in more than one way; such cases are illegal. For example: c cl la as ss s X X { /* ... */ X X(i in nt t) ; X X(c ch ha ar r*) ; }; c cl la as ss s Y Y { /* ... */ Y Y(i in nt t) ; }; c cl la as ss s Z Z { /* ... */ Z Z(X X) ; }; X X f f(X X) ; Y Y f f(Y Y) ; Z Z g g(Z Z) ; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.4.1 Ambiguities 277 v vo oi id d k k1 1() { f f(1 1) ; / / error: ambiguous f(X(1)) or f(Y(1))? f f(X X(1 1)) ; / / ok f f(Y Y(1 1)) ; / / ok g g("M Ma ac ck k") ; / / error: two user-defined conversions needed; g(Z(X("Mack"))) not tried g g(X X("D Do oc c")) ; / / ok: g(Z(X("Doc"))) g g(Z Z("S Su uz zy y")) ; / / ok: g(Z(X("Suzy"))) } User-defined conversions are considered only if they are necessary to resolve a call. For example: c cl la as ss s X XX X { /* ... */ X XX X(i in nt t) ; }; v vo oi id d h h(d do ou ub bl le e) ; v vo oi id d h h(X XX X) ; v vo oi id d k k2 2() { h h(1 1) ; / / h(double(1)) or h(XX(1))? h(double(1))! } The call h h(1 1) means h h(d do ou ub bl le e(1 1)) because that alternative uses only a standard conversion rather than a user-defined conversion (§7.4). The rules for conversion are neither the simplest to implement, the simplest to document, nor the most general that could be devised. They are, however, considerably safer, and the resulting resolutions are less surprising. It is far easier to manually resolve an ambiguity than to find an error caused by an unsuspected conversion. The insistence on strict bottom-up analysis implies that the return type is not used in overload- ing resolution. For example: c cl la as ss s Q Qu ua ad d { p pu ub bl li ic c: Q Qu ua ad d(d do ou ub bl le e) ; / / ... }; Q Qu ua ad d o op pe er ra at to or r+(Q Qu ua ad d,Q Qu ua ad d) ; v vo oi id d f f(d do ou ub bl le e a a1 1, d do ou ub bl le e a a2 2) { Q Qu ua ad d r r1 1 = a a1 1+a a2 2; / / double-precision add Q Qu ua ad d r r2 2 = Q Qu ua ad d(a a1 1)+a a2 2; / / force quad arithmetic } The reason for this design choice is partly that strict bottom-up analysis is more comprehensible and partly that it is not considered the compiler’s job to decide which precision the programmer might want for the addition. Once the types of both sides of an initialization or assignment have been determined, both types are used to resolve the initialization or assignment. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.278 Operator Overloading Chapter 11 c cl la as ss s R Re ea al l { p pu ub bl li ic c: o op pe er ra at to or r d do ou ub bl le e() ; o op pe er ra at to or r i in nt t() ; / / ... }; v vo oi id d g g(R Re ea al l a a) { d do ou ub bl le e d d = a a; / / d = a.double(); i in nt t i i = a a; / / i = a.int(); d d = a a; / / d = a.double(); i i = a a; / / i = a.int(); } In these cases, the type analysis is still bottom-up, with only a single operator and its argument types considered at any one time. 11.5 Friends [over.friends] An ordinary member function declaration specifies three logically distinct things: [1] The function can access the private part of the class declaration, and [2] the function is in the scope of the class, and [3] the function must be invoked on an object (has a t th hi is s pointer). By declaring a member function s st ta at ti ic c (§10.2.4), we can give it the first two properties only. By declaring a function a f fr ri ie en nd d, we can give it the first property only. For example, we could define an operator that multiplies a M Ma at tr ri ix x by a V Ve ec ct to or r. Naturally, V Ve ec ct to or r and M Ma at tr ri ix x each hide their representation and provide a complete set of operations for manipulating objects of their type. However, our multiplication routine cannot be a member of both. Also, we don’t really want to provide low-level access functions to allow every user to both read and write the complete representation of both M Ma at tr ri ix x and V Ve ec ct to or r. To avoid this, we declare the o op pe er ra at to or r* a friend of both: c cl la as ss s M Ma at tr ri ix x; c cl la as ss s V Ve ec ct to or r { f fl lo oa at t v v[4 4] ; / / ... f fr ri ie en nd d V Ve ec ct to or r o op pe er ra at to or r*(c co on ns st t M Ma at tr ri ix x&, c co on ns st t V Ve ec ct to or r&) ; }; c cl la as ss s M Ma at tr ri ix x { V Ve ec ct to or r v v[4 4] ; / / ... f fr ri ie en nd d V Ve ec ct to or r o op pe er ra at to or r*(c co on ns st t M Ma at tr ri ix x&, c co on ns st t V Ve ec ct to or r&) ; }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.5 Friends 279 V Ve ec ct to or r o op pe er ra at to or r*(c co on ns st t M Ma at tr ri ix x& m m, c co on ns st t V Ve ec ct to or r& v v) { V Ve ec ct to or r r r; f fo or r (i in nt t i i = 0 0; i i<4 4; i i++) { / / r[i] = m[i] * v; r r.v v[i i] = 0 0; f fo or r (i in nt t j j = 0 0; j j<4 4; j j++) r r.v v[i i] += m m.v v[i i].v v[j j] * v v.v v[j j] ; } r re et tu ur rn n r r; } A f fr ri ie en nd d declaration can be placed in either the private or the public part of a class declaration; it does not matter where. Like a member function, a friend function is explicitly declared in the declaration of the class of which it is a friend. It is therefore as much a part of that interface as is a member function. A member function of one class can be the friend of another. For example: c cl la as ss s L Li is st t_ _i it te er ra at to or r { / / ... i in nt t* n ne ex xt t() ; }; c cl la as ss s L Li is st t { f fr ri ie en nd d i in nt t* L Li is st t_ _i it te er ra at to or r: :n ne ex xt t() ; / / ... }; It is not unusual for all functions of one class to be friends of another. There is a shorthand for this: c cl la as ss s L Li is st t { f fr ri ie en nd d c cl la as ss s L Li is st t_ _i it te er ra at to or r; / / ... }; This friend declaration makes all of L Li is st t_ _i it te er ra at to or r’s member functions friends of L Li is st t. Clearly, f fr ri ie en nd d classes should be used only to express closely connected concepts. Often, there is a choice between making a class a member (a nested class) or a friend (§24.4). 11.5.1 Finding Friends [over.lookup] Like a member declaration, a f fr ri ie en nd d declaration does not introduce a name into an enclosing scope. For example: c cl la as ss s M Ma at tr ri ix x { f fr ri ie en nd d c cl la as ss s X Xf fo or rm m; f fr ri ie en nd d M Ma at tr ri ix x i in nv ve er rt t(c co on ns st t M Ma at tr ri ix x&) ; / / ... }; X Xf fo or rm m x x; / / error: no Xform in scope M Ma at tr ri ix x (*p p)(c co on ns st t M Ma at tr ri ix x&) = &i in nv ve er rt t; / / error: no invert() in scope For large programs and large classes, it is nice that a class doesn’t ‘‘quietly’’ add names to its The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.280 Operator Overloading Chapter 11 enclosing scope. For a template class that can be instantiated in many different contexts (Chapter 13), this is very important. A friend class must be previously declared in an enclosing scope or defined in the non-class scope immediately enclosing the class that is declaring it a friend. For example: c cl la as ss s X X { /* ... */ }; / / Y’s friend n na am me es sp pa ac ce e N N { c cl la as ss s Y Y { f fr ri ie en nd d c cl la as ss s X X; f fr ri ie en nd d c cl la as ss s Z Z; f fr ri ie en nd d c cl la as ss s A AE E; }; c cl la as ss s Z Z { /* ... */ }; / / Y’s friend } c cl la as ss s A AE E { /* ... */ }; / / not a friend of Y A friend function can be explicitly declared just like friend classes, or it can be found through its argument types (§8.2.6) as if it was declared in the non-class scope immediately enclosing its class. For example: v vo oi id d f f(M Ma at tr ri ix x& m m) { i in nv ve er rt t(m m) ; / / Matrix’s friend invert() } It follows that a friend function should either be explicitly declared in an enclosing scope or take an argument of its class. If not, the friend cannot be called. For example: / / no f() here v vo oi id d g g() ; / / X’s friend c cl la as ss s X X { f fr ri ie en nd d v vo oi id d f f() ; / / useless f fr ri ie en nd d v vo oi id d g g() ; f fr ri ie en nd d v vo oi id d h h(c co on ns st t X X&) ; / / can be found through its argument }; v vo oi id d f f() { /* ... */ } / / not a friend of X 11.5.2 Friends and Members [over.friends.members] When should we use a friend function, and when is a member function the better choice for specify- ing an operation? First, we try to minimize the number of functions that access the representation of a class and try to make the set of access functions as appropriate as possible. Therefore, the first question is not, ‘‘Should it be a member, a static member, or a friend?’’ but rather, ‘‘Does it really need access?’’ Typically, the set of functions that need access is smaller than we are willing to believe at first. Some operations must be members ± for example, constructors, destructors, and virtual The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.5.2 Friends and Members 281 functions (§12.2.6) ± but typically there is a choice. Because member names are local to the class, a function should be a member unless there is a specific reason for it to be a nonmember. Consider a class X X presenting alternative ways of presenting an operation: c cl la as ss s X X { / / ... X X(i in nt t) ; i in nt t m m1 1() ; i in nt t m m2 2() c co on ns st t; f fr ri ie en nd d i in nt t f f1 1(X X&) ; f fr ri ie en nd d i in nt t f f2 2(c co on ns st t X X&) ; f fr ri ie en nd d i in nt t f f3 3(X X) ; }; Member functions can be invoked for objects of their class only; no user-defined conversions are applied. For example: v vo oi id d g g() { 9 99 9.m m1 1() ; / / error: X(99).m1() not tried 9 99 9.m m2 2() ; / / error: X(99).m2() not tried } The conversion X X(i in nt t) is not applied to make an X X out of 9 99 9. The global function f f1 1() has a similar property because implicit conversions are not used for non-c co on ns st t reference arguments (§5.5, §11.3.5). However, conversions may be applied to the argu- ments of f f2 2() and f f3 3(): v vo oi id d h h() { f f1 1(9 99 9) ; / / error: f1(X(99)) not tried f f2 2(9 99 9) ; / / ok: f2(X(99)); f f3 3(9 99 9) ; / / ok: f3(X(99)); } An operation modifying the state of a class object should therefore be a member or a global func- tion taking a non-c co on ns st t reference argument (or a non-c co on ns st t pointer argument). Operators that require lvalue operands for the fundamental types (=, *=, ++, etc.) are most naturally defined as members for user-defined types. Conversely, if implicit type conversion is desired for all operands of an operation, the function implementing it must be a nonmember function taking a c co on ns st t reference argument or a non- reference argument. This is often the case for the functions implementing operators that do not require lvalue operands when applied to fundamental types (+, -, ||, etc.). Such operators often need access to the representations of their operand class. Consequently, binary operators are the most common source of f fr ri ie en nd d functions. If no type conversions are defined, there appears to be no compelling reason to choose a mem- ber over a friend taking a reference argument, or vice versa. In some cases, the programmer may have a preference for one call syntax over another. For example, most people seem to prefer the The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.282 Operator Overloading Chapter 11 notation i in nv v(m m) for inverting a M Ma at tr ri ix x m m to the alternative m m.i in nv v(). Naturally, if i in nv v() really does invert m m itself, rather than return a new M Ma at tr ri ix x that is the inverse of m m, it should be a member. All other things considered equal, choose a member. It is not possible to know if someone someday will define a conversion operator. It is not always possible to predict if a future change may require changes to the state of the object involved. The member function call syntax makes it clear to the user that the object may be modified; a reference argument is far less obvious. Further- more, expressions in the body of a member can be noticeably shorter than the equivalent expres- sions in a global function; a nonmember function must use an explicit argument, whereas the mem- ber can use t th hi is s implicitly. Also, because member names are local to the class they tend to be shorter than the names of nonmember functions. 11.6 Large Objects [over.large] We defined the c co om mp pl le ex x operators to take arguments of type c co om mp pl le ex x. This implies that for each use of a c co om mp pl le ex x operator, each operand is copied. The overhead of copying two d do ou ub bl le es s can be noticeable but often less than what a pair of pointers impose. Unfortunately, not all classes have a conveniently small representation. To avoid excessive copying, one can declare functions to take reference arguments. For example: c cl la as ss s M Ma at tr ri ix x { d do ou ub bl le e m m[4 4][4 4] ; p pu ub bl li ic c: M Ma at tr ri ix x() ; f fr ri ie en nd d M Ma at tr ri ix x o op pe er ra at to or r+(c co on ns st t M Ma at tr ri ix x&, c co on ns st t M Ma at tr ri ix x&) ; f fr ri ie en nd d M Ma at tr ri ix x o op pe er ra at to or r*(c co on ns st t M Ma at tr ri ix x&, c co on ns st t M Ma at tr ri ix x&) ; }; References allow the use of expressions involving the usual arithmetic operators for large objects without excessive copying. Pointers cannot be used because it is not possible to redefine the mean- ing of an operator applied to a pointer. Addition could be defined like this: M Ma at tr ri ix x o op pe er ra at to or r+(c co on ns st t M Ma at tr ri ix x& a ar rg g1 1, c co on ns st t M Ma at tr ri ix x& a ar rg g2 2) { M Ma at tr ri ix x s su um m; f fo or r (i in nt t i i=0 0; i i<4 4; i i++) f fo or r (i in nt t j j=0 0; j j<4 4; j j++) s su um m.m m[i i][j j] = a ar rg g1 1.m m[i i][j j] + a ar rg g2 2.m m[i i][j j] ; r re et tu ur rn n s su um m; } This o op pe er ra at to or r+() accesses the operands of + through references but returns an object value. Returning a reference would appear to be more efficient: c cl la as ss s M Ma at tr ri ix x { / / ... f fr ri ie en nd d M Ma at tr ri ix x& o op pe er ra at to or r+(c co on ns st t M Ma at tr ri ix x&, c co on ns st t M Ma at tr ri ix x&) ; f fr ri ie en nd d M Ma at tr ri ix x& o op pe er ra at to or r*(c co on ns st t M Ma at tr ri ix x&, c co on ns st t M Ma at tr ri ix x&) ; }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.6 Large Objects 283 This is legal, but it causes a memory allocation problem. Because a reference to the result will be passed out of the function as a reference to the return value, the return value cannot be an automatic variable (§7.3). Since an operator is often used more than once in an expression, the result cannot be a s st ta at ti ic c local variable. The result would typically be allocated on the free store. Copying the return value is often cheaper (in execution time, code space, and data space) than allocating and (eventually) deallocating an object on the free store. It is also much simpler to program. There are techniques you can use to avoid copying the result. The simplest is to use a buffer of static objects. For example: c co on ns st t m ma ax x_ _m ma at tr ri ix x_ _t te em mp p = 7 7; M Ma at tr ri ix x& g ge et t_ _m ma at tr ri ix x_ _t te em mp p() { s st ta at ti ic c i in nt t n nb bu uf f = 0 0; s st ta at ti ic c M Ma at tr ri ix x b bu uf f[m ma ax x_ _m ma at tr ri ix x_ _t te em mp p] ; i if f (n nb bu uf f == m ma ax x_ _m ma at tr ri ix x_ _t te em mp p) n nb bu uf f = 0 0; r re et tu ur rn n b bu uf f[n nb bu uf f++] ; } M Ma at tr ri ix x& o op pe er ra at to or r+(c co on ns st t M Ma at tr ri ix x& a ar rg g1 1, c co on ns st t M Ma at tr ri ix x& a ar rg g2 2) { M Ma at tr ri ix x& r re es s = g ge et t_ _m ma at tr ri ix x_ _t te em mp p() ; / / ... r re et tu ur rn n r re es s; } Now a M Ma at tr ri ix x is copied only when the result of an expression is assigned. However, heaven help you if you write an expression that involves more than m ma ax x_ _m ma at tr ri ix x_ _t te em mp p temporaries! A less error-prone technique involves defining the matrix type as a handle (§25.7) to a represen- tation type that really holds the data. In that way, the matrix handles can manage the representation objects in such a way that allocation and copying are minimized (see §11.12 and §11.14[18]). However, that strategy relies on operators returning objects rather than references or pointers. Another technique is to define ternary operations and have them automatically invoked for expres- sions such as a a=b b+c c and a a+b b*i i (§21.4.6.3, §22.4.7). 11.7 Essential Operators [over.essential] In general, for a type X X, the copy constructor X X(c co on ns st t X X&) takes care of initialization by an object of the same type X X. It cannot be overemphasized that assignment and initialization are different operations (§10.4.4.1). This is especially important when a destructor is declared. If a class X X has a destructor that performs a nontrivial task, such as free-store deallocation, the class is likely to need the full complement of functions that control construction, destruction, and copying: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.284 Operator Overloading Chapter 11 c cl la as ss s X X { / / ... X X(S So om me et ty yp pe e) ; / / constructor: create objects X X(c co on ns st t X X&) ; / / copy constructor X X& o op pe er ra at to or r=(c co on ns st t X X&) ; / / copy assignment: cleanup and copy ~X X() ; / / destructor: cleanup }; There are three more cases in which an object is copied: as a function argument, as a function return value, and as an exception. When an argument is passed, a hitherto uninitialized variable ± the formal parameter ± is initialized. The semantics are identical to those of other initializations. The same is the case for function return values and exceptions, although that is less obvious. In such cases, the copy constructor will be applied. For example: s st tr ri in ng g g g(s st tr ri in ng g a ar rg g) { r re et tu ur rn n a ar rg g; } i in nt t m ma ai in n () { s st tr ri in ng g s s = "N Ne ew wt to on n"; s s = g g(s s) ; } Clearly, the value of s s ought to be " "N Ne ew wt to on n" " after the call of g g(). Getting a copy of the value of s s into the argument a ar rg g is not difficult; a call of s st tr ri in ng g’s copy constructor does that. Getting a copy of that value out of g g() takes another call of s st tr ri in ng g(c co on ns st t s st tr ri in ng g&); this time, the variable initial- ized is a temporary one, which is then assigned to s s. Often one, but not both, of these copy opera- tions can be optimized away. Such temporary variables are, of course, destroyed properly using s st tr ri in ng g: :~s st tr ri in ng g() (see §10.4.10). For a class X X for which the assignment operator X X: :o op pe er ra at to or r=(c co on ns st t X X&) and the copy con- structor X X: :X X(c co on ns st t X X&) are not explicitly declared by the programmer, the missing operation or operations will be generated by the compiler (§10.2.5). 11.7.1 Explicit Constructors [over.explicit] By default, a single argument constructor also defines an implicit conversion. For some types, that is ideal. For example: c co om mp pl le ex x z z = 2 2; / / initialize z with complex(2) In other cases, the implicit conversion is undesirable and error-prone. For example: s st tr ri in ng g s s = ´a a´; / / make s a string with int(’a’) elements It is quite unlikely that this was what the person defining s s meant. Implicit conversion can be suppressed by declaring a constructor e ex xp pl li ic ci it t. That is, an e ex xp pl li ic ci it t constructor will be invoked only explicitly. In particular, where a copy constructor is in principle needed (§11.3.4), an e ex xp pl li ic ci it t constructor will not be implicitly invoked. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.7.1 Explicit Constructors 285 c cl la as ss s S St tr ri in ng g { / / ... e ex xp pl li ic ci it t S St tr ri in ng g(i in nt t n n) ; / / preallocate n bytes S St tr ri in ng g(c co on ns st t c ch ha ar r* p p) ; / / initial value is the C-style string p }; S St tr ri in ng g s s1 1 = ´a a´; / / error: no implicit char± >String conversion S St tr ri in ng g s s2 2(1 10 0) ; / / ok: String with space for 10 characters S St tr ri in ng g s s3 3 = S St tr ri in ng g(1 10 0) ; / / ok: String with space for 10 characters S St tr ri in ng g s s4 4 = "B Br ri ia an n"; / / ok: s4 = String("Brian") S St tr ri in ng g s s5 5("F Fa aw wl lt ty y") ; v vo oi id d f f(S St tr ri in ng g) ; S St tr ri in ng g g g() { f f(1 10 0) ; / / error: no implicit int± >String conversion f f(S St tr ri in ng g(1 10 0)) ; f f("A Ar rt th hu ur r") ; / / ok: f(String("Arthur")) f f(s s1 1) ; S St tr ri in ng g* p p1 1 = n ne ew w S St tr ri in ng g("E Er ri ic c") ; S St tr ri in ng g* p p2 2 = n ne ew w S St tr ri in ng g(1 10 0) ; r re et tu ur rn n 1 10 0; / / error: no implicit int± >String conversion } The distinction between S St tr ri in ng g s s1 1 = ´a a´; / / error: no implicit char± >String conversion and S St tr ri in ng g s s2 2(1 10 0) ; / / ok: string with space for 10 characters may seem subtle, but it is less so in real code than in contrived examples. In D Da at te e, we used a plain i in nt t to represent a year (§10.3). Had D Da at te e been critical in our design, we might have introduced a Y Ye ea ar r type to allow stronger compile-time checking. For example: c cl la as ss s Y Ye ea ar r { i in nt t y y; p pu ub bl li ic c: e ex xp pl li ic ci it t Y Ye ea ar r(i in nt t i i) : y y(i i) { } / / construct Year from int o op pe er ra at to or r i in nt t() c co on ns st t { r re et tu ur rn n y y; } / / conversion: Year to int }; c cl la as ss s D Da at te e { p pu ub bl li ic c: D Da at te e(i in nt t d d, M Mo on nt th h m m, Y Ye ea ar r y y) ; / / ... }; D Da at te e d d3 3(1 19 97 78 8,f fe eb b,2 21 1) ; / / error: 21 is not a Year D Da at te e d d4 4(2 21 1,f fe eb b,Y Ye ea ar r(1 19 97 78 8)) ; / / ok The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.286 Operator Overloading Chapter 11 The Y Ye ea ar r class is a simple ‘‘wrapper’’ around an i in nt t. Thanks to the o op pe er ra at to or r i in nt t(), a Y Ye ea ar r is implicitly converted into an i in nt t wherever needed. By declaring the constructor e ex xp pl li ic ci it t, we make sure that the i in nt t to Y Ye ea ar r happens only when we ask for it and that ‘‘accidental’’ assignments are caught at compile time. Because Y Ye ea ar r’s member functions are easily inlined, no run-time or space costs are added. A similar technique can be used to define range types (§25.6.1). 11.8 Subscripting [over.subscript] An o op pe er ra at to or r[] function can be used to give subscripts a meaning for class objects. The second argument (the subscript) of an o op pe er ra at to or r[] function may be of any type. This makes it possible to define v ve ec ct to or rs, associative arrays, etc. As an example, let us recode the example from §5.5 in which an associative array is used to write a small program for counting the number of occurrences of words in a file. There, a function is used. Here, an associative array type is defined: c cl la as ss s A As ss so oc c { s st tr ru uc ct t P Pa ai ir r { s st tr ri in ng g n na am me e; d do ou ub bl le e v va al l; P Pa ai ir r(s st tr ri in ng g n n ="", d do ou ub bl le e v v =0 0) :n na am me e(n n) , v va al l(v v) { } }; v ve ec ct to or r

v ve ec c; A As ss so oc c(c co on ns st t A As ss so oc c&) ; / / private to prevent copying A As ss so oc c& o op pe er ra at to or r=(c co on ns st t A As ss so oc c&) ; / / private to prevent copying p pu ub bl li ic c: A As ss so oc c() {} d do ou ub bl le e& o op pe er ra at to or r[](c co on ns st t s st tr ri in ng g&) ; v vo oi id d p pr ri in nt t_ _a al ll l() c co on ns st t; }; An A As ss so oc c keeps a vector of P Pa ai ir rs. The implementation uses the same trivial and inefficient search method as in §5.5: d do ou ub bl le e& A As ss so oc c: :o op pe er ra at to or r[](c co on ns st t s st tr ri in ng g& s s) / / search for s; return its value if found; otherwise, make a new Pair and return the default value 0 { f fo or r (v ve ec ct to or r

: :c co on ns st t_ _i it te er ra at to or r p p = v ve ec c.b be eg gi in n() ; p p!=v ve ec c.e en nd d() ; ++p p) i if f (s s == p p->n na am me e) r re et tu ur rn n p p->v va al l; v ve ec c.p pu us sh h_ _b ba ac ck k(P Pa ai ir r(s s,0 0)) ; / / initial value: 0 r re et tu ur rn n v ve ec c.b ba ac ck k().v va al l; / / return last element (§16.3.3) } Because the representation of an A As ss so oc c is hidden, we need a way of printing it: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.8 Subscripting 287 v vo oi id d A As ss so oc c: :p pr ri in nt t_ _a al ll l() c co on ns st t { f fo or r (v ve ec ct to or r

: :c co on ns st t_ _i it te er ra at to or r p p = v ve ec c.b be eg gi in n() ; p p!=v ve ec c.e en nd d() ; ++p p) c co ou ut t << p p->n na am me e << ": " << p p->v va al l << ´\ \n n´; } Finally, we can write the trivial main program: i in nt t m ma ai in n() / / count the occurrences of each word on input { s st tr ri in ng g b bu uf f; A As ss so oc c v ve ec c; w wh hi il le e (c ci in n>>b bu uf f) v ve ec c[b bu uf f]++; v ve ec c.p pr ri in nt t_ _a al ll l() ; } A further development of the idea of an associative array can be found in §17.4.1. An o op pe er ra at to or r[]() must be a member function. 11.9 Function Call [over.call] Function call, that is, the notation expression(expression-list), can be interpreted as a binary opera- tion with the expression as the left-hand operand and the expression-list as the right-hand operand. The call operator () can be overloaded in the same way as other operators can. An argument list for an o op pe er ra at to or r()() is evaluated and checked according to the usual argument-passing rules. Overloading function call seems to be useful primarily for defining types that have only a single operation and for types for which one operation is predominant. The most obvious, and probably also the most important, use of the () operator is to provide the usual function call syntax for objects that in some way behave like functions. An object that acts like a function is often called a function-like object or simply a function object (§18.4). Such function objects are important because they allow us to write code that takes nontrivial operations as parameters. For example, the standard library provides many algorithms that invoke a function for each element of a container. Consider: v vo oi id d n ne eg ga at te e(c co om mp pl le ex x& c c) { c c = -c c; } v vo oi id d f f(v ve ec ct to or r& a aa a, l li is st t& l ll l) { f fo or r_ _e ea ac ch h(a aa a.b be eg gi in n() ,a aa a.e en nd d() ,n ne eg ga at te e) ; / / negate all vector elements f fo or r_ _e ea ac ch h(l ll l.b be eg gi in n() ,l ll l.e en nd d() ,n ne eg ga at te e) ; / / negate all list elements } This negates every element in the vector and the list. What if we wanted to add c co om mp pl le ex x(2 2,3 3) to every element? That is easily done like this: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.288 Operator Overloading Chapter 11 v vo oi id d a ad dd d2 23 3(c co om mp pl le ex x& c c) { c c += c co om mp pl le ex x(2 2,3 3) ; } v vo oi id d g g(v ve ec ct to or r& a aa a, l li is st t& l ll l) { f fo or r_ _e ea ac ch h(a aa a.b be eg gi in n() ,a aa a.e en nd d() ,a ad dd d2 23 3) ; f fo or r_ _e ea ac ch h(l ll l.b be eg gi in n() ,l ll l.e en nd d() ,a ad dd d2 23 3) ; } How would we write a function to repeatedly add an arbitrary complex value? We need something to which we can pass that arbitrary value and which can then use that value each time it is called. That does not come naturally for functions. Typically, we end up ‘‘passing’’ the arbitrary value by leaving it in the function’s surrounding context. That’s messy. However, we can write a class that behaves in the desired way: c cl la as ss s A Ad dd d { c co om mp pl le ex x v va al l; p pu ub bl li ic c: A Ad dd d(c co om mp pl le ex x c c) { v va al l = c c; } / / save value A Ad dd d(d do ou ub bl le e r r, d do ou ub bl le e i i) { v va al l = c co om mp pl le ex x(r r,i i) ; } v vo oi id d o op pe er ra at to or r()(c co om mp pl le ex x& c c) c co on ns st t { c c += v va al l; } / / add value to argument }; An object of class A Ad dd d is initialized with a complex number, and when invoked using (), it adds that number to its argument. For example: v vo oi id d h h(v ve ec ct to or r& a aa a, l li is st t& l ll l, c co om mp pl le ex x z z) { f fo or r_ _e ea ac ch h(a aa a.b be eg gi in n() ,a aa a.e en nd d() ,A Ad dd d(2 2,3 3)) ; f fo or r_ _e ea ac ch h(l ll l.b be eg gi in n() ,l ll l.e en nd d() ,A Ad dd d(z z)) ; } This will add c co om mp pl le ex x(2 2,3 3) to every element of the array and z z to every element on the list. Note that A Ad dd d(z z) constructs an object that is used repeatedly by f fo or r_ _e ea ac ch h(). It is not simply a function that is called once or even called repeatedly. The function that is called repeatedly is A Ad dd d(z z)’s o op pe er ra at to or r()(). This all works because f fo or r_ _e ea ac ch h is a template that applies () to its third argument without car- ing exactly what that third argument really is: t te em mp pl la at te e I It te er r f fo or r_ _e ea ac ch h(I It te er r b b, I It te er r e e, F Fc ct t f f) { w wh hi il le e (b b != e e) f f(*b b++) ; r re et tu ur rn n b b; } At first glance, this technique may look esoteric, but it is simple, efficient, and extremely useful (see §3.8.5, §18.4). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.9 Function Call 289 Other popular uses of o op pe er ra at to or r()() are as a substring operator and as a subscripting operator for multidimensional arrays (§22.4.5). An o op pe er ra at to or r()() must be a member function. 11.10 Dereferencing [over.deref] The dereferencing operator -> can be defined as a unary postfix operator. That is, given a class c cl la as ss s P Pt tr r { / / ... X X* o op pe er ra at to or r->() ; }; objects of class P Pt tr r can be used to access members of class X X in a very similar manner to the way pointers are used. For example: v vo oi id d f f(P Pt tr r p p) { p p->m m = 7 7; / / (p.operator± >())± >m = 7 } The transformation of the object p p into the pointer p p.o op pe er ra at to or r->() does not depend on the mem- ber m m pointed to. That is the sense in which o op pe er ra at to or r->() is a unary postfix operator. However, there is no new syntax introduced, so a member name is still required after the ->. For example: v vo oi id d g g(P Pt tr r p p) { X X* q q1 1 = p p->; / / syntax error X X* q q2 2 = p p.o op pe er ra at to or r->() ; / / ok } Overloading -> is primarily useful for creating ‘‘smart pointers,’’ that is, objects that act like point- ers and in addition perform some action whenever an object is accessed through them. For exam- ple, one could define a class R Re ec c_ _p pt tr r for accessing objects of class R Re ec c stored on disk. R Re ec c_ _p pt tr r’s constructor takes a name that can be used to find the object on disk, R Re ec c_ _p pt tr r: :o op pe er ra at to or r->() brings the object into main memory when accessed through its R Re ec c_ _p pt tr r, and R Re ec c_ _p pt tr r’s destructor eventually writes the updated object back out to disk: c cl la as ss s R Re ec c_ _p pt tr r { R Re ec c* i in n_ _c co or re e_ _a ad dd dr re es ss s; c co on ns st t c ch ha ar r* i id de en nt ti if fi ie er r; / / ... p pu ub bl li ic c: R Re ec c_ _p pt tr r(c co on ns st t c ch ha ar r* p p) : i id de en nt ti if fi ie er r(p p) , i in n_ _c co or re e_ _a ad dd dr re es ss s(0 0) { } ~R Re ec c_ _p pt tr r() { w wr ri it te e_ _t to o_ _d di is sk k(i in n_ _c co or re e_ _a ad dd dr re es ss s,i id de en nt ti if fi ie er r) ; } R Re ec c* o op pe er ra at to or r->() ; }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.290 Operator Overloading Chapter 11 R Re ec c* R Re ec c_ _p pt tr r: :o op pe er ra at to or r->() { i if f (i in n_ _c co or re e_ _a ad dd dr re es ss s == 0 0) i in n_ _c co or re e_ _a ad dd dr re es ss s = r re ea ad d_ _f fr ro om m_ _d di is sk k(i id de en nt ti if fi ie er r) ; r re et tu ur rn n i in n_ _c co or re e_ _a ad dd dr re es ss s; } R Re ec c_ _p pt tr r might be used like this: s st tr ru uc ct t R Re ec c { / / the Rec that a Rec_ptr points to s st tr ri in ng g n na am me e; / / ... }; v vo oi id d u up pd da at te e(c co on ns st t c ch ha ar r* s s) { R Re ec c_ _p pt tr r p p(s s) ; / / get Rec_ptr for s p p->n na am me e = "R Ro os sc co oe e"; / / update s; if necessary, first retrieve from disk / / ... } Naturally, a real R Re ec c_ _p pt tr r would be a template so that the R Re ec c type is a parameter. Also, a realistic program would contain error-handling code and use a less naive way of interacting with the disk. For ordinary pointers, use of -> is synonymous with some uses of unary * and []. Given Y Y* p p; it holds that p p->m m == (*p p).m m == p p[0 0].m m As usual, no such guarantee is provided for user-defined operators. The equivalence can be pro- vided where desired: c cl la as ss s P Pt tr r_ _t to o_ _Y Y { Y Y* p p; p pu ub bl li ic c: Y Y* o op pe er ra at to or r->() { r re et tu ur rn n p p; } Y Y& o op pe er ra at to or r*() { r re et tu ur rn n *p p; } Y Y& o op pe er ra at to or r[](i in nt t i i) { r re et tu ur rn n p p[i i] ; } }; If you provide more than one of these operators, it might be wise to provide the equivalence, just as it is wise to ensure that ++x x and x x+=1 1 have the same effect as x x=x x+1 1 for a simple variable x x of some class if ++, +=, =, and + are provided. The overloading of -> is important to a class of interesting programs and not just a minor curiosity. The reason is that indirection is a key concept and that overloading -> provides a clean, direct, and efficient way of representing indirection in a program. Iterators (Chapter 19) provide an important example of this. Another way of looking at operator -> is to consider it as a way of pro- viding C++ with a limited, but useful, form of delegation (§24.2.4). Operator -> must be a member function. If used, its return type must be a pointer or an object of a class to which you can apply ->. When declared for a template class, o op pe er ra at to or r->() is The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.10 Dereferencing 291 frequently unused, so it makes sense to postpone checking the constraint on the return type until actual use. 11.11 Increment and Decrement [over.incr] Once people invent ‘‘smart pointers,’’ they often decide to provide the increment operator ++ and the decrement operator -- to mirror these operators’ use for built-in types. This is especially obvi- ous and necessary where the aim is to replace an ordinary pointer type with a ‘‘smart pointer’’ type that has the same semantics, except that it adds a bit of run-time error checking. For example, con- sider a troublesome traditional program: v vo oi id d f f1 1(T T a a) / / traditional use { T T v v[2 20 00 0] ; T T* p p = &v v[0 0] ; p p--; *p p = a a; / / Oops: ‘p’ out of range, uncaught ++p p; *p p = a a; / / ok } We might want to replace the pointer p p with an object of a class P Pt tr r_ _t to o_ _T T that can be dereferenced only provided it actually points to an object. We would also like to ensure that p p can be incre- mented and decremented, only provided it points to an object within an array and the increment and decrement operations yield an object within the array. That is we would like something like this: c cl la as ss s P Pt tr r_ _t to o_ _T T { / / ... }; v vo oi id d f f2 2(T T a a) / / checked { T T v v[2 20 00 0] ; P Pt tr r_ _t to o_ _T T p p(&v v[0 0] ,v v,2 20 00 0) ; p p--; *p p = a a; / / run-time error: ‘p’ out of range ++p p; *p p = a a; / / ok } The increment and decrement operators are unique among C++ operators in that they can be used as both prefix and postfix operators. Consequently, we must define prefix and postfix increment and decrement P Pt tr r_ _t to o_ _T T. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.292 Operator Overloading Chapter 11 c cl la as ss s P Pt tr r_ _t to o_ _T T { T T* p p; T T* a ar rr ra ay y; i in nt t s si iz ze e; p pu ub bl li ic c: P Pt tr r_ _t to o_ _T T(T T* p p, T T* v v, i in nt t s s) ; / / bind to array v of size s, initial value p P Pt tr r_ _t to o_ _T T(T T* p p) ; / / bind to single object, initial value p P Pt tr r_ _t to o_ _T T& o op pe er ra at to or r++() ; / / prefix P Pt tr r_ _t to o_ _T T o op pe er ra at to or r++(i in nt t) ; / / postfix P Pt tr r_ _t to o_ _T T& o op pe er ra at to or r--() ; / / prefix P Pt tr r_ _t to o_ _T T o op pe er ra at to or r--(i in nt t) ; / / postfix T T& o op pe er ra at to or r*() ; / / prefix }; The i in nt t argument is used to indicate that the function is to be invoked for postfix application of ++. This i in nt t is never used; the argument is simply a dummy used to distinguish between prefix and postfix application. The way to remember which version of an o op pe er ra at to or r++ is prefix is to note that the version without the dummy argument is prefix, exactly like all the other unary arithmetic and logical operators. The dummy argument is used only for the ‘‘odd’’ postfix ++ and --. Using P Pt tr r_ _t to o_ _T T, the example is equivalent to: v vo oi id d f f3 3(T T a a) / / checked { T T v v[2 20 00 0] ; P Pt tr r_ _t to o_ _T T p p(&v v[0 0] ,v v,2 20 00 0) ; p p.o op pe er ra at to or r--(0 0) ; p p.o op pe er ra at to or r*() = a a; / / run-time error: ‘p’ out of range p p.o op pe er ra at to or r++() ; p p.o op pe er ra at to or r*() = a a; / / ok } Completing class P Pt tr r_ _t to o_ _T T is left as an exercise (§11.14[19]). Its elaboration into a template using exceptions to report the run-time errors is another exercise (§14.12[2]). An example of operators ++ and -- for iteration can be found in §19.3. A pointer template that behaves correctly with respect to inheritance is presented in (§13.6.3). 11.12 A String Class [over.string] Here is a more realistic version of class S St tr ri in ng g. I designed it as the minimal string that served my needs. This string provides value semantics, character read and write operations, checked and unchecked access, stream I/O, literal strings as literals, and equality and concatenation operators. It represents strings as C-style, zero-terminated arrays of characters and uses reference counts to mini- mize copying. Writing a better string class and/or one that provides more facilities is a good exer- cise (§11.14[7-12]). That done, we can throw away our exercises and use the standard library string (Chapter 20). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.12 A String Class 293 My almost-real S St tr ri in ng g employs three auxiliary classes: S Sr re ep p, to allow an actual representation to be shared between several S St tr ri in ng gs with the same value; R Ra an ng ge e, to be thrown in case of range errors, and C Cr re ef f, to help implement a subscript operator that distinguishes between reading and writing: c cl la as ss s S St tr ri in ng g { s st tr ru uc ct t S Sr re ep p; / / representation S Sr re ep p *r re ep p; p pu ub bl li ic c: c cl la as ss s C Cr re ef f; / / reference to char c cl la as ss s R Ra an ng ge e { }; / / for exceptions / / ... }; Like other members, a member class (often called a nested class) can be declared in the class itself and defined later: s st tr ru uc ct t S St tr ri in ng g: :S Sr re ep p { c ch ha ar r* s s; / / pointer to elements i in nt t s sz z; / / number of characters i in nt t n n; / / reference count S Sr re ep p(i in nt t n ns sz z, c co on ns st t c ch ha ar r* p p) { n n = 1 1; s sz z = n ns sz z; s s = n ne ew w c ch ha ar r[s sz z+1 1] ; / / add space for terminator s st tr rc cp py y(s s,p p) ; } ~S Sr re ep p() { d de el le et te e[] s s; } S Sr re ep p* g ge et t_ _o ow wn n_ _c co op py y() / / clone if necessary { i if f (n n==1 1) r re et tu ur rn n t th hi is s; n n--; r re et tu ur rn n n ne ew w S Sr re ep p(s sz z,s s) ; } v vo oi id d a as ss si ig gn n(i in nt t n ns sz z, c co on ns st t c ch ha ar r* p p) { i if f (s sz z != n ns sz z) { d de el le et te e[] s s; s sz z = n ns sz z; s s = n ne ew w c ch ha ar r[s sz z+1 1] ; } s st tr rc cp py y(s s,p p) ; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.294 Operator Overloading Chapter 11 p pr ri iv va at te e: / / prevent copying: S Sr re ep p(c co on ns st t S Sr re ep p&) ; S Sr re ep p& o op pe er ra at to or r=(c co on ns st t S Sr re ep p&) ; }; Class S St tr ri in ng g provides the usual set of constructors, destructor, and assignment operations: c cl la as ss s S St tr ri in ng g { / / ... S St tr ri in ng g() ; / / x = "" S St tr ri in ng g(c co on ns st t c ch ha ar r*) ; / / x = "abc" S St tr ri in ng g(c co on ns st t S St tr ri in ng g&) ; / / x = other_string S St tr ri in ng g& o op pe er ra at to or r=(c co on ns st t c ch ha ar r *) ; S St tr ri in ng g& o op pe er ra at to or r=(c co on ns st t S St tr ri in ng g&) ; ~S St tr ri in ng g() ; / / ... }; This S St tr ri in ng g has value semantics. That is, after an assignment s s1 1=s s2 2, the two strings s s1 1 and s s2 2 are fully distinct and subsequent changes to the one have no effect on the other. The alternative would be to give S St tr ri in ng g pointer semantics. That would be to let changes to s s2 2 after s s1 1=s s2 2 also affect the value of s s1 1. For types with conventional arithmetic operations, such as complex, vector, matrix, and string, I prefer value semantics. However, for the value semantics to be affordable, a S St tr ri in ng g is implemented as a handle to its representation and the representation is copied only when necessary: S St tr ri in ng g: :S St tr ri in ng g() / / the empty string is the default value { r re ep p = n ne ew w S Sr re ep p(0 0,"") ; } S St tr ri in ng g: :S St tr ri in ng g(c co on ns st t S St tr ri in ng g& x x) / / copy constructor { x x.r re ep p->n n++; r re ep p = x x.r re ep p; / / share representation } S St tr ri in ng g: :~S St tr ri in ng g() { i if f (--r re ep p->n n == 0 0) d de el le et te e r re ep p; } S St tr ri in ng g& S St tr ri in ng g: :o op pe er ra at to or r=(c co on ns st t S St tr ri in ng g& x x) / / copy assignment { x x.r re ep p->n n++; / / protects against ‘‘st = st’’ i if f (--r re ep p->n n == 0 0) d de el le et te e r re ep p; r re ep p = x x.r re ep p; / / share representation r re et tu ur rn n *t th hi is s; } Pseudo-copy operations taking c co on ns st t c ch ha ar r* arguments are provided to allow string literals: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.12 A String Class 295 S St tr ri in ng g: :S St tr ri in ng g(c co on ns st t c ch ha ar r* s s) { r re ep p = n ne ew w S Sr re ep p(s st tr rl le en n(s s) ,s s) ; } S St tr ri in ng g& S St tr ri in ng g: :o op pe er ra at to or r=(c co on ns st t c ch ha ar r* s s) { i if f (r re ep p->n n == 1 1) / / recycle Srep r re ep p->a as ss si ig gn n(s st tr rl le en n(s s) ,s s) ; e el ls se e { / / use new Srep r re ep p->n n--; r re ep p = n ne ew w S Sr re ep p(s st tr rl le en n(s s) ,s s) ; } r re et tu ur rn n *t th hi is s; } The design of access operators for a string is a difficult topic because ideally access is by conven- tional notation (that is, using []), maximally efficient, and range checked. Unfortunately, you can- not have all of these properties simultaneously. My choice here has been to provide efficient unchecked operations with a slightly inconvenient notation plus slightly less efficient checked oper- ators with the conventional notation: c cl la as ss s S St tr ri in ng g { / / ... v vo oi id d c ch he ec ck k(i in nt t i i) c co on ns st t { i if f (i i<0 0 || r re ep p->s sz z<=i i) t th hr ro ow w R Ra an ng ge e() ; } c ch ha ar r r re ea ad d(i in nt t i i) c co on ns st t { r re et tu ur rn n r re ep p->s s[i i] ; } v vo oi id d w wr ri it te e(i in nt t i i, c ch ha ar r c c) { r re ep p=r re ep p->g ge et t_ _o ow wn n_ _c co op py y() ; r re ep p->s s[i i]=c c; } C Cr re ef f o op pe er ra at to or r[](i in nt t i i) { c ch he ec ck k(i i) ; r re et tu ur rn n C Cr re ef f(*t th hi is s,i i) ; } c ch ha ar r o op pe er ra at to or r[](i in nt t i i) c co on ns st t { c ch he ec ck k(i i) ; r re et tu ur rn n r re ep p->s s[i i] ; } i in nt t s si iz ze e() c co on ns st t { r re et tu ur rn n r re ep p->s sz z; } / / ... }; The idea is to use [] to get checked access for ordinary use, but to allow the user to optimize by checking the range once for a set of accesses. For example: i in nt t h ha as sh h(c co on ns st t S St tr ri in ng g& s s) { i in nt t h h = s s.r re ea ad d(0 0) ; c co on ns st t i in nt t m ma ax x = s s.s si iz ze e() ; f fo or r (i in nt t i i = 1 1; i i>1 1; / / unchecked access to s r re et tu ur rn n h h; } Defining an operator, such as [], to be used for both reading and writing is difficult where it is not acceptable simply to return a reference and let the user decide what to do with it. Here, that is not a reasonable alternative because I have defined S St tr ri in ng g so that the representation is shared between S St tr ri in ng gs that have been assigned, passed as value arguments, etc., until someone actually writes to a The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.296 Operator Overloading Chapter 11 S St tr ri in ng g. Then, and only then, is the representation copied. This technique is usually called copy- on-write. The actual copy is done by S St tr ri in ng g: :S Sr re ep p: :g ge et t_ _o ow wn n_ _c co op py y(). To get these access functions inlined, their definitions must be placed so that the definition of S Sr re ep p is in scope. This implies that either S Sr re ep p is defined within S St tr ri in ng g or the access functions are defined i in nl li in ne e outside S St tr ri in ng g and after S St tr ri in ng g: :S Sr re ep p (§11.14[2]). To distinguish between a read and a write, S St tr ri in ng g: :o op pe er ra at to or r[]() returns a C Cr re ef f when called for a non-c co on ns st t object. A C Cr re ef f behaves like a c ch ha ar r&, except that it calls S St tr ri in ng g: :S Sr re ep p: :g ge et t_ _o ow wn n_ _c co op py y() when written to: c cl la as ss s S St tr ri in ng g: :C Cr re ef f { / / reference to s[i] f fr ri ie en nd d c cl la as ss s S St tr ri in ng g; S St tr ri in ng g& s s; i in nt t i i; C Cr re ef f(S St tr ri in ng g& s ss s, i in nt t i ii i) : s s(s ss s) , i i(i ii i) { } p pu ub bl li ic c: o op pe er ra at to or r c ch ha ar r() { r re et tu ur rn n s s.r re ea ad d(i i) ; } / / yield value v vo oi id d o op pe er ra at to or r=(c ch ha ar r c c) { s s.w wr ri it te e(i i,c c) ; } / / change value }; For example: v vo oi id d f f(S St tr ri in ng g s s, c co on ns st t S St tr ri in ng g& r r) { i in nt t c c1 1 = s s[1 1] ; / / c1 = s.operator[](1).operator char() s s[1 1] = ´c c´; / / s.operator[](1).operator=(’c’) i in nt t c c2 2 = r r[1 1] ; / / c2 = r.operator[](1) r r[1 1] = ´d d´; / / error: assignment to char, r.operator[](1) = ’d’ } Note that for a non-c co on ns st t object s s.o op pe er ra at to or r[](1 1) is C Cr re ef f(s s,1 1). To complete class S St tr ri in ng g, I provide a set of useful functions: c cl la as ss s S St tr ri in ng g { / / ... S St tr ri in ng g& o op pe er ra at to or r+=(c co on ns st t S St tr ri in ng g&) ; S St tr ri in ng g& o op pe er ra at to or r+=(c co on ns st t c ch ha ar r*) ; f fr ri ie en nd d o os st tr re ea am m& o op pe er ra at to or r<<(o os st tr re ea am m&, c co on ns st t S St tr ri in ng g&) ; f fr ri ie en nd d i is st tr re ea am m& o op pe er ra at to or r>>(i is st tr re ea am m&, S St tr ri in ng g&) ; f fr ri ie en nd d b bo oo ol l o op pe er ra at to or r==(c co on ns st t S St tr ri in ng g& x x, c co on ns st t c ch ha ar r* s s) { r re et tu ur rn n s st tr rc cm mp p(x x.r re ep p->s s, s s) == 0 0; } f fr ri ie en nd d b bo oo ol l o op pe er ra at to or r==(c co on ns st t S St tr ri in ng g& x x, c co on ns st t S St tr ri in ng g& y y) { r re et tu ur rn n s st tr rc cm mp p(x x.r re ep p->s s, y y.r re ep p->s s) == 0 0; } f fr ri ie en nd d b bo oo ol l o op pe er ra at to or r!=(c co on ns st t S St tr ri in ng g& x x, c co on ns st t c ch ha ar r* s s) { r re et tu ur rn n s st tr rc cm mp p(x x.r re ep p->s s, s s) != 0 0; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.12 A String Class 297 f fr ri ie en nd d b bo oo ol l o op pe er ra at to or r!=(c co on ns st t S St tr ri in ng g& x x, c co on ns st t S St tr ri in ng g& y y) { r re et tu ur rn n s st tr rc cm mp p(x x.r re ep p->s s, y y.r re ep p->s s) != 0 0; } }; S St tr ri in ng g o op pe er ra at to or r+(c co on ns st t S St tr ri in ng g&, c co on ns st t S St tr ri in ng g&) ; S St tr ri in ng g o op pe er ra at to or r+(c co on ns st t S St tr ri in ng g&, c co on ns st t c ch ha ar r*) ; To save space, I have left the I/O and concatenation operations as exercises. The main program simply exercises the S St tr ri in ng g operators a bit: S St tr ri in ng g f f(S St tr ri in ng g a a, S St tr ri in ng g b b) { a a[2 2] = ´x x´; c ch ha ar r c c = b b[3 3] ; c co ou ut t << "i in n f f: " << a a << ´ ´ << b b << ´ ´ << c c << ´\ \n n´; r re et tu ur rn n b b; } i in nt t m ma ai in n() { S St tr ri in ng g x x, y y; c co ou ut t << "P Pl le ea as se e e en nt te er r t tw wo o s st tr ri in ng gs s\ \n n"; c ci in n >> x x >> y y; c co ou ut t << "i in np pu ut t: " << x x << ´ ´ << y y << ´\ \n n´; S St tr ri in ng g z z = x x; y y = f f(x x,y y) ; i if f (x x != z z) c co ou ut t << "x x c co or rr ru up pt te ed d!\ \n n"; x x[0 0] = ´!´; i if f (x x == z z) c co ou ut t << "w wr ri it te e f fa ai il le ed d!\ \n n"; c co ou ut t << "e ex xi it t: " << x x << ´ ´ << y y << ´ ´ << z z << ´\ \n n´; } This S St tr ri in ng g lacks many features that you might consider important or even essential. For example, it offers no operation of producing a C-string representation of its value (§11.14[10], Chapter 20). 11.13 Advice [class.advice] [1] Define operators primarily to mimic conventional usage; §11.1. [2] For large operands, use c co on ns st t reference argument types; §11.6. [3] For large results, consider optimizing the return; §11.6. [4] Prefer the default copy operations if appropriate for a class; §11.3.4. [5] Redefine or prohibit copying if the default is not appropriate for a type; §11.2.2. [6] Prefer member functions over nonmembers for operations that need access to the representa- tion; §11.5.2. [7] Prefer nonmember functions over members for operations that do not need access to the repre- sentation; §11.5.2. [8] Use namespaces to associate helper functions with ‘‘their’’ class; §11.2.4. [9] Use nonmember functions for symmetric operators; §11.3.2. [10] Use () for subscripting multidimensional arrays; §11.9. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.298 Operator Overloading Chapter 11 [11] Make constructors that take a single ‘‘size argument’’ e ex xp pl li ic ci it t; §11.7.1. [12] For non-specialized uses, prefer the standard s st tr ri in ng g (Chapter 20) to the result of your own exercises; §11.12. [13] Be cautious about introducing implicit conversions; §11.4. [14] Use member functions to express operators that require an lvalue as its left-hand operand; §11.3.5. 11.14 Exercises [over.exercises] 1. (∗2) In the following program, which conversions are used in each expression? s st tr ru uc ct t X X { i in nt t i i; X X(i in nt t) ; o op pe er ra at to or r+(i in nt t) ; }; s st tr ru uc ct t Y Y { i in nt t i i; Y Y(X X) ; o op pe er ra at to or r+(X X) ; o op pe er ra at to or r i in nt t() ; }; e ex xt te er rn n X X o op pe er ra at to or r*(X X, Y Y) ; e ex xt te er rn n i in nt t f f(X X) ; X X x x = 1 1; Y Y y y = x x; i in nt t i i = 2 2; i in nt t m ma ai in n() { i i + 1 10 0; y y + 1 10 0; y y + 1 10 0 * y y; x x + y y + i i; x x * x x + i i; f f(7 7) ; f f(y y) ; y y + y y; 1 10 06 6 + y y; } Modify the program so that it will run and print the values of each legal expression. 2. (∗2) Complete and test class S St tr ri in ng g from §11.12. 3. (∗2) Define a class I IN NT T that behaves exactly like an i in nt t. Hint: Define I IN NT T: :o op pe er ra at to or r i in nt t(). 4. (∗1) Define a class R RI IN NT T that behaves like an i in nt t except that the only operations allowed are + (unary and binary), - (unary and binary), *, /, and %. Hint: Do not define R RI IN NT T: :o op pe er ra at to or r i in nt t(). 5. (∗3) Define a class L LI IN NT T that behaves like a R RI IN NT T, except that it has at least 64 bits of preci- sion. 6. (∗4) Define a class implementing arbitrary precision arithmetic. Test it by calculating the facto- rial of 1 10 00 00 0. Hint: You will need to manage storage in a way similar to what was done for class S St tr ri in ng g. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 11.14 Exercises 299 7. (∗2) Define an external iterator for class S St tr ri in ng g: c cl la as ss s S St tr ri in ng g_ _i it te er r { / / refer to string and string element p pu ub bl li ic c: S St tr ri in ng g_ _i it te er r(S St tr ri in ng g& s s) ; / / iterator for s c ch ha ar r& n ne ex xt t() ; / / reference to next element / / more operations of your choice }; Compare this in utility, programming style, and efficiency to having an internal iterator for S St tr ri in ng g (that is, a notion of a current element for the S St tr ri in ng g and operations relating to that ele- ment). 8. (∗1.5) Provide a substring operator for a string class by overloading (). What other operations would you like to be able to do on a string? 9. (∗3) Design class S St tr ri in ng g so that the substring operator can be used on the left-hand side of an assignment. First, write a version in which a string can be assigned to a substring of the same length. Then, write a version in which the lengths may differ. 10. (∗2) Define an operation for S St tr ri in ng g that produces a C-string representation of its value. Discuss the pros and cons of having that operation as a conversion operator. Discuss alternatives for allocating the memory for that C-string representation. 11. (∗2.5) Define and implement a simple regular expression pattern match facility for class S St tr ri in ng g. 12. (∗1.5) Modify the pattern match facility from §11.14[11] to work on the standard library s st tr ri in ng g. Note that you cannot modify the definition of s st tr ri in ng g. 13. (∗2) Write a program that has been rendered unreadable through use of operator overloading and macros. An idea: Define + to mean - and vice versa for I IN NT Ts s. Then, use a macro to define i in nt t to mean I IN NT T. Redefine popular functions using reference type arguments. Writing a few misleading comments can also create great confusion. 14. (∗3) Swap the result of §11.14[13] with a friend. Without running it, figure out what your friend’s program does. When you have completed this exercise, you’ll know what to avoid. 15. (∗2) Define a type V Ve ec c4 4 as a vector of four f fl lo oa at ts. Define o op pe er ra at to or r[] for V Ve ec c4 4. Define opera- tors +, -, *, /, =, +=, -=, *=, and /= for combinations of vectors and floating-point numbers. 16. (∗3) Define a class M Ma at t4 4 as a vector of four V Ve ec c4 4s. Define o op pe er ra at to or r[] to return a V Ve ec c4 4 for M Ma at t4 4. Define the usual matrix operations for this type. Define a function doing Gaussian elim- ination for a M Ma at t4 4. 17. (∗2) Define a class V Ve ec ct to or r similar to V Ve ec c4 4 but with the size given as an argument to the con- structor V Ve ec ct to or r: :V Ve ec ct to or r(i in nt t). 18. (∗3) Define a class M Ma at tr ri ix x similar to M Ma at t4 4 but with the dimensions given as arguments to the constructor M Ma at tr ri ix x: :M Ma at tr ri ix x(i in nt t,i in nt t). 19. (∗2) Complete class P Pt tr r_ _t to o_ _T T from §11.11 and test it. To be complete, P Pt tr r_ _t to o_ _T T must have at least the operators *, ->, =, ++, and -- defined. Do not cause a run-time error until a wild pointer is actually dereferenced. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.300 Operator Overloading Chapter 11 20. (∗1) Given two structures: s st tr ru uc ct t S S { i in nt t x x, y y; }; s st tr ru uc ct t T T { c ch ha ar r* p p; c ch ha ar r* q q; }; write a class C C that allows the use of x x and p p from some S S and T T, much as if x x and p p had been members of C C. 21. (∗1.5) Define a class I In nd de ex x to hold the index for an exponentiation function m my yp po ow w(d do ou ub bl le e,I In nd de ex x). Find a way to have 2 2**I I call m my yp po ow w(2 2,I I). 22. (∗2) Define a class I Im ma ag gi in na ar ry y to represent imaginary numbers. Define class C Co om mp pl le ex x based on that. Implement the fundamental arithmetic operators. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 12 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Derived Classes Do not multiply objects without necessity. ± W. Occam Concepts and classes Ð derived classes Ð member functions Ð construction and destruction Ð class hierarchies Ð type fields Ð virtual functions Ð abstract classes Ð traditional class hierarchies Ð abstract classes as interfaces Ð localizing object creation Ð abstract classes and class hierarchies Ð advice Ð exercises. 12.1 Introduction [derived.intro] From Simula, C++ borrowed the concept of a class as a user-defined type and the concept of class hierarchies. In addition, it borrowed the idea for system design that classes should be used to model concepts in the programmer’s and the application’s world. C++ provides language con- structs that directly support these design notions. Conversely, using the language features in sup- port of design concepts distinguishes effective use of C++. Using language constructs only as nota- tional props for more traditional types of programming is to miss key strengths of C++. A concept does not exist in isolation. It coexists with related concepts and derives much of its power from relationships with related concepts. For example, try to explain what a car is. Soon you’ll have introduced the notions of wheels, engines, drivers, pedestrians, trucks, ambulances, roads, oil, speeding tickets, motels, etc. Since we use classes to represent concepts, the issue becomes how to represent relationships between concepts. However, we can’t express arbitrary relationships directly in a programming language. Even if we could, we wouldn’t want to. Our classes should be more narrowly defined than our everyday concepts ± and more precise. The notion of a derived class and its associated language mechanisms are provided to express hierarchi- cal relationships, that is, to express commonality between classes. For example, the concepts of a circle and a triangle are related in that they are both shapes; that is, they have the concept of a shape in common. Thus, we must explicitly define class C Ci ir rc cl le e and class T Tr ri ia an ng gl le e to have class S Sh ha ap pe e in The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.302 Derived Classes Chapter 12 common. Representing a circle and a triangle in a program without involving the notion of a shape would be to lose something essential. This chapter is an exploration of the implications of this sim- ple idea, which is the basis for what is commonly called object-oriented programming. The presentation of language features and techniques progress from the simple and concrete to the more sophisticated and abstract. For many programmers, this will also be a progression from the familiar towards the less well known. This is not a simple journey from ‘‘bad old techniques’’ towards ‘‘the one right way.’’ When I point out limitations of one technique as a motivation for another, I do so in the context of specific problems; for different problems or in other contexts, the first technique may indeed be the better choice. Useful software has been constructed using all of the techniques presented here. The aim is to help you attain sufficient understanding of the tech- niques to be able to make intelligent and balanced choices among them for real problems. In this chapter, I first introduce the basic language features supporting object-oriented program- ming. Next, the use of those features to develop well-structured programs is discussed in the con- text of a larger example. Further facilities supporting object-oriented programming, such as multi- ple inheritance and run-time type identification, are discussed in Chapter 15. 12.2 Derived Classes [derived.derived] Consider building a program dealing with people employed by a firm. Such a program might have a data structure like this: s st tr ru uc ct t E Em mp pl lo oy ye ee e { s st tr ri in ng g f fi ir rs st t_ _n na am me e, f fa am mi il ly y_ _n na am me e; c ch ha ar r m mi id dd dl le e_ _i in ni it ti ia al l; D Da at te e h hi ir ri in ng g_ _d da at te e; s sh ho or rt t d de ep pa ar rt tm me en nt t; / / ... }; Next, we might try to define a manager: s st tr ru uc ct t M Ma an na ag ge er r { E Em mp pl lo oy ye ee e e em mp p; / / manager’s employee record s se et t g gr ro ou up p; / / people managed s sh ho or rt t l le ev ve el l; / / ... }; A manager is also an employee; the E Em mp pl lo oy ye ee e data is stored in the e em mp p member of a M Ma an na ag ge er r object. This may be obvious to a human reader ± especially a careful reader ± but there is nothing that tells the compiler and other tools that M Ma an na ag ge er r is also an E Em mp pl lo oy ye ee e. A M Ma an na ag ge er r* is not an E Em mp pl lo oy ye ee e*, so one cannot simply use one where the other is required. In particular, one cannot put a M Ma an na ag ge er r onto a list of E Em mp pl lo oy ye ee es without writing special code. We could either use explicit type conversion on a M Ma an na ag ge er r* or put the address of the e em mp p member onto a list of e em mp pl lo oy ye ee es. However, both solutions are inelegant and can be quite obscure. The correct approach is to explic- itly state that a M Ma an na ag ge er risan E Em mp pl lo oy ye ee e, with a few pieces of information added: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 12.2 Derived Classes 303 s st tr ru uc ct t M Ma an na ag ge er r : p pu ub bl li ic c E Em mp pl lo oy ye ee e { s se et t g gr ro ou up p; s sh ho or rt t l le ev ve el l; / / ... }; The M Ma an na ag ge er r is derived from E Em mp pl lo oy ye ee e, and conversely, E Em mp pl lo oy ye ee e is a base class for M Ma an na ag ge er r. The class M Ma an na ag ge er r has the members of class E Em mp pl lo oy ye ee e (n na am me e, a ag ge e, etc.) in addition to its own members (g gr ro ou up p, l le ev ve el l, etc.). Derivation is often represented graphically by a pointer from the derived class to its base class indicating that the derived class refers to its base (rather than the other way around): E Em mp pl lo oy ye ee e M Ma an na ag ge er r .. A derived class is often said to inherit properties from its base, so the relationship is also called inheritance. A base class is sometimes called a superclass and a derived class a subclass. This ter- minology, however, is confusing to people who observe that the data in a derived class object is a superset of the data of an object of its base class. A derived class is larger than its base class in the sense that it holds more data and provides more functions. A popular and efficient implementation of the notion of derived classes has an object of the derived class represented as an object of the base class, with the information belonging specifically to the derived class added at the end. For example: f fi ir rs st t_ _n na am me e f fa am mi il ly y_ _n na am me e ... f fi ir rs st t_ _n na am me e f fa am mi il ly y_ _n na am me e ... g gr ro ou up p l le ev ve el l ... E Em mp pl lo oy ye ee e: M Ma an na ag ge er r: Deriving M Ma an na ag ge er r from E Em mp pl lo oy ye ee e in this way makes M Ma an na ag ge er r a subtype of E Em mp pl lo oy ye ee e so that a M Ma an na ag ge er r can be used wherever an E Em mp pl lo oy ye ee e is acceptable. For example, we can now create a list of E Em mp pl lo oy ye ee es, some of whom are M Ma an na ag ge er rs: v vo oi id d f f(M Ma an na ag ge er r m m1 1, E Em mp pl lo oy ye ee e e e1 1) { l li is st t e el li is st t; e el li is st t.p pu us sh h_ _f fr ro on nt t(&m m1 1) ; e el li is st t.p pu us sh h_ _f fr ro on nt t(&e e1 1) ; / / ... } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.304 Derived Classes Chapter 12 A M Ma an na ag ge er r is (also) an E Em mp pl lo oy ye ee e, so a M Ma an na ag ge er r* can be used as a E Em mp pl lo oy ye ee e*. However, an E Em mp pl lo oy ye ee e is not necessarily a M Ma an na ag ge er r, so an E Em mp pl lo oy ye ee e* cannot be used as a M Ma an na ag ge er r*. In gen- eral, if a class D De er ri iv ve ed d has a public base class (§15.3) B Ba as se e, then a D De er ri iv ve ed d* can be assigned to a variable of type B Ba as se e* without the use of explicit type conversion. The opposite conversion, from B Ba as se e* to D De er ri iv ve ed d*, must be explicit. For example: v vo oi id d g g(M Ma an na ag ge er r m mm m, E Em mp pl lo oy ye ee e e ee e) { E Em mp pl lo oy ye ee e* p pe e = &m mm m; / / ok: every Manager is an Employee M Ma an na ag ge er r* p pm m = &e ee e; / / error: not every Employee is a Manager p pm m->l le ev ve el l = 2 2; / / disaster: ee doesn’t have a ‘level’ p pm m = s st ta at ti ic c_ _c ca as st t(p pe e) ; / / brute force: works because pe points / / to the Manager mm p pm m->l le ev ve el l = 2 2; / / fine: pm points to the Manager mm that has a ‘level’ } In other words, an object of a derived class can be treated as an object of its base class when manip- ulated through pointers and references. The opposite is not true. The use of s st ta at ti ic c_ _c ca as st t and d dy yn na am mi ic c_ _c ca as st t is discussed in §15.4.2. Using a class as a base is equivalent to declaring an (unnamed) object of that class. Conse- quently, a class must be defined in order to be used as a base (§5.7): c cl la as ss s E Em mp pl lo oy ye ee e; / / declaration only, no definition c cl la as ss s M Ma an na ag ge er r : p pu ub bl li ic c E Em mp pl lo oy ye ee e { / / error: Employee not defined / / ... }; 12.2.1 Member Functions [derived.member] Simple data structures, such as E Em mp pl lo oy ye ee e and M Ma an na ag ge er r, are really not that interesting and often not particularly useful. We need to give the information as a proper type that provides a suitable set of operations that present the concept, and we need to do this without tying us to the details of a par- ticular representation. For example: c cl la as ss s E Em mp pl lo oy ye ee e { s st tr ri in ng g f fi ir rs st t_ _n na am me e, f fa am mi il ly y_ _n na am me e; c ch ha ar r m mi id dd dl le e_ _i in ni it ti ia al l; / / ... p pu ub bl li ic c: v vo oi id d p pr ri in nt t() c co on ns st t; s st tr ri in ng g f fu ul ll l_ _n na am me e() c co on ns st t { r re et tu ur rn n f fi ir rs st t_ _n na am me e + ´ ´ + m mi id dd dl le e_ _i in ni it ti ia al l + ´ ´ + f fa am mi il ly y_ _n na am me e; } / / ... }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 12.2.1 Member Functions 305 c cl la as ss s M Ma an na ag ge er r : p pu ub bl li ic c E Em mp pl lo oy ye ee e { / / ... p pu ub bl li ic c: v vo oi id d p pr ri in nt t() c co on ns st t; / / ... }; A member of a derived class can use the public ± and protected (see §15.3) ± members of its base class as if they were declared in the derived class itself. For example: v vo oi id d M Ma an na ag ge er r: :p pr ri in nt t() c co on ns st t { c co ou ut t << "n na am me e i is s " << f fu ul ll l_ _n na am me e() << ´\ \n n´; / / ... } However, a derived class cannot use a base class’ private names: v vo oi id d M Ma an na ag ge er r: :p pr ri in nt t() c co on ns st t { c co ou ut t << " n na am me e i is s " << f fa am mi il ly y_ _n na am me e << ´\ \n n´; / / error! / / ... } This second version of M Ma an na ag ge er r: :p pr ri in nt t() will not compile. A member of a derived class has no special permission to access private members of its base class, so f fa am mi il ly y_ _n na am me e is not accessible to M Ma an na ag ge er r: :p pr ri in nt t(). This comes as a surprise to some, but consider the alternative: that a member function of a derived class could access the private members of its base class. The concept of a private member would be rendered meaningless by allowing a programmer to gain access to the private part of a class simply by deriving a new class from it. Furthermore, one could no longer find all uses of a private name by looking at the functions declared as members and friends of that class. One would have to examine every source file of the complete program for derived classes, then examine every function of those classes, then find every class derived from those classes, etc. This is, at best, tedious and often impractical. Where it is acceptable, p pr ro ot te ec ct te ed d ± rather than p pr ri iv va at te e ± members can be used. A protected member is like a public member to a member of a derived class, yet it is like a private member to other functions (see §15.3). Typically, the cleanest solution is for the derived class to use only the public members of its base class. For example: v vo oi id d M Ma an na ag ge er r: :p pr ri in nt t() c co on ns st t { E Em mp pl lo oy ye ee e: :p pr ri in nt t() ; / / print Employee information c co ou ut t << l le ev ve el l; / / print Manager-specific information / / ... } Note that : : must be used because p pr ri in nt t() has been redefined in M Ma an na ag ge er r. Such reuse of names is typical. The unwary might write this: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.306 Derived Classes Chapter 12 v vo oi id d M Ma an na ag ge er r: :p pr ri in nt t() c co on ns st t { p pr ri in nt t() ; / / oops! / / print Manager-specific information } and find the program involved in an unexpected sequence of recursive calls. 12.2.2 Constructors and Destructors [derived.ctor] Some derived classes need constructors. If a base class has constructors, then a constructor must be invoked. Default constructors can be invoked implicitly. However, if all constructors for a base require arguments, then a constructor for that base must be explicitly called. Consider: c cl la as ss s E Em mp pl lo oy ye ee e { s st tr ri in ng g f fi ir rs st t_ _n na am me e, f fa am mi il ly y_ _n na am me e; s sh ho or rt t d de ep pa ar rt tm me en nt t; / / ... p pu ub bl li ic c: E Em mp pl lo oy ye ee e(c co on ns st t s st tr ri in ng g& n n, i in nt t d d) ; / / ... }; c cl la as ss s M Ma an na ag ge er r : p pu ub bl li ic c E Em mp pl lo oy ye ee e { s se et t g gr ro ou up p; / / people managed s sh ho or rt t l le ev ve el l; / / ... p pu ub bl li ic c: M Ma an na ag ge er r(c co on ns st t s st tr ri in ng g& n n, i in nt t d d, i in nt t l lv vl l) ; / / ... }; Arguments for the base class’ constructor are specified in the definition of a derived class’ con- structor. In this respect, the base class acts exactly like a member of the derived class (§10.4.6). For example: E Em mp pl lo oy ye ee e: :E Em mp pl lo oy ye ee e(c co on ns st t s st tr ri in ng g& n n, i in nt t d d) : f fa am mi il ly y_ _n na am me e(n n) , d de ep pa ar rt tm me en nt t(d d) / / initialize members { / / ... } M Ma an na ag ge er r: :M Ma an na ag ge er r(c co on ns st t s st tr ri in ng g& n n, i in nt t d d, i in nt t l lv vl l) : E Em mp pl lo oy ye ee e(n n,d d) , / / initialize base l le ev ve el l(l lv vl l) / / initialize members { / / ... } A derived class constructor can specify initializers for its own members and immediate bases only; it cannot directly initialize members of a base. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 12.2.2 Constructors and Destructors 307 M Ma an na ag ge er r: :M Ma an na ag ge er r(c co on ns st t s st tr ri in ng g& n n, i in nt t d d, i in nt t l lv vl l) : f fa am mi il ly y_ _n na am me e(n n) , / / error: family_name not declared in manager d de ep pa ar rt tm me en nt t(d d) , / / error: department not declared in manager l le ev ve el l(l lv vl l) { / / ... } This definition contains three errors: it fails to invoke E Em mp pl lo oy ye ee e´s s constructor, and twice it attempts to initialize members of E Em mp pl lo oy ye ee e directly. Class objects are constructed from the bottom up: first the base, then the members, and then the derived class itself. They are destroyed in the opposite order: first the derived class itself, then the members, and then the base. Members and bases are constructed in order of declaration in the class and destroyed in the reverse order. See also §10.4.6 and §15.2.4.1. 12.2.3 Copying [derived.copy] Copying of class objects is defined by the copy constructor and assignments (§10.4.4.1). Consider: c cl la as ss s E Em mp pl lo oy ye ee e { / / ... E Em mp pl lo oy ye ee e& o op pe er ra at to or r=(c co on ns st t E Em mp pl lo oy ye ee e&) ; E Em mp pl lo oy ye ee e(c co on ns st t E Em mp pl lo oy ye ee e&) ; }; v vo oi id d f f(c co on ns st t M Ma an na ag ge er r& m m) { E Em mp pl lo oy ye ee e e e = m m; / / construct e from Employee part of m e e = m m; / / assign Employee part of m to e } Because the E Em mp pl lo oy ye ee e copy functions do not know anything about M Ma an na ag ge er rs, only the E Em mp pl lo oy ye ee e part of a M Ma an na ag ge er r is copied. This is commonly referred to as slicing and can be a source of sur- prises and errors. One reason to pass pointers and references to objects of classes in a hierarchy is to avoid slicing. Other reasons are to preserve polymorphic behavior (§2.5.4, §12.2.6) and to gain efficiency. 12.2.4 Class Hierarchies [derived.hierarchy] A derived class can itself be a base class. For example: c cl la as ss s E Em mp pl lo oy ye ee e { /* ... */ }; c cl la as ss s M Ma an na ag ge er r : p pu ub bl li ic c E Em mp pl lo oy ye ee e { /* ... */ }; c cl la as ss s D Di ir re ec ct to or r : p pu ub bl li ic c M Ma an na ag ge er r { /* ... */ }; Such a set of related classes is traditionally called a class hierarchy. Such a hierarchy is most often a tree, but it can also be a more general graph structure. For example: c cl la as ss s T Te em mp po or ra ar ry y { /* ... */ }; c cl la as ss s S Se ec cr re et ta ar ry y : p pu ub bl li ic c E Em mp pl lo oy ye ee e { /* ... */ }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.308 Derived Classes Chapter 12 c cl la as ss s T Ts se ec c : p pu ub bl li ic c T Te em mp po or ra ar ry y, p pu ub bl li ic c S Se ec cr re et ta ar ry y { /* ... */ }; c cl la as ss s C Co on ns su ul lt ta an nt t : p pu ub bl li ic c T Te em mp po or ra ar ry y, p pu ub bl li ic c M Ma an na ag ge er r { /* ... */ }; Or graphically: T Te em mp po or ra ar ry y E Em mp pl lo oy ye ee e T Ts se ec c S Se ec cr re et ta ar ry y M Ma an na ag ge er r C Co on ns su ul lt ta an nt t D Di ir re ec ct to or r .. Thus, as is explained in detail in §15.2, C++ can express a directed acyclic graph of classes. 12.2.5 Type Fields [derived.typefield] To use derived classes as more than a convenient shorthand in declarations, we must solve the fol- lowing problem: Given a pointer of type b ba as se e*, to which derived type does the object pointed to really belong? There are four fundamental solutions to the problem: [1] Ensure that only objects of a single type are pointed to (§2.7, Chapter 13). [2] Place a type field in the base class for the functions to inspect. [3] Use d dy yn na am mi ic c_ _c ca as st t (§15.4.2, §15.4.5). [4] Use virtual functions (§2.5.5, §12.2.6). Pointers to base classes are commonly used in the design of container classes such as set, vector, and list. In this case, solution 1 yields homogeneous lists, that is, lists of objects of the same type. Solutions 2, 3, and 4 can be used to build heterogeneous lists, that is, lists of (pointers to) objects of several different types. Solution 3 is a language-supported variant of solution 2. Solution 4 is a special type-safe variation of solution 2. Combinations of solutions 1 and 4 are particularly inter- esting and powerful; in almost all situations, they yield cleaner code than do solutions 2 and 3. Let us first examine the simple type-field solution to see why it is most often best avoided. The manager/employee example could be redefined like this: s st tr ru uc ct t E Em mp pl lo oy ye ee e { e en nu um m E Em mp pl l_ _t ty yp pe e { M M, E E }; E Em mp pl l_ _t ty yp pe e t ty yp pe e; E Em mp pl lo oy ye ee e() : t ty yp pe e(E E) { } s st tr ri in ng g f fi ir rs st t_ _n na am me e, f fa am mi il ly y_ _n na am me e; c ch ha ar r m mi id dd dl le e_ _i in ni it ti ia al l; D Da at te e h hi ir ri in ng g_ _d da at te e; s sh ho or rt t d de ep pa ar rt tm me en nt t; / / ... }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 12.2.5 Type Fields 309 s st tr ru uc ct t M Ma an na ag ge er r : p pu ub bl li ic c E Em mp pl lo oy ye ee e { M Ma an na ag ge er r() { t ty yp pe e = M M; } s se et t g gr ro ou up p; / / people managed s sh ho or rt t l le ev ve el l; / / ... }; Given this, we can now write a function that prints information about each E Em mp pl lo oy ye ee e: v vo oi id d p pr ri in nt t_ _e em mp pl lo oy ye ee e(c co on ns st t E Em mp pl lo oy ye ee e* e e) { s sw wi it tc ch h (e e->t ty yp pe e) { c ca as se e E Em mp pl lo oy ye ee e: :E E: c co ou ut t << e e->f fa am mi il ly y_ _n na am me e << ´\ \t t´ << e e->d de ep pa ar rt tm me en nt t << ´\ \n n´; / / ... b br re ea ak k; c ca as se e E Em mp pl lo oy ye ee e: :M M: { c co ou ut t << e e->f fa am mi il ly y_ _n na am me e << ´\ \t t´ << e e->d de ep pa ar rt tm me en nt t << ´\ \n n´; / / ... c co on ns st t M Ma an na ag ge er r* p p = s st ta at ti ic c_ _c ca as st t(e e) ; c co ou ut t << " l le ev ve el l " << p p->l le ev ve el l << ´\ \n n´; / / ... b br re ea ak k; } } } and use it to print a list of E Em mp pl lo oy ye ee es, like this: v vo oi id d p pr ri in nt t_ _l li is st t(c co on ns st t l li is st t& e el li is st t) { f fo or r (l li is st t: :c co on ns st t_ _i it te er ra at to or r p p = e el li is st t.b be eg gi in n() ; p p!=e el li is st t.e en nd d() ; ++p p) p pr ri in nt t_ _e em mp pl lo oy ye ee e(*p p) ; } This works fine, especially in a small program maintained by a single person. However, it has the fundamental weakness in that it depends on the programmer manipulating types in a way that can- not be checked by the compiler. This problem is usually made worse because functions such as p pr ri in nt t_ _e em mp pl lo oy ye ee e() are organized to take advantage of the commonality of the classes involved. For example: v vo oi id d p pr ri in nt t_ _e em mp pl lo oy ye ee e(c co on ns st t E Em mp pl lo oy ye ee e* e e) { c co ou ut t << e e->f fa am mi il ly y_ _n na am me e << ´\ \t t´ << e e->d de ep pa ar rt tm me en nt t << ´\ \n n´; / / ... i if f (e e->t ty yp pe e == E Em mp pl lo oy ye ee e: :M M) { c co on ns st t M Ma an na ag ge er r* p p = s st ta at ti ic c_ _c ca as st t(e e) ; c co ou ut t << " l le ev ve el l " << p p->l le ev ve el l << ´\ \n n´; / / ... } } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.310 Derived Classes Chapter 12 Finding all such tests on the type field buried in a large function that handles many derived classes can be difficult. Even when they have been found, understanding what is going on can be difficult. Furthermore, any addition of a new kind of E Em mp pl lo oy ye ee e involves a change to all the key functions in the system ± the ones containing the tests on the type field. The programmer must consider every function that could conceivably need a test on the type field after a change. This implies the need to access critical source code and the resulting necessary overhead of testing the affected code. The use of an explicit type conversion is a strong hint that improvement is possible. In other words, use of a type field is an error-prone technique that leads to maintenance prob- lems. The problems increase in severity as the size of the program increases because the use of a type field causes a violation of the ideals of modularity and data hiding. Each function using a type field must know about the representation and other details of the implementation of every class derived from the one containing the type field. It also seems that the existence of any common data accessible from every derived class, such as a type field, tempts people to add more such data. The common base thus becomes the reposi- tory of all kinds of ‘‘useful information.’’ This, in turn, gets the implementation of the base and derived classes intertwined in ways that are most undesirable. For clean design and simpler main- tenance, we want to keep separate issues separate and avoid mutual dependencies. 12.2.6 Virtual Functions [derived.virtual] Virtual functions overcome the problems with the type-field solution by allowing the programmer to declare functions in a base class that can be redefined in each derived class. The compiler and loader will guarantee the correct correspondence between objects and the functions applied to them. For example: c cl la as ss s E Em mp pl lo oy ye ee e { s st tr ri in ng g f fi ir rs st t_ _n na am me e, f fa am mi il ly y_ _n na am me e; s sh ho or rt t d de ep pa ar rt tm me en nt t; / / ... p pu ub bl li ic c: E Em mp pl lo oy ye ee e(c co on ns st t s st tr ri in ng g& n na am me e, i in nt t d de ep pt t) ; v vi ir rt tu ua al l v vo oi id d p pr ri in nt t() c co on ns st t; / / ... }; The keyword v vi ir rt tu ua al l indicates that p pr ri in nt t() can act as an interface to the p pr ri in nt t() function defined in this class and the p pr ri in nt t() functions defined in classes derived from it. Where such p pr ri in nt t() functions are defined in derived classes, the compiler ensures that the right p pr ri in nt t() for the given E Em mp pl lo oy ye ee e object is invoked in each case. To allow a virtual function declaration to act as an interface to functions defined in derived classes, the argument types specified for a function in a derived class cannot differ from the argu- ment types declared in the base, and only very slight changes are allowed for the return type (§15.6.2). A virtual member function is sometimes called a method. A virtual function must be defined for the class in which it is first declared (unless it is declared to be a pure virtual function; see §12.3). For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 12.2.6 Virtual Functions 311 v vo oi id d E Em mp pl lo oy ye ee e: :p pr ri in nt t() c co on ns st t { c co ou ut t << f fa am mi il ly y_ _n na am me e << ´\ \t t´ << d de ep pa ar rt tm me en nt t << ´\ \n n´; / / ... } A virtual function can be used even if no class is derived from its class, and a derived class that does not need its own version of a virtual function need not provide one. When deriving a class, simply provide an appropriate function, if it is needed. For example: c cl la as ss s M Ma an na ag ge er r : p pu ub bl li ic c E Em mp pl lo oy ye ee e { s se et t g gr ro ou up p; s sh ho or rt t l le ev ve el l; / / ... p pu ub bl li ic c: M Ma an na ag ge er r(c co on ns st t s st tr ri in ng g& n na am me e, i in nt t d de ep pt t, i in nt t l lv vl l) ; v vo oi id d p pr ri in nt t() c co on ns st t; / / ... }; v vo oi id d M Ma an na ag ge er r: :p pr ri in nt t() c co on ns st t { E Em mp pl lo oy ye ee e: :p pr ri in nt t() ; c co ou ut t << "\ \t tl le ev ve el l " << l le ev ve el l << ´\ \n n´; / / ... } A function from a derived class with the same name and the same set of argument types as a virtual function in a base is said to override the base class version of the virtual function. Except where we explicitly say which version of a virtual function is called (as in the call E Em mp pl lo oy ye ee e: :p pr ri in nt t()), the overriding function is chosen as the most appropriate for the object for which it is called. The global function p pr ri in nt t_ _e em mp pl lo oy ye ee e() (§12.2.5) is now unnecessary because the p pr ri in nt t() member functions have taken its place. A list of E Em mp pl lo oy ye ee es can be printed like this: v vo oi id d p pr ri in nt t_ _l li is st t(s se et t& s s) { f fo or r (s se et t: :c co on ns st t_ _i it te er ra at to or r p p = s s.b be eg gi in n() ; p p!=s s.e en nd d() ; ++p p)/ / see §2.7.2 (*p p)->p pr ri in nt t() ; } or even v vo oi id d p pr ri in nt t_ _l li is st t(s se et t& s s) { f fo or r_ _e ea ac ch h(s s.b be eg gi in n() ,s s.e en nd d() ,m me em m_ _f fu un n(&E Em mp pl lo oy ye ee e: :p pr ri in nt t)) ; / / see §3.8.5 } Each E Em mp pl lo oy ye ee e will be written out according to its type. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.312 Derived Classes Chapter 12 i in nt t m ma ai in n() { E Em mp pl lo oy ye ee e e e("B Br ro ow wn n",1 12 23 34 4) ; M Ma an na ag ge er r m m("S Sm mi it th h",1 12 23 34 4,2 2) ; s se et t e em mp pl l; e em mp pl l.p pu us sh h_ _f fr ro on nt t(&e e) ; / / see §2.5.4 e em mp pl l.p pu us sh h_ _f fr ro on nt t(&m m) ; p pr ri in nt t_ _l li is st t(e em mp pl l) ; } produced: S Sm mi it th h 1 12 23 34 4 l le ev ve el l 2 2 B Br ro ow wn n 1 12 23 34 4 Note that this will work even if E Em mp pl lo oy ye ee e: :p pr ri in nt t_ _l li is st t() was written and compiled before the spe- cific derived class M Ma an na ag ge er r was even conceived of! This is a key aspect of classes. When used properly, it becomes the cornerstone of object-oriented designs and provides a degree of stability to an evolving program. Getting ‘‘the right’’ behavior from E Em mp pl lo oy ye ee e’s functions independently of exactly what kind of E Em mp pl lo oy ye ee e is actually used is called polymorphism. A type with virtual functions is called a polymorphic type. To get polymorphic behavior in C++, the member functions called must be v vi ir r- - t tu ua al l and objects must be manipulated through pointers or references. When manipulating an object directly (rather than through a pointer or reference), its exact type is known by the compilation so that run-time polymorphism is not needed. Clearly, to implement polymorphism, the compiler must store some kind of type information in each object of class E Em mp pl lo oy ye ee e and use it to call the right version of the virtual function p pr ri in nt t(). In a typical implementation, the space taken is just enough to hold a pointer (§2.5.5). This space is taken only in objects of a class with virtual functions ± not in every object, or even in every object of a derived class. You pay this overhead only for classes for which you declare virtual functions. Had you chosen to use the alternative type-field solution, a comparable amount of space would have been needed for the type field. Calling a function using the scope resolution operator : : as is done in M Ma an na ag ge er r: :p pr ri in nt t() ensures that the virtual mechanism is not used. Otherwise, M Ma an na ag ge er r: :p pr ri in nt t() would suffer an infinite recursion. The use of a qualified name has another desirable effect. That is, if a v vi ir rt tu ua al l function is also i in nl li in ne e (as is not uncommon), then inline substitution can be used for calls specified using : :. This provides the programmer with an efficient way to handle some important special cases in which one virtual function calls another for the same object. The M Ma an na ag ge er r: :p pr ri in nt t() function is an example of this. Because the type of the object is determined in the call of M Ma an na ag ge er r: :p pr ri in nt t(), it need not be dynamically determined again for the resulting call of E Em mp pl lo oy ye ee e: :p pr ri in nt t(). It is worth remembering that the traditional and obvious implementation of a virtual function call is simply an indirect function call (§2.5.5), so efficiency concerns should not deter anyone from using a virtual function where an ordinary function call would be acceptably efficient. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 12.3 Abstract Classes 313 12.3 Abstract Classes [derived.abstract] Many classes resemble class E Em mp pl lo oy ye ee e in that they are useful both as themselves and also as bases for derived classes. For such classes, the techniques described in the previous section suffice. However, not all classes follow that pattern. Some classes, such as class S Sh ha ap pe e, represent abstract concepts for which objects cannot exist. A S Sh ha ap pe e makes sense only as the base of some class derived from it. This can be seen from the fact that it is not possible to provide sensible definitions for its virtual functions: c cl la as ss s S Sh ha ap pe e { p pu ub bl li ic c: v vi ir rt tu ua al l v vo oi id d r ro ot ta at te e(i in nt t) { e er rr ro or r("S Sh ha ap pe e: :r ro ot ta at te e") ; } / / inelegant v vi ir rt tu ua al l v vo oi id d d dr ra aw w() { e er rr ro or r("S Sh ha ap pe e: :d dr ra aw w") ; } / / ... }; Trying to make a shape of this unspecified kind is silly but legal: S Sh ha ap pe e s s; / / silly: ‘‘shapeless shape’’ It is silly because every operation on s s will result in an error. A better alternative is to declare the virtual functions of class S Sh ha ap pe e to be pure virtual functions. A virtual function is ‘‘made pure’’ by the initializer = 0 0: c cl la as ss s S Sh ha ap pe e { / / abstract class p pu ub bl li ic c: v vi ir rt tu ua al l v vo oi id d r ro ot ta at te e(i in nt t) = 0 0; / / pure virtual function v vi ir rt tu ua al l v vo oi id d d dr ra aw w() = 0 0; / / pure virtual function v vi ir rt tu ua al l b bo oo ol l i is s_ _c cl lo os se ed d() = 0 0; / / pure virtual function / / ... }; A class with one or more pure virtual functions is an abstract class, and no objects of that abstract class can be created: S Sh ha ap pe e s s; / / error: variable of abstract class Shape An abstract class can be used only as an interface and as a base for other classes. For example: c cl la as ss s P Po oi in nt t { /* ... */ }; c cl la as ss s C Ci ir rc cl le e : p pu ub bl li ic c S Sh ha ap pe e { p pu ub bl li ic c: v vo oi id d r ro ot ta at te e(i in nt t) { } / / override Shape::rotate v vo oi id d d dr ra aw w() ; / / override Shape::draw b bo oo ol l i is s_ _c cl lo os se ed d() { r re et tu ur rn n t tr ru ue e; } / / override Shape::is_closed C Ci ir rc cl le e(P Po oi in nt t p p, i in nt t r r) ; p pr ri iv va at te e: P Po oi in nt t c ce en nt te er r; i in nt t r ra ad di iu us s; }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.314 Derived Classes Chapter 12 A pure virtual function that is not defined in a derived class remains a pure virtual function, so the derived class is also an abstract class. This allows us to build implementations in stages: c cl la as ss s P Po ol ly yg go on n : p pu ub bl li ic c S Sh ha ap pe e { / / abstract class p pu ub bl li ic c: b bo oo ol l i is s_ _c cl lo os se ed d() { r re et tu ur rn n t tr ru ue e; } / / override Shape::is_closed / / ... draw and rotate not overridden ... }; P Po ol ly yg go on n b b; / / error: declaration of object of abstract class Polygon c cl la as ss s I Ir rr re eg gu ul la ar r_ _p po ol ly yg go on n : p pu ub bl li ic c P Po ol ly yg go on n { l li is st t

l lp p; p pu ub bl li ic c: v vo oi id d d dr ra aw w() ; / / override Shape::draw v vo oi id d r ro ot ta at te e(i in nt t) ; / / override Shape::rotate / / ... }; I Ir rr re eg gu ul la ar r_ _p po ol ly yg go on n p po ol ly y(s so om me e_ _p po oi in nt ts s) ; / / fine (assume suitable constructor) An important use of abstract classes is to provide an interface without exposing any implementation details. For example, an operating system might hide the details of its device drivers behind an abstract class: c cl la as ss s C Ch ha ar ra ac ct te er r_ _d de ev vi ic ce e { p pu ub bl li ic c: v vi ir rt tu ua al l i in nt t o op pe en n(i in nt t o op pt t) = 0 0; v vi ir rt tu ua al l i in nt t c cl lo os se e(i in nt t o op pt t) = 0 0; v vi ir rt tu ua al l i in nt t r re ea ad d(c ch ha ar r* p p, i in nt t n n) = 0 0; v vi ir rt tu ua al l i in nt t w wr ri it te e(c co on ns st t c ch ha ar r* p p, i in nt t n n) = 0 0; v vi ir rt tu ua al l i in nt t i io oc ct tl l(i in nt t ...) = 0 0; v vi ir rt tu ua al l ~C Ch ha ar ra ac ct te er r_ _d de ev vi ic ce e() { } / / virtual destructor }; We can then specify drivers as classes derived from C Ch ha ar ra ac ct te er r_ _d de ev vi ic ce e, and manipulate a variety of drivers through that interface. The importance of virtual destructors is explained in §12.4.2. With the introduction of abstract classes, we have the basic facilities for writing a complete pro- gram in a modular fashion using classes as building blocks. 12.4 Design of Class Hierarchies [derived.design] Consider a simple design problem: provide a way for a program to get an integer value from a user interface. This can be done in a bewildering number of ways. To insulate our program from this variety, and also to get a chance to explore the possible design choices, let us start by defining our program’s model of this simple input operation. We will leave until later the details of implement- ing it using a real user-interface system. The idea is to have a class I Iv va al l_ _b bo ox x that knows what range of input values it will accept. A program can ask an I Iv va al l_ _b bo ox x for its value and ask it to prompt the user if necessary. In addition, a program can ask an I Iv va al l_ _b bo ox x if a user changed the value since the program last looked at it. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 12.4 Design of Class Hierarchies 315 Because there are many ways of implementing this basic idea, we must assume that there will be many different kinds of I Iv va al l_ _b bo ox xe es s, such as sliders, plain boxes in which a user can type a num- ber, dials, and voice interaction. The general approach is to build a ‘‘virtual user-interface system’’ for the application to use. This system provides some of the services provided by existing user-interface systems. It can be implemented on a wide variety of systems to ensure the portability of application code. Naturally, there are other ways of insulating an application from a user-interface system. I chose this approach because it is general, because it allows me to demonstrate a variety of techniques and design tradeoffs, because those techniques are also the ones used to build ‘‘real’’ user-interface sys- tems, and ± most important ± because these techniques are applicable to problems far beyond the narrow domain of interface systems. 12.4.1 A Traditional Class Hierarchy [derived.traditional] Our first solution is a traditional class hierarchy as is commonly found in Simula, Smalltalk, and older C++ programs. Class I Iv va al l_ _b bo ox x defines the basic interface to all I Iv va al l_ _b bo ox xes and specifies a default implementa- tion that more specific kinds of I Iv va al l_ _b bo ox xes can override with their own versions. In addition, we declare the data needed to implement the basic notion: c cl la as ss s I Iv va al l_ _b bo ox x { p pr ro ot te ec ct te ed d: i in nt t v va al l; i in nt t l lo ow w, h hi ig gh h; b bo oo ol l c ch ha an ng ge ed d; p pu ub bl li ic c: I Iv va al l_ _b bo ox x(i in nt t l ll l, i in nt t h hh h) { c ch ha an ng ge ed d = f fa al ls se e; v va al l = l lo ow w = l ll l; h hi ig gh h = h hh h; } v vi ir rt tu ua al l i in nt t g ge et t_ _v va al lu ue e() { c ch ha an ng ge ed d = f fa al ls se e; r re et tu ur rn n v va al l; } v vi ir rt tu ua al l v vo oi id d s se et t_ _v va al lu ue e(i in nt t i i) { c ch ha an ng ge ed d = t tr ru ue e; v va al l = i i; } / / for user v vi ir rt tu ua al l v vo oi id d r re es se et t_ _v va al lu ue e(i in nt t i i) { c ch ha an ng ge ed d = f fa al ls se e; v va al l = i i; } / / for application v vi ir rt tu ua al l v vo oi id d p pr ro om mp pt t() { } v vi ir rt tu ua al l b bo oo ol l w wa as s_ _c ch ha an ng ge ed d() c co on ns st t { r re et tu ur rn n c ch ha an ng ge ed d; } }; The default implementation of the functions is pretty sloppy and is provided here primarily to illus- trate the intended semantics. A realistic class would, for example, provide some range checking. A programmer might use these ‘‘i iv va al l classes’’ like this: v vo oi id d i in nt te er ra ac ct t(I Iv va al l_ _b bo ox x* p pb b) { p pb b->p pr ro om mp pt t() ; / / alert user / / ... i in nt t i i = p pb b->g ge et t_ _v va al lu ue e() ; i if f (p pb b->w wa as s_ _c ch ha an ng ge ed d()) { / / new value; do something } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.316 Derived Classes Chapter 12 e el ls se e { / / old value was fine; do something else } / / ... } v vo oi id d s so om me e_ _f fc ct t() { I Iv va al l_ _b bo ox x* p p1 1 = n ne ew w I Iv va al l_ _s sl li id de er r(0 0,5 5) ; / / Ival_slider derived from Ival_box i in nt te er ra ac ct t(p p1 1) ; I Iv va al l_ _b bo ox x* p p2 2 = n ne ew w I Iv va al l_ _d di ia al l(1 1,1 12 2) ; i in nt te er ra ac ct t(p p2 2) ; } Most application code is written in terms of (pointers to) plain I Iv va al l_ _b bo ox xes the way i in nt te er ra ac ct t() is. That way, the application doesn’t have to know about the potentially large number of variants of the I Iv va al l_ _b bo ox x concept. The knowledge of such specialized classes is isolated in the relatively few functions that create such objects. This isolates users from changes in the implementations of the derived classes. Most code can be oblivious to the fact that there are different kinds of I Iv va al l_ _b bo ox xes. To simplify the discussion, I do not address issues of how a program waits for input. Maybe the program really does wait for the user in g ge et t_ _v va al lu ue e(), maybe the program associates the I Iv va al l_ _b bo ox x with an event and prepares to respond to a callback, or maybe the program spawns a thread for the I Iv va al l_ _b bo ox x and later inquires about the state of that thread. Such decisions are crucial in the design of user-interface systems. However, discussing them here in any realistic detail would simply dis- tract from the presentation of programming techniques and language facilities. The design tech- niques described here and the language facilities that support them are not specific to user inter- faces. They apply to a far greater range of problems. The different kinds of I Iv va al l_ _b bo ox xes are defined as classes derived from I Iv va al l_ _b bo ox x. For example: c cl la as ss s I Iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _b bo ox x { / / graphics stuff to define what the slider looks like, etc. p pu ub bl li ic c: I Iv va al l_ _s sl li id de er r(i in nt t, i in nt t) ; i in nt t g ge et t_ _v va al lu ue e() ; v vo oi id d p pr ro om mp pt t() ; }; The data members of I Iv va al l_ _b bo ox x were declared p pr ro ot te ec ct te ed d to allow access from derived classes. Thus, I Iv va al l_ _s sl li id de er r: :g ge et t_ _v va al lu ue e() can deposit a value in I Iv va al l_ _b bo ox x: :v va al l. A p pr ro ot te ec ct te ed d member is accessible from a class’ own members and from members of derived classes, but not to general users (see §15.3). In addition to I Iv va al l_ _s sl li id de er r, we would define other variants of the I Iv va al l_ _b bo ox x concept. These could include I Iv va al l_ _d di ia al l, which lets you select a value by turning a knob; f fl la as sh hi in ng g_ _i iv va al l_ _s sl li id de er r, which flashes when you ask it to p pr ro om mp pt t(); and p po op pu up p_ _i iv va al l_ _s sl li id de er r, which responds to p pr ro om mp pt t() by appearing in some prominent place, thus making it hard for the user to ignore. From where would we get the graphics stuff? Most user-interface systems provide a class defining the basic properties of being an entity on the screen. So, if we use the system from ‘‘Big The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 12.4.1 A Traditional Class Hierarchy 317 Bucks Inc.,’’ we would have to make each of our I Iv va al l_ _s sl li id de er r, I Iv va al l_ _d di ia al l, etc., classes a kind of B BB Bw wi in nd do ow w. This would most simply be achieved by rewriting our I Iv va al l_ _b bo ox x so that it derives from B BB Bw wi in nd do ow w. In that way, all our classes inherit all the properties of a B BB Bw wi in nd do ow w. For example, every I Iv va al l_ _b bo ox x can be placed on the screen, obey the graphical style rules, be resized, be dragged around, etc., according to the standard set by the B BB Bw wi in nd do ow w system. Our class hierarchy would look like this: c cl la as ss s I Iv va al l_ _b bo ox x : p pu ub bl li ic c B BB Bw wi in nd do ow w { /* ... */ }; / / rewritten to use BBwindow c cl la as ss s I Iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _b bo ox x { /* ... */ }; c cl la as ss s I Iv va al l_ _d di ia al l : p pu ub bl li ic c I Iv va al l_ _b bo ox x { /* ... */ }; c cl la as ss s F Fl la as sh hi in ng g_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _s sl li id de er r { /* ... */ }; c cl la as ss s P Po op pu up p_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _s sl li id de er r { /* ... */ }; or graphically: B BB Bw wi in nd do ow w I Iv va al l_ _b bo ox x I Iv va al l_ _s sl li id de er r I Iv va al l_ _d di ia al l F Fl la as sh hi in ng g_ _i iv va al l_ _s sl li id de er r P Po op pu up p_ _i iv va al l_ _s sl li id de er r .. 12.4.1.1 Critique [derived.critique] This design works well in many ways, and for many problems this kind of hierarchy is a good solu- tion. However, there are some awkward details that could lead us to look for alternative designs. We retrofitted B BB Bw wi in nd do ow w as the base of I Iv va al l_ _b bo ox x. This is not quite right. The use of B BB Bw wi in n- - d do ow w isn’t part of our basic notion of an I Iv va al l_ _b bo ox x; it is an implementation detail. Deriving I Iv va al l_ _b bo ox x from B BB Bw wi in nd do ow w elevated an implementation detail to a first-level design decision. That can be right. For example, using the environment defined by ‘‘Big Bucks Inc.’’ may be a key decision of how our organization conducts its business. However, what if we also wanted to have implementa- tions of our I Iv va al l_ _b bo ox xes for systems from ‘‘Imperial Bananas,’’ ‘‘Liberated Software,’’ and ‘‘Com- piler Whizzes?’’ We would have to maintain four distinct versions of our program: c cl la as ss s I Iv va al l_ _b bo ox x : p pu ub bl li ic c B BB Bw wi in nd do ow w { /* ... */ }; / / BB version c cl la as ss s I Iv va al l_ _b bo ox x : p pu ub bl li ic c C CW Ww wi in nd do ow w { /* ... */ }; / / CW version c cl la as ss s I Iv va al l_ _b bo ox x : p pu ub bl li ic c I IB Bw wi in nd do ow w { /* ... */ }; / / IB version c cl la as ss s I Iv va al l_ _b bo ox x : p pu ub bl li ic c L LS Sw wi in nd do ow w { /* ... */ }; / / LS version Having many versions could result in a version-control nightmare. Another problem is that every derived class shares the basic data declared in I Iv va al l_ _b bo ox x. That data is, of course, an implementation detail that also crept into our I Iv va al l_ _b bo ox x interface. From a practical point of view, it is also the wrong data in many cases. For example, an I Iv va al l_ _s sl li id de er r doesn’t need the value stored specifically. It can easily be calculated from the position of the slider when someone executes g ge et t_ _v va al lu ue e(). In general, keeping two related, but different, sets of data is The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.318 Derived Classes Chapter 12 asking for trouble. Sooner or later someone will get them out of sync. Also, experience shows that novice programmers tend to mess with protected data in ways that are unnecessary and that cause maintenance problems. Data is better kept private so that writers of derived classes cannot mess with them. Better still, data should be in the derived classes, where it can be defined to match requirements exactly and cannot complicate the life of unrelated derived classes. In almost all cases, a protected interface should contain only functions, types, and constants. Deriving from B BB Bw wi in nd do ow w gives the benefit of making the facilities provided by B BB Bw wi in nd do ow w available to users of I Iv va al l_ _b bo ox x. Unfortunately, it also means that changes to class B BB Bw wi in nd do ow w may force users to recompile or even rewrite their code to recover from such changes. In particular, the way most C++ implementations work implies that a change in the size of a base class requires a recompilation of all derived classes. Finally, our program may have to run in a mixed environment in which windows of different user-interface systems coexist. This could happen either because two systems somehow share a screen or because our program needs to communicate with users on different systems. Having our user-interface systems ‘‘wired in’’ as the one and only base of our one and only I Iv va al l_ _b bo ox x interface just isn’t flexible enough to handle those situations. 12.4.2 Abstract Classes [derived.interface] So, let’s start again and build a new class hierarchy that solves the problems presented in the cri- tique of the traditional hierarchy: [1] The user-interface system should be an implementation detail that is hidden from users who don’t want to know about it. [2] The I Iv va al l_ _b bo ox x class should contain no data. [3] No recompilation of code using the I Iv va al l_ _b bo ox x family of classes should be required after a change of the user-interface system. [4] I Iv va al l_ _b bo ox xes for different interface systems should be able to coexist in our program. Several alternative approaches can be taken to achieve this. Here, I present one that maps cleanly into the C++ language. First, I specify class I Iv va al l_ _b bo ox x as a pure interface: c cl la as ss s I Iv va al l_ _b bo ox x { p pu ub bl li ic c: v vi ir rt tu ua al l i in nt t g ge et t_ _v va al lu ue e() = 0 0; v vi ir rt tu ua al l v vo oi id d s se et t_ _v va al lu ue e(i in nt t i i) = 0 0; v vi ir rt tu ua al l v vo oi id d r re es se et t_ _v va al lu ue e(i in nt t i i) = 0 0; v vi ir rt tu ua al l v vo oi id d p pr ro om mp pt t() = 0 0; v vi ir rt tu ua al l b bo oo ol l w wa as s_ _c ch ha an ng ge ed d() c co on ns st t = 0 0; v vi ir rt tu ua al l ~I Iv va al l_ _b bo ox x() { } }; This is much cleaner than the original declaration of I Iv va al l_ _b bo ox x. The data is gone and so are the sim- plistic implementations of the member functions. Gone, too, is the constructor, since there is no data for it to initialize. Instead, I added a virtual destructor to ensure proper cleanup of the data that will be defined in the derived classes. The definition of I Iv va al l_ _s sl li id de er r might look like this: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 12.4.2 Abstract Classes 319 c cl la as ss s I Iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _b bo ox x, p pr ro ot te ec ct te ed d B BB Bw wi in nd do ow w { p pu ub bl li ic c: I Iv va al l_ _s sl li id de er r(i in nt t,i in nt t) ; ~I Iv va al l_ _s sl li id de er r() ; i in nt t g ge et t_ _v va al lu ue e() ; v vo oi id d s se et t_ _v va al lu ue e(i in nt t i i) ; / / ... p pr ro ot te ec ct te ed d: / / functions overriding BBwindow virtual functions / / e.g. BBwindow::draw(), BBwindow::mouse1hit() p pr ri iv va at te e: / / data needed for slider }; The derived class I Iv va al l_ _s sl li id de er r inherits from an abstract class (I Iv va al l_ _b bo ox x) that requires it to imple- ment the base class’ pure virtual functions. It also inherits from B BB Bw wi in nd do ow w that provides it with the means of doing so. Since I Iv va al l_ _b bo ox x provides the interface for the derived class, it is derived using p pu ub bl li ic c. Since B BB Bw wi in nd do ow w is only an implementation aid, it is derived using p pr ro ot te ec ct te ed d (§15.3.2). This implies that a programmer using I Iv va al l_ _s sl li id de er r cannot directly use facilities defined by B BB Bw wi in nd do ow w. The interface provided by I Iv va al l_ _s sl li id de er r is the one inherited by I Iv va al l_ _b bo ox x, plus what I Iv va al l_ _s sl li id de er r explicitly declares. I used p pr ro ot te ec ct te ed d derivation instead of the more restrictive (and usu- ally safer) p pr ri iv va at te e derivation to make B BB Bw wi in nd do ow w available to classes derived from I Iv va al l_ _s sl li id de er r. Deriving directly from more than one class is usually called multiple inheritance (§15.2). Note that I Iv va al l_ _s sl li id de er r must override functions from both I Iv va al l_ _b bo ox x and B BB Bw wi in nd do ow w. Therefore, it must be derived directly or indirectly from both. As shown in §12.4.1.1, deriving I Iv va al l_ _s sl li id de er r indirectly from B BB Bw wi in nd do ow w by making B BB Bw wi in nd do ow w a base of I Iv va al l_ _b bo ox x is possible, but doing so has undesirable side effects. Similarly, making the ‘‘implementation class’’ B BB Bw wi in nd do ow w a member of I Iv va al l_ _b bo ox x is not a solution because a class cannot override virtual functions of its members (§24.3.4). Repre- senting the window by a B BB Bw wi in nd do ow w* member in I Iv va al l_ _b bo ox x leads to a completely different design with a separate set of tradeoffs (§12.7[14], §25.7). Interestingly, this declaration of I Iv va al l_ _s sl li id de er r allows application code to be written exactly as before. All we have done is to restructure the implementation details in a more logical way. Many classes require some form of cleanup for an object before it goes away. Since the abstract class I Iv va al l_ _b bo ox x cannot know if a derived class requires such cleanup, it must assume that it does require some. We ensure proper cleanup by defining a virtual destructor I Iv va al l_ _b bo ox x: :~I Iv va al l_ _b bo ox x() in the base and overriding it suitably in derived classes. For example: v vo oi id d f f(I Iv va al l_ _b bo ox x* p p) { / / ... d de el le et te e p p; } The d de el le et te e operator explicitly destroys the object pointed to by p p. We have no way of knowing exactly to which class the object pointed to by p p belongs, but thanks to I Iv va al l_ _b bo ox x’s virtual destructor, proper cleanup as (optionally) defined by that class’ destructor will be called. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.320 Derived Classes Chapter 12 The I Iv va al l_ _b bo ox x hierarchy can now be defined like this: c cl la as ss s I Iv va al l_ _b bo ox x { /* ... */ }; c cl la as ss s I Iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _b bo ox x, p pr ro ot te ec ct te ed d B BB Bw wi in nd do ow w { /* ... */ }; c cl la as ss s I Iv va al l_ _d di ia al l : p pu ub bl li ic c I Iv va al l_ _b bo ox x, p pr ro ot te ec ct te ed d B BB Bw wi in nd do ow w { /* ... */ }; c cl la as ss s F Fl la as sh hi in ng g_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _s sl li id de er r { /* ... */ }; c cl la as ss s P Po op pu up p_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _s sl li id de er r { /* ... */ }; or graphically using obvious abbreviations: B BB Bw wi in nd do ow w B BB Bw wi in nd do ow w I Iv va al l_ _b bo ox x I Iv va al l_ _s sl li id de er r I Iv va al l_ _d di ia al l F Fl la as sh hi in ng g_ _s sl li id de er r P Po op pu up p_ _s sl li id de er r .. I used a dashed line to represent protected inheritance. As far as general users are concerned, doing that is simply an implementation detail. 12.4.3 Alternative Implementations [derived.alt] This design is cleaner and more easily maintainable than the traditional one ± and no less efficient. However, it still fails to solve the version control problem: c cl la as ss s I Iv va al l_ _b bo ox x { /* ... */ }; / / common c cl la as ss s I Iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _b bo ox x, p pr ro ot te ec ct te ed d B BB Bw wi in nd do ow w { /* ... */ }; / / for BB c cl la as ss s I Iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _b bo ox x, p pr ro ot te ec ct te ed d C CW Ww wi in nd do ow w { /* ... */ }; / / for CW / / ... In addition, there is no way of having an I Iv va al l_ _s sl li id de er r for B BB Bw wi in nd do ow ws coexist with an I Iv va al l_ _s sl li id de er r for C CW Ww wi in nd do ow ws, even if the two user-interface systems could themselves coexist. The obvious solution is to define several different I Iv va al l_ _s sl li id de er r classes with separate names: c cl la as ss s I Iv va al l_ _b bo ox x { /* ... */ }; c cl la as ss s B BB B_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _b bo ox x, p pr ro ot te ec ct te ed d B BB Bw wi in nd do ow w { /* ... */ }; c cl la as ss s C CW W_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _b bo ox x, p pr ro ot te ec ct te ed d C CW Ww wi in nd do ow w { /* ... */ }; / / ... or graphically: I Iv va al l_ _b bo ox x B BB Bw wi in nd do ow w C CW Ww wi in nd do ow w B BB B_ _i iv va al l_ _s sl li id de er r C CW W_ _i iv va al l_ _s sl li id de er r.. To further insulate our application-oriented I Iv va al l_ _b bo ox x classes from implementation details, we can derive an abstract I Iv va al l_ _s sl li id de er r class from I Iv va al l_ _b bo ox x and then derive the system-specific I Iv va al l_ _s sl li id de er rs s from that: c cl la as ss s I Iv va al l_ _b bo ox x { /* ... */ }; c cl la as ss s I Iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _b bo ox x { /* ... */ }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 12.4.3 Alternative Implementations 321 c cl la as ss s B BB B_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _s sl li id de er r, p pr ro ot te ec ct te ed d B BB Bw wi in nd do ow w { /* ... */ }; c cl la as ss s C CW W_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _s sl li id de er r, p pr ro ot te ec ct te ed d C CW Ww wi in nd do ow w { /* ... */ }; / / ... or graphically: I Iv va al l_ _b bo ox x B BB Bw wi in nd do ow w C CW Ww wi in nd do ow w I Iv va al l_ _s sl li id de er r B BB B_ _i iv va al l_ _s sl li id de er r C CW W_ _i iv va al l_ _s sl li id de er r .. Usually, we can do better yet by utilizing more-specific classes in the implementation hierarchy. For example, if the ‘‘Big Bucks Inc.’’ system has a slider class, we can derive our I Iv va al l_ _s sl li id de er r directly from the B BB Bs sl li id de er r: c cl la as ss s B BB B_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _s sl li id de er r, p pr ro ot te ec ct te ed d B BB Bs sl li id de er r { /* ... */ }; c cl la as ss s C CW W_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _s sl li id de er r, p pr ro ot te ec ct te ed d C CW Ws sl li id de er r { /* ... */ }; or graphically: I Iv va al l_ _b bo ox x B BB Bs sl li id de er r C CW Ws sl li id de er r I Iv va al l_ _s sl li id de er r B BB B_ _i iv va al l_ _s sl li id de er r C CW W_ _i iv va al l_ _s sl li id de er r ..B BB Bw wi in nd do ow w C CW Ww wi in nd do ow w.. This improvement becomes significant where ± as is not uncommon ± our abstractions are not too different from the ones provided by the system used for implementation. In that case, program- ming is reduced to mapping between similar concepts. Derivation from general base classes, such as B BB Bw wi in nd do ow w, is then done only rarely. The complete hierarchy will consist of our original application-oriented conceptual hierarchy of interfaces expressed as derived classes: c cl la as ss s I Iv va al l_ _b bo ox x { /* ... */ }; c cl la as ss s I Iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _b bo ox x { /* ... */ }; c cl la as ss s I Iv va al l_ _d di ia al l : p pu ub bl li ic c I Iv va al l_ _b bo ox x { /* ... */ }; c cl la as ss s F Fl la as sh hi in ng g_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _s sl li id de er r { /* ... */ }; c cl la as ss s P Po op pu up p_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _s sl li id de er r { /* ... */ }; followed by the implementations of this hierarchy for various graphical user-interface systems, expressed as derived classes: c cl la as ss s B BB B_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _s sl li id de er r, p pr ro ot te ec ct te ed d B BB Bs sl li id de er r { /* ... */ }; c cl la as ss s B BB B_ _f fl la as sh hi in ng g_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c F Fl la as sh hi in ng g_ _i iv va al l_ _s sl li id de er r, p pr ro ot te ec ct te ed d B BB Bw wi in nd do ow w_ _w wi it th h_ _b be el ll ls s_ _a an nd d_ _w wh hi is st tl le es s { /* ... */ }; c cl la as ss s B BB B_ _p po op pu up p_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c P Po op pu up p_ _i iv va al l_ _s sl li id de er r, p pr ro ot te ec ct te ed d B BB Bs sl li id de er r { /* ... */ }; c cl la as ss s C CW W_ _i iv va al l_ _s sl li id de er r : p pu ub bl li ic c I Iv va al l_ _s sl li id de er r, p pr ro ot te ec ct te ed d C CW Ws sl li id de er r { /* ... */ }; / / ... The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.322 Derived Classes Chapter 12 Using obvious abbreviations, this hierarchy can be represented graphically like this: I Iv va al l_ _b bo ox x I Iv va al l_ _s sl li id de er r I Iv va al l_ _d di ia al l i if fl la as sh h i ip po op pu up p C CW Ws sl l C CW Ws sl l C CW Ws sl l C CW Wi is sl li id de er r B BB Bi is sl li id de er r C CW Wi ip po op p C CW Wi if fl l B BB Bi ip po op p B BB Bi if fl l B BB Bs sl li id de er r B BB Bs sl li id de er r B BB Bb b& &w w .. The original I Iv va al l_ _b bo ox x class hierarchy appears unchanged surrounded by implementation classes. 12.4.3.1 Critique [derived.critique2] The abstract class design is flexible and almost as simple to deal with as the equivalent design that relies on a common base defining the user-interface system. In the latter design, the windows class is the root of a tree. In the former, the original application class hierarchy appears unchanged as the root of classes that supply its implementations. From the application’s point of view, these designs are equivalent in the strong sense that almost all code works unchanged and in the same way in the two cases. In either case, you can look at the I Iv va al l_ _b bo ox x family of classes without bothering with the window-related implementation details most of the time. For example, we would not need to rewrite i in nt te er ra ac ct t() from §12.4.1 if we switched from the one class hierarchy to the other. In either case, the implementation of each I Iv va al l_ _b bo ox x class must be rewritten when the public interface of the user-interface system changes. However, in the abstract class design, almost all user code is protected against changes to the implementation hierarchy and requires no recompila- tion after such a change. This is especially important when the supplier of the implementation hier- archy issues a new ‘‘almost compatible’’ release. In addition, users of the abstract class hierarchy are in less danger of being locked into a proprietary implementation than are users of a classical hierarchy. Users of the I Iv va al l_ _b bo ox x abstract class application hierarchy cannot accidentally use facili- ties from the implementation because only facilities explicitly specified in the I Iv va al l_ _b bo ox x hierarchy are accessible; nothing is implicitly inherited from an implementation-specific base class. 12.4.4 Localizing Object Creation [derived.local] Most of an application can be written using the I Iv va al l_ _b bo ox x interface. Further, should the derived interfaces evolve to provide more facilities than plain I Iv va al l_ _b bo ox x, then most of an application can be written using the I Iv va al l_ _b bo ox x, I Iv va al l_ _s sl li id de er r, etc., interfaces. However, the creation of objects must be The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 12.4.4 Localizing Object Creation 323 done using implementation-specific names such as C CW W_ _i iv va al l_ _d di ia al l and B BB B_ _f fl la as sh hi in ng g_ _i iv va al l_ _s sl li id de er r. We would like to minimize the number of places where such specific names occur, and object cre- ation is hard to localize unless it is done systematically. As usual, the solution is to introduce an indirection. This can be done in many ways. A simple one is to introduce an abstract class to represent the set of creation operations: c cl la as ss s I Iv va al l_ _m ma ak ke er r { p pu ub bl li ic c: v vi ir rt tu ua al l I Iv va al l_ _d di ia al l* d di ia al l(i in nt t, i in nt t) =0 0; / / make dial v vi ir rt tu ua al l P Po op pu up p_ _i iv va al l_ _s sl li id de er r* p po op pu up p_ _s sl li id de er r(i in nt t, i in nt t) =0 0; / / make popup slider / / ... }; For each interface from the I Iv va al l_ _b bo ox x family of classes that a user should know about, class I Iv va al l_ _m ma ak ke er r provides a function that makes an object. Such a class is sometimes called a factory, and its functions are (somewhat misleadingly) sometimes called virtual constructors (§15.6.2). We now represent each user-interface system by a class derived from I Iv va al l_ _m ma ak ke er r: c cl la as ss s B BB B_ _m ma ak ke er r : p pu ub bl li ic c I Iv va al l_ _m ma ak ke er r { / / make BB versions p pu ub bl li ic c: I Iv va al l_ _d di ia al l* d di ia al l(i in nt t, i in nt t) ; P Po op pu up p_ _i iv va al l_ _s sl li id de er r* p po op pu up p_ _s sl li id de er r(i in nt t, i in nt t) ; / / ... }; c cl la as ss s L LS S_ _m ma ak ke er r : p pu ub bl li ic c I Iv va al l_ _m ma ak ke er r { / / make LS versions p pu ub bl li ic c: I Iv va al l_ _d di ia al l* d di ia al l(i in nt t, i in nt t) ; P Po op pu up p_ _i iv va al l_ _s sl li id de er r* p po op pu up p_ _s sl li id de er r(i in nt t, i in nt t) ; / / ... }; Each function creates an object of the desired interface and implementation type. For example: I Iv va al l_ _d di ia al l* B BB B_ _m ma ak ke er r: :d di ia al l(i in nt t a a, i in nt t b b) { r re et tu ur rn n n ne ew w B BB B_ _i iv va al l_ _d di ia al l(a a,b b) ; } I Iv va al l_ _d di ia al l* L LS S_ _m ma ak ke er r: :d di ia al l(i in nt t a a, i in nt t b b) { r re et tu ur rn n n ne ew w L LS S_ _i iv va al l_ _d di ia al l(a a,b b) ; } Given a pointer to a I Iv va al l_ _m ma ak ke er r, a user can now create objects without having to know exactly which user-interface system is used. For example: v vo oi id d u us se er r(I Iv va al l_ _m ma ak ke er r* p pi im m) { I Iv va al l_ _b bo ox x* p pb b = p pi im m->d di ia al l(0 0,9 99 9) ; / / create appropriate dial / / ... } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.324 Derived Classes Chapter 12 B BB B_ _m ma ak ke er r B BB B_ _i im mp pl l; / / for BB users L LS S_ _m ma ak ke er r L LS S_ _i im mp pl l; / / for LS users v vo oi id d d dr ri iv ve er r() { u us se er r(&B BB B_ _i im mp pl l) ; / / use BB u us se er r(&L LS S_ _i im mp pl l) ; / / use LS } 12.5 Class Hierarchies and Abstract Classes [derived.hier] An abstract class is an interface. A class hierarchy is a means of building classes incrementally. Naturally, every class provides an interface to users and some abstract classes provide significant functionality to build from, but ‘‘interface’’ and ‘‘building block’’ are the primary roles of abstract classes and class hierarchies. A classical hierarchy is a hierarchy in which the individual classes both provide useful function- ality for users and act as building blocks for the implementation of more advanced or specialized classes. Such hierarchies are ideal for supporting programming by incremental refinement. They provide the maximum support for the implementation of new classes as long as the new class relates strongly to the existing hierarchy. Classical hierarchies do tend to couple implementation concerns rather strongly with the inter- faces provided to users. Abstract classes can help here. Hierarchies of abstract classes provide a clean and powerful way of expressing concepts without encumbering them with implementation concerns or significant run-time overheads. After all, a virtual function call is cheap and indepen- dent of the kind of abstraction barrier it crosses. It costs no more to call a member of an abstract class than to call any other v vi ir rt tu ua al l function. The logical conclusion of this line of thought is a system represented to users as a hierarchy of abstract classes and implemented by a classical hierarchy. 12.6 Advice [derived.advice] [1] Avoid type fields; §12.2.5. [2] Use pointers and references to avoid slicing; §12.2.3. [3] Use abstract classes to focus design on the provision of clean interfaces; §12.3. [4] Use abstract classes to minimize interfaces; §12.4.2. [5] Use abstract classes to keep implementation details out of interfaces; §12.4.2. [6] Use virtual functions to allow new implementations to be added without affecting user code; §12.4.1. [7] Use abstract classes to minimize recompilation of user code; §12.4.2. [8] Use abstract classes to allow alternative implementations to coexist; §12.4.3. [9] A class with a virtual function should have a virtual destructor; §12.4.2. [10] An abstract class typically doesn’t need a constructor; §12.4.2. [11] Keep the representations of distinct concepts distinct; §12.4.1.1. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 12.7 Exercises 325 12.7 Exercises [derived.exercises] 1. (∗1) Define c cl la as ss s b ba as se e { p pu ub bl li ic c: v vi ir rt tu ua al l v vo oi id d i ia am m() { c co ou ut t << "b ba as se e\ \n n"; } }; Derive two classes from b ba as se e, and for each define i ia am m() to write out the name of the class. Create objects of these classes and call i ia am m() for them. Assign pointers to objects of the derived classes to b ba as se e* pointers and call i ia am m() through those pointers. 2. (∗3.5) Implement a simple graphics system using whatever graphics facilities are available on your system (if you don’t have a good graphics system or have no experience with one, you might consider a simple ‘‘huge bit ASCII implementation’’ where a point is a character position and you write by placing a suitable character, such as * in a position): W Wi in nd do ow w(n n,m m) creates an area of size n n times m m on the screen. Points on the screen are addressed using (x,y) coordi- nates (Cartesian). A W Wi in nd do ow w w w has a current position w w.c cu ur rr re en nt t(). Initially, c cu ur rr re en nt t is P Po oi in nt t(0 0,0 0). The current position can be set by w w.c cu ur rr re en nt t(p p) where p p is a P Po oi in nt t. A P Po oi in nt t is specified by a coordinate pair: P Po oi in nt t(x x,y y). A L Li in ne e is specified by a pair of P Po oi in nt ts: L Li in ne e(w w.c cu ur rr re en nt t() ,p p2 2) ; class S Sh ha ap pe e is the common interface to D Do ot ts, L Li in ne es, R Re ec ct ta an ng gl le es, C Ci ir rc cl le es, etc. A P Po oi in nt t is not a S Sh ha ap pe e. A D Do ot t, D Do ot t(p p) can be used to represent a P Po oi in nt t p p on the screen. A S Sh ha ap pe e is invisible unless d dr ra aw w()n. For example: w w.d dr ra aw w(C Ci ir rc cl le e(w w.c cu ur rr re en nt t() ,1 10 0)). Every S Sh ha ap pe e has 9 contact points: e e (east), w w (west), n n (north), s s (south), n ne e, n nw w, s se e, s sw w, and c c (center). For example, L Li in ne e(x x.c c() ,y y.n nw w()) creates a line from x x’s center to y y’s top left corner. After d dr ra aw w()ing a S Sh ha ap pe e the current position is the S Sh ha ap pe e’s s se e(). A R Re ec ct ta an ng gl le e is specified by its bottom left and top right corner: R Re ec ct ta an ng gl le e(w w.c cu ur rr re en nt t() ,P Po oi in nt t(1 10 0,1 10 0)). As a simple test, display a simple ‘‘child’s draw- ing of a house’’ with a roof, two windows, and a door. 3. (∗2) Important aspects of a S Sh ha ap pe e appear on the screen as a set of line segments. Implement operations to vary the appearance of these segments: s s.t th hi ic ck kn ne es ss s(n n) sets the line thickness to 0 0, 1 1, 2 2, or 3 3, where 2 2 is the default and 0 0 means invisible. In addition, a line segment can be s so ol li id d, d da as sh he ed d, or d do ot tt te ed d. This is set by the function S Sh ha ap pe e: :o ou ut tl li in ne e(). 4. (∗2.5) Provide a function L Li in ne e: :a ar rr ro ow wh he ea ad d() that adds arrow heads to an end of a line. A line has two ends and an arrowhead can point in two directions relative to the line, so the argu- ment or arguments to a ar rr ro ow wh he ea ad d() must be able to express at least four alternatives. 5. (∗3.5) Make sure that points and line segments that fall outside the W Wi in nd do ow w do not appear on the screen. This is often called ‘‘clipping.’’ As an exercise only, do not rely on the implemen- tation graphics system for this. 6. (∗2.5) Add a T Te ex xt t type to the graphics system. A T Te ex xt t is a rectangular S Sh ha ap pe e displaying charac- ters. By default, a character takes up one coordinate unit along each coordinate axis. 7. (∗2) Define a function that draws a line connecting two shapes by finding the two closest ‘‘con- tact points’’ and connecting them. 8. (∗3) Add a notion of color to the simple graphics system. Three things can be colored: the background, the inside of a closed shape, and the outlines of shapes. 9. (∗2) Consider: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.326 Derived Classes Chapter 12 c cl la as ss s C Ch ha ar r_ _v ve ec c { i in nt t s sz z; c ch ha ar r e el le em me en nt t[1 1] ; p pu ub bl li ic c: s st ta at ti ic c C Ch ha ar r_ _v ve ec c* n ne ew w_ _c ch ha ar r_ _v ve ec c(i in nt t s s) ; c ch ha ar r& o op pe er ra at to or r[](i in nt t i i) { r re et tu ur rn n e el le em me en nt t[i i] ; } / / ... }; Define n ne ew w_ _c ch ha ar r_ _v ve ec c() to allocate contiguous memory for a C Ch ha ar r_ _v ve ec c object so that the ele- ments can be indexed through e el le em me en nt t as shown. Under what circumstances does this trick cause serious problems? 10. (∗2.5) Given classes C Ci ir rc cl le e, S Sq qu ua ar re e, and T Tr ri ia an ng gl le e derived from a class S Sh ha ap pe e, define a func- tion i in nt te er rs se ec ct t() that takes two S Sh ha ap pe e* arguments and calls suitable functions to determine if the two shapes overlap. It will be necessary to add suitable (virtual) functions to the classes to achieve this. Don’t bother to write the code that checks for overlap; just make sure the right functions are called. This is commonly referred to as double d di is sp pa at tc ch h or a multi-method. 11. (∗5) Design and implement a library for writing event-driven simulations. Hint: . However, that is an old program, and you can do better. There should be a class t ta as sk k. An object of class t ta as sk k should be able to save its state and to have that state restored (you might define t ta as sk k: :s sa av ve e() and t ta as sk k: :r re es st to or re e()) so that it can operate as a coroutine. Specific tasks can be defined as objects of classes derived from class t ta as sk k. The program to be executed by a task might be specified as a virtual function. It should be possible to pass arguments to a new task as arguments to its constructor(s). There should be a scheduler implementing a concept of virtual time. Provide a function t ta as sk k: :d de el la ay y(l lo on ng g) that ‘‘consumes’’ virtual time. Whether the scheduler is part of class t ta as sk k or separate will be one of the major design decisions. The tasks will need to communicate. Design a class q qu ue eu ue e for that. Devise a way for a task to wait for input from several queues. Handle run-time errors in a uniform way. How would you debug programs written using such a library? 12. (∗2) Define interfaces for W Wa ar rr ri io or r, M Mo on ns st te er r, and O Ob bj je ec ct t (that is a thing you can pick up, drop, use, etc.) classes for an adventure-style game. 13. (∗1.5) Why is there both a P Po oi in nt t and a D Do ot t class in §12.7[2]? Under which circumstances would it be a good idea to augment the S Sh ha ap pe e classes with concrete versions of key classes such as L Li in ne e. 14. (∗3) Outline a different implementation strategy for the I Iv va al l_ _b bo ox x example (§12.4) based on the idea that every class seen by an application is an interface containing a single pointer to the implementation. Thus, each "interface class" will be a handle to an "implementation class," and there will be an interface hierarchy and an implementation hierarchy. Write code fragments that are detailed enough to illustrate possible problems with type conversion. Consider ease of use, ease of programming, ease of reusing implementations and interfaces when adding a new con- cept to the hierarchy, ease of making changes to interfaces and implementations, and need for recompilation after change in the implementation. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 13 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Templates Your quote here. ± B. Stroustrup Templates Ð a string template Ð instantiation Ð template parameters Ð type checking Ð function templates Ð template argument deduction Ð specifying template arguments Ð function template overloading Ð policy as template arguments Ð default template arguments Ð specialization Ð derivation and templates Ð member templates Ð con- versions Ð source code organization Ð advice Ð exercises. 13.1 Introduction [temp.intro] Independent concepts should be independently represented and should be combined only when needed. Where this principle is violated, you either bundle unrelated concepts together or create unnecessary dependencies. Either way, you get a less flexible set of components out of which to compose systems. Templates provide a simple way to represent a wide range of general concepts and simple ways to combine them. The resulting classes and functions can match hand-written, more-specialized code in run-time and space efficiency. Templates provide direct support for generic programming (§2.7), that is, programming using types as parameters. The C++ template mechanism allows a type to be a parameter in the definition of a class or a function. A template depends only on the properties that it actually uses from its parameter types and does not require different types used as arguments to be explicitly related. In particular, the argument types used for a template need not be from a single inheritance hierarchy. Here, templates are introduced with the primary focus on techniques needed for the design, implementation, and use of the standard library. The standard library requires a greater degree of generality, flexibility, and efficiency than does most software. Consequently, techniques that can be used in the design and implementation of the standard library are effective and efficient in the design of solutions to a wide variety of problems. These techniques enable an implementer to hide The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.328 Templates Chapter 13 sophisticated implementations behind simple interfaces and to expose complexity to the user only when the user has a specific need for it. For example, s so or rt t(v v) can be the interface to a variety of sort algorithms for elements of a variety of types held in a variety of containers. The sort function that is most appropriate for the particular v v will be automatically chosen. Every major standard library abstraction is represented as a template (for example, s st tr ri in ng g, o os st tr re ea am m, c co om mp pl le ex x, l li is st t, and m ma ap p) and so are the key operations (for example, s st tr ri in ng g compare, the output operator <<, c co om mp pl le ex x addition, getting the next element from a l li is st t, and s so or rt t()). This makes the library chapters (Part 3) of this book a rich source of examples of templates and pro- gramming techniques relying on them. Consequently, this chapter concentrates on smaller exam- ples illustrating technical aspects of templates and fundamental techniques for using them: §13.2: The basic mechanisms for defining and using class templates §13.3: Function templates, function overloading, and type deduction §13.4: Template parameters used to specify policies for generic algorithms §13.5: Multiple definitions providing alternative implementations for a template §13.6: Derivation and templates (run-time and compile-time polymorphism) §13.7: Source code organization Templates were introduced in §2.7.1 and §3.8. Detailed rules for template name resolution, tem- plate syntax, etc., can be found in §C.13. 13.2 A Simple String Template [temp.string] Consider a string of characters. A string is a class that holds characters and provides operations such as subscripting, concatenation, and comparison that we usually associate with the notion of a ‘‘string.’’ We would like to provide that behavior for many different kinds of characters. For example, strings of signed characters, of unsigned characters, of Chinese characters, of Greek char- acters, etc., are useful in various contexts. Thus, we want to represent the notion of ‘‘string’’ with minimal dependence on a specific kind of character. The definition of a string relies on the fact that a character can be copied, and little else. Thus, we can make a more general string type by taking the string of c ch ha ar r from §11.12 and making the character type a parameter: t te em mp pl la at te e c cl la as ss s S St tr ri in ng g { s st tr ru uc ct t S Sr re ep p; S Sr re ep p *r re ep p; p pu ub bl li ic c: S St tr ri in ng g() ; S St tr ri in ng g(c co on ns st t C C*) ; S St tr ri in ng g(c co on ns st t S St tr ri in ng g&) ; C C r re ea ad d(i in nt t i i) c co on ns st t; / / ... }; The t te em mp pl la at te e prefix specifies that a template is being declared and that a type argument C C will be used in the declaration. After its introduction, C C is used exactly like other type names. The scope of C C extends to the end of the declaration prefixed by t te em mp pl la at te e . Note that t te em mp pl la at te e says that C C is a type name; it need not be the name of a class. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 13.2 A Simple String Template 329 The name of a class template followed by a type bracketed by < > is the name of a class (as defined by the template) and can be used exactly like other class names. For example: S St tr ri in ng g c cs s; S St tr ri in ng g u us s; S St tr ri in ng g w ws s; c cl la as ss s J Jc ch ha ar r { / / Japanese character }; S St tr ri in ng g j js s; Except for the special syntax of its name, S St tr ri in ng g works exactly as if it had been defined using the definition of class S St tr ri in ng g in §11.12. Making S St tr ri in ng g a template allows us to provide the facilities we had for S St tr ri in ng g of c ch ha ar r for S St tr ri in ng gs of any kind of character. For example, if we use the standard library m ma ap p and the S St tr ri in ng g template, the word-counting example from §11.8 becomes: i in nt t m ma ai in n() / / count the occurrences of each word on input { S St tr ri in ng g b bu uf f; m ma ap p,i in nt t> m m; w wh hi il le e (c ci in n>>b bu uf f) m m[b bu uf f]++; / / write out result } The version for our Japanese-character type J Jc ch ha ar r would be: i in nt t m ma ai in n() / / count the occurrences of each word on input { S St tr ri in ng g b bu uf f; m ma ap p,i in nt t> m m; w wh hi il le e (c ci in n>>b bu uf f) m m[b bu uf f]++; / / write out result } The standard library provides the template class b ba as si ic c_ _s st tr ri in ng g that is similar to the templatized S St tr ri in ng g (§11.12, §20.3). In the standard library, s st tr ri in ng g is defined as a synonym for b ba as si ic c_ _s st tr ri in ng g: t ty yp pe ed de ef f b ba as si ic c_ _s st tr ri in ng g s st tr ri in ng g; This allows us to write the word-counting program like this: i in nt t m ma ai in n() / / count the occurrences of each word on input { s st tr ri in ng g b bu uf f; m ma ap p m m; w wh hi il le e (c ci in n>>b bu uf f) m m[b bu uf f]++; / / write out result } In general, t ty yp pe ed de ef fs are useful for shortening the long names of classes generated from templates. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.330 Templates Chapter 13 Also, we often prefer not to know the details of how a type is defined, and a t ty yp pe ed de ef f allows us to hide the fact that a type is generated from a template. 13.2.1 Defining a Template [temp.string.details] A class generated from a class template is a perfectly ordinary class. Thus, use of a template does not imply any run-time mechanisms beyond what is used for an equivalent ‘‘hand-written’’ class. Nor does it necessarily imply any reduction in the amount of code generated. It is usually a good idea to debug a particular class, such as S St tr ri in ng g, before turning it into a tem- plate such as S St tr ri in ng g. By doing so, we handle many design problems and most of the code errors in the context of a concrete example. This kind of debugging is familiar to all programmers, and most people cope better with a concrete example than with an abstract concept. Later, we can deal with any problems that might arise from generalization without being distracted by more con- ventional errors. Similarly, when trying to understand a template, it is often useful to imagine its behavior for a particular type argument such as c ch ha ar r before trying to comprehend the template in its full generality. Members of a template class are declared and defined exactly as they would have been for a non-template class. A template member need not be defined within the template class itself. In that case, its definition must be provided somewhere else, as for non-template class members (§C.13.7). Members of a template class are themselves templates parameterized by the parameters of their template class. When such a member is defined outside its class, it must explicitly be declared a template. For example: t te em mp pl la at te e s st tr ru uc ct t S St tr ri in ng g: :S Sr re ep p { C C* s s; / / pointer to elements i in nt t s sz z; / / number of elements i in nt t n n; / / reference count / / ... }; t te em mp pl la at te e C C S St tr ri in ng g: :r re ea ad d(i in nt t i i) c co on ns st t { r re et tu ur rn n r re ep p->s s[i i] ; } t te em mp pl la at te e S St tr ri in ng g: :S St tr ri in ng g() { p p = n ne ew w S Sr re ep p(0 0,C C()) ; } Template parameters, such as C C, are parameters rather than names of types defined externally to the template. However, that doesn’t affect the way we write the template code using them. Within the scope of S St tr ri in ng g, qualification with is redundant for the name of the template itself, so S St tr ri in ng g: :S St tr ri in ng g is the name for the constructor. If you prefer, you can be explicit: t te em mp pl la at te e S St tr ri in ng g: :S St tr ri in ng g() { p p = n ne ew w S Sr re ep p(0 0,C C()) ; } Just as there can be only one function defining a class member function in a program, there can be only one function template defining a class template member function in a program. However, The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 13.2.1 Defining a Template 331 overloading is a possibility for functions only (§13.3.2), while specialization (§13.5) enables us to provide alternative implementations for a template. It is not possible to overload a class template name, so if a class template is declared in a scope, no other entity can be declared there with the same name (see also §13.5). For example: t te em mp pl la at te e c cl la as ss s S St tr ri in ng g { /* ... */ }; c cl la as ss s S St tr ri in ng g { /* ... */ }; / / error: double definition A type used as a template argument must provide the interface expected by the template. For example, a type used as an argument to S St tr ri in ng g must provide the usual copy operations (§10.4.4.1, §20.2.1). Note that there is no requirement that different arguments for the same template parame- ter should be related by inheritance. 13.2.2 Template Instantiation [temp.string.inst] The process of generating a class declaration from a template class and a template argument is often called template instantiation (§C.13.7). Similarly, a function is generated (‘‘instantiated’’) from a template function plus a template argument. A version of a template for a particular template argu- ment is called a specialization. In general, it is the implementation’s job ± not the programmer’s ± to ensure that versions of a template function are generated for each set of template arguments used (§C.13.7). For example: S St tr ri in ng g c cs s; v vo oi id d f f() { S St tr ri in ng g j js s; c cs s = "I It t´s s t th he e i im mp pl le em me en nt ta at ti io on n´s s j jo ob b t to o f fi ig gu ur re e o ou ut t w wh ha at t c co od de e n ne ee ed ds s t to o b be e g ge en ne er ra at te ed d"; } For this, the implementation generates declarations for S St tr ri in ng g and S St tr ri in ng g, for their corresponding S Sr re ep p types, for their destructors and default constructors, and for the assignment S St tr ri in ng g: :o op pe er ra at to or r=(c ch ha ar r*). Other member functions are not used and should not be gen- erated. The generated classes are perfectly ordinary classes that obey all the usual rules for classes. Similarly, generated functions are ordinary functions that obey all the usual rules for functions. Obviously, templates provide a powerful way of generating code from relatively short defini- tions. Consequently, a certain amount of caution is in order to avoid flooding memory with almost identical function definitions (§13.5). 13.2.3 Template Parameters [temp.param] A template can take type parameters, parameters of ordinary types such as i in nt ts, and template parameters (§C.13.3). Naturally, a template can take several parameters. For example: t te em mp pl la at te e c cl la as ss s C Co on nt t { /* ... */ }; As shown, a template parameter can be used in the definition of subsequent template parameters. Integer arguments come in handy for supplying sizes and limits. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.332 Templates Chapter 13 t te em mp pl la at te e c cl la as ss s B Bu uf ff fe er r { T T v v[i i] ; i in nt t s sz z; p pu ub bl li ic c: B Bu uf ff fe er r() : s sz z(i i) {} / / ... }; B Bu uf ff fe er r c cb bu uf f; B Bu uf ff fe er r r rb bu uf f; Simple and constrained containers such as B Bu uf ff fe er r can be important where run-time efficiency and compactness are paramount (thus preventing the use of a more general s st tr ri in ng g or v ve ec ct to or r). Passing a size as a template argument allows B Bu uf ff fe er r’s implementer to avoid free store use. Another example is the R Ra an ng ge e type in §25.6.1. A template argument can be a constant expression (§C.5), the address of an object or function with external linkage (§9.2), or a non-overloaded pointer to member (§15.5). A pointer used as a template argument must be of the form &o of f, where o of f is the name of an object or a function, or of the form f f, where f f is the name of a function. A pointer to member must be of the form &X X: :o of f, where o of f is the name of an member. In particular, a string literal is not acceptable as a template argument. An integer template argument must be a constant: v vo oi id d f f(i in nt t i i) { B Bu uf ff fe er r b bx x; / / error: constant expression expected } Conversely, a non-type template parameter is a constant within the template so that an attempt to change the value of a parameter is an error. 13.2.4 Type Equivalence [temp.equiv] Given a template, we can generate types by supplying template arguments. For example: S St tr ri in ng g s s1 1; S St tr ri in ng g s s2 2; S St tr ri in ng g s s3 3; t ty yp pe ed de ef f u un ns si ig gn ne ed d c ch ha ar r U Uc ch ha ar r; S St tr ri in ng g s s4 4; S St tr ri in ng g s s5 5; B Bu uf ff fe er r,1 10 0> b b1 1; B Bu uf ff fe er r b b2 2; B Bu uf ff fe er r b b3 3; When using the same set of template arguments for a template, we always refer to the same gener- ated type. However, what does ‘‘the same’’ mean in this context? As usual, t ty yp pe ed de ef fs do not intro- duce new types, so S St tr ri in ng g is the same type as S St tr ri in ng g. Conversely, The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 13.2.4 Type Equivalence 333 because c ch ha ar r and u un ns si ig gn ne ed d c ch ha ar r are different types (§4.3), S St tr ri in ng g and S St tr ri in ng g are different types. The compiler can evaluate constant expressions (§C.5), so B Bu uf ff fe er r is recognized to be the same type as B Bu uf ff fe er r. 13.2.5 Type Checking [temp.check] A template is defined and then later used in combination with a set of template arguments. When the template is defined, the definition is checked for syntax errors and possibly also for other errors that can be detected in isolation from a particular set of template arguments. For example: t te em mp pl la at te e c cl la as ss s L Li is st t { s st tr ru uc ct t L Li in nk k { L Li in nk k* p pr re e; L Li in nk k* s su uc c; T T v va al l; L Li in nk k(L Li in nk k* p p, L Li in nk k* s s,c co on ns st t T T& v v) :p pr re e(p p) , s su uc c(s s) , v va al l(v v) { } } / / syntax error: missing semicolon L Li in nk k* h he ea ad d; p pu ub bl li ic c: L Li is st t() : h he ea ad d(7 7) { } / / error: pointer initialized with int L Li is st t(c co on ns st t T T& t t) : h he ea ad d(n ne ew w L Li in nk k(0 0,o o,t t)) { } / / error: undefined identifier ‘o’ / / ... v vo oi id d p pr ri in nt t_ _a al ll l() { f fo or r (L Li in nk k* p p = h he ea ad d; p p; p p=p p->s su uc c) c co ou ut t << p p->v va al l << ´\ \n n´; } }; A compiler can catch simple semantic errors at the point of definition or later at the point of use. Users generally prefer early detection, but not all ‘‘simple’’ errors are easy to detect. Here, I made three ‘‘mistakes.’’ Independently of what the template parameter is, a pointer T T* cannot be initial- ized by the integer 7 7. Similarly, the identifier o o (a mistyped 0 0, of course) cannot be an argument to L Li is st t: :L Li in nk k’s constructor because there is no such name in scope. A name used in a template definition must either be in scope or in some reasonably obvious way depend on a template parameter (§C.13.8.1). The most common and obvious way of depend- ing on a template parameter T T is to use a member of a T T or to take an argument of type T T. In L Li is st t: :p pr ri in nt t_ _a al ll l(), c co ou ut t<

v va al l is a slightly more subtle example. Errors that relate to the use of template parameters cannot be detected until the template is used. For example: c cl la as ss s R Re ec c { /* ... */ }; v vo oi id d f f(L Li is st t& l li i, L Li is st t& l lr r) { l li i.p pr ri in nt t_ _a al ll l() ; l lr r.p pr ri in nt t_ _a al ll l() ; } The l li i.p pr ri in nt t_ _a al ll l() checks out fine, but l lr r.p pr ri in nt t_ _a al ll l() gives a type error because there is no << output operator defined for R Re ec c. The earliest that errors relating to a template parameter can be detected is at the first point of use of the template for a particular template argument. That point is The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.334 Templates Chapter 13 usually called the first point of instantiation, or simply the point of instantiation (see §C.13.7). The implementation is allowed to postpone this checking until the program is linked. If we had only a declaration of p pr ri in nt t_ _a al ll l() available in this translation unit, rather than its definition, the implemen- tation might have had to delay type checking (see §13.7). Independently of when checking is done, the same set of rules is checked. Again, users prefer early checking. It is possible to express con- straints on template arguments in terms of member functions (see §13.9[16]). 13.3 Function Templates [temp.fct] For most people, the first and most obvious use of templates is to define and use container classes such as b ba as si ic c_ _s st tr ri in ng g (§20.3), v ve ec ct to or r (§16.3), l li is st t (§17.2.2), and m ma ap p (§17.4.1). Soon after, the need for template functions arises. Sorting an array is a simple example: t te em mp pl la at te e v vo oi id d s so or rt t(v ve ec ct to or r&) ; / / declaration v vo oi id d f f(v ve ec ct to or r& v vi i, v ve ec ct to or r& v vs s) { s so or rt t(v vi i) ; / / sort(vector&); s so or rt t(v vs s) ; / / sort(vector&); } When a template function is called, the types of the function arguments determine which version of the template is used; that is, the template arguments are deduced from the function arguments (§13.3.1). Naturally, the template function must be defined somewhere (§C.13.7): t te em mp pl la at te e v vo oi id d s so or rt t(v ve ec ct to or r& v v) / / definition / / Shell sort (Knuth, Vol. 3, pg. 84). { c co on ns st t s si iz ze e_ _t t n n = v v.s si iz ze e() ; f fo or r (i in nt t g ga ap p=n n/2 2; 0 0 T T l lo oo ok ku up p(B Bu uf ff fe er r& b b, c co on ns st t c ch ha ar r* p p) ; c cl la as ss s R Re ec co or rd d { c co on ns st t c ch ha ar r[1 12 2] ; / / ... }; R Re ec co or rd d f f(B Bu uf ff fe er r& b bu uf f, c co on ns st t c ch ha ar r* p p) { r re et tu ur rn n l lo oo ok ku up p(b bu uf f,p p) ; / / use the lookup() where T is Record and i is 128 } Here, T T is deduced to be R Re ec co or rd d and i i is deduced to be 1 12 28 8. Note that class template parameters are never deduced. The reason is that the flexibility pro- vided by several constructors for a class would make such deduction impossible in many cases and obscure in many more. Specialization provides a mechanism for implicitly choosing between dif- ferent implementations of a class (§13.5). If we need to create an object of a deduced type, we can often do that by calling a function to do the creation; see m ma ak ke e_ _p pa ai ir r() in §17.4.1.2. If a template argument cannot be deduced from the template function arguments (§C.13.4), we must specify it explicitly. This is done in the same way template arguments are explicitly specified for a template class. For example: t te em mp pl la at te e c cl la as ss s v ve ec ct to or r { /* ... */ }; t te em mp pl la at te e T T* c cr re ea at te e() ; / / make a T and return a pointer to it v vo oi id d f f() { v ve ec ct to or r v v; / / class, template argument ‘int’ i in nt t* p p = c cr re ea at te e() ; / / function, template argument ‘int’ } One common use of explicit specification is to provide a return type for a template function: t te em mp pl la at te e T T i im mp pl li ic ci it t_ _c ca as st t(U U u u) { r re et tu ur rn n u u; } v vo oi id d g g(i in nt t i i) { i im mp pl li ic ci it t_ _c ca as st t(i i) ; / / error: can’t deduce T i im mp pl li ic ci it t_ _c ca as st t(i i) ; / / T is double; U is int The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.336 Templates Chapter 13 i im mp pl li ic ci it t_ _c ca as st t(i i) ; / / T is char; U is double i im mp pl li ic ci it t_ _c ca as st t(i i) ; / / T is char*; U is int; error: cannot convert int to char* } As with default function arguments (§7.5), only trailing arguments can be left out of a list of explicit template arguments. Explicit specification of template arguments allows the definition of families of conversion functions and object creation functions (§13.3.2, §C.13.1, §C.13.5). An explicit version of the implicit conversions (§C.6), such as i im mp pl li ic ci it t_ _c ca as st t(), is frequently useful. The syntax for d dy yn na am mi ic c_ _c ca as st t, s st ta at ti ic c_ _c ca as st t, etc., (§6.2.7, §15.4.1) matches the explicitly qualified template function syntax. However, the built-in type conversion operators supply operations that cannot be expressed by other language features. 13.3.2 Function Template Overloading [temp.over] One can declare several function templates with the same name and even declare a combination of function templates and ordinary functions with the same name. When an overloaded function is called, overload resolution is necessary to find the right function or template function to invoke. For example: t te em mp pl la at te e T T s sq qr rt t(T T) ; t te em mp pl la at te e c co om mp pl le ex x s sq qr rt t(c co om mp pl le ex x) ; d do ou ub bl le e s sq qr rt t(d do ou ub bl le e) ; v vo oi id d f f(c co om mp pl le ex x z z) { s sq qr rt t(2 2) ; / / sqrt(int) s sq qr rt t(2 2.0 0) ; / / sqrt(double) s sq qr rt t(z z) ; / / sqrt(complex) } In the same way that a template function is a generalization of the notion of a function, the rules for resolution in the presence of function templates are generalizations of the function overload resolu- tion rules. Basically, for each template we find the specialization that is best for the set of function arguments. Then, we apply the usual function overload resolution rules to these specializations and all ordinary functions: [1] Find the set of function template specializations (§13.2.2) that will take part in overload res- olution. Do this by considering each function template and deciding which template argu- ments, if any, would be used if no other function templates or functions of the same name were in scope. For the call s sq qr rt t(z z), this makes s sq qr rt t(c co om mp pl le ex x) and s sq qr rt t< c co om mp pl le ex x >(c co om mp pl le ex x) candidates. [2] If two template functions can be called and one is more specialized than the other (§13.5.1), consider only the most specialized template function in the following steps. For the call s sq qr rt t(z z), this means that s sq qr rt t(c co om mp pl le ex x) is preferred over s sq qr rt t< c co om mp pl le ex x >(c co om mp pl le ex x): any call that matches s sq qr rt t(c co om mp pl le ex x) also matches s sq qr rt t(T T). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 13.3.2 Function Template Overloading 337 [3] Do overload resolution for this set of functions, plus any ordinary functions as for ordinary functions (§7.4). If a template function argument has been determined by template argu- ment deduction (§13.3.1), that argument cannot also have promotions, standard conversions, or user-defined conversions applied. For s sq qr rt t(2 2) , s sq qr rt t(i in nt t) is an exact match, so it is preferred over s sq qr rt t(d do ou ub bl le e). [4] If a function and a specialization are equally good matches, the function is preferred. Con- sequently, s sq qr rt t(d do ou ub bl le e) is preferred over s sq qr rt t(d do ou ub bl le e) for s sq qr rt t(2 2.0 0). [5] If no match is found, the call is an error. If we end up with two or more equally good matches, the call is ambiguous and is an error. For example: t te em mp pl la at te e T T m ma ax x(T T,T T) ; c co on ns st t i in nt t s s = 7 7; v vo oi id d k k() { m ma ax x(1 1,2 2) ; / / max(1,2) m ma ax x(´a a´,´b b´) ; / / max(’a’,’b’) m ma ax x(2 2.7 7,4 4.9 9) ; / / max(2.7,4.9) m ma ax x(s s,7 7) ; / / max(int(s),7) (trivial conversion used) m ma ax x(´a a´,1 1) ; / / error: ambiguous (no standard conversion) m ma ax x(2 2.7 7,4 4) ; / / error: ambiguous (no standard conversion) } We could resolve the two ambiguities either by explicit qualification: v vo oi id d f f() { m ma ax x(´a a´,1 1) ; / / max(int(’a’),1) m ma ax x(2 2.7 7,4 4) ; / / max(2.7,double(4)) } or by adding suitable declarations: i in nl li in ne e i in nt t m ma ax x(i in nt t i i, i in nt t j j) { r re et tu ur rn n m ma ax x(i i,j j) ; } i in nl li in ne e d do ou ub bl le e m ma ax x(i in nt t i i, d do ou ub bl le e d d) { r re et tu ur rn n m ma ax x(i i,d d) ; } i in nl li in ne e d do ou ub bl le e m ma ax x(d do ou ub bl le e d d, i in nt t i i) { r re et tu ur rn n m ma ax x(d d,i i) ; } i in nl li in ne e d do ou ub bl le e m ma ax x(d do ou ub bl le e d d1 1, d do ou ub bl le e d d2 2) { r re et tu ur rn n m ma ax x(d d1 1,d d2 2) ; } v vo oi id d g g() { m ma ax x(´a a´,1 1) ; / / max(int(’a’),1) m ma ax x(2 2.7 7,4 4) ; / / max(2.7,double(4)) } For ordinary functions, ordinary overloading rules (§7.4) apply, and the use of i in nl li in ne e ensures that no extra overhead is imposed. The definition of m ma ax x() is trivial, so we could have written it explicitly. However, using a spe- cialization of the template is an easy and general way of defining such resolution functions. The overload resolution rules ensure that template functions interact properly with inheritance: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.338 Templates Chapter 13 t te em mp pl la at te e c cl la as ss s B B { /* ... */ }; t te em mp pl la at te e c cl la as ss s D D : p pu ub bl li ic c B B { /* ... */ }; t te em mp pl la at te e v vo oi id d f f(B B*) ; v vo oi id d g g(B B* p pb b, D D* p pd d) { f f(p pb b) ; / / f(pb) f f(p pd d) ; / / f(static_cast*>(pd)); standard conversion D* to B* used } In this example, the template function f f() accepts a B B* for any type T T. We have an argument of type D D*, so the compiler easily deduces that by choosing T T to be i in nt t, the call can be uniquely resolved to a call of f f(B B*). A function argument that is not involved in the deduction of a template parameter is treated exactly as an argument of a non-template function. In particular, the usual conversion rules hold. Consider: t te em mp pl la at te e i in nt t g ge et t_ _n nt th h(C C& p p, i in nt t n n) ; / / get n-th element This function presumably returns the value of the n-th element of a container of type C C. Because C C has to be deduced from an actual argument of g ge et t_ _n nt th h() in a call, conversions are not applicable to the first argument. However, the second argument is perfectly ordinary, so the full range of possi- ble conversions is considered. For example: c cl la as ss s I In nd de ex x { p pu ub bl li ic c: o op pe er ra at to or r i in nt t() ; / / ... }; v vo oi id d f f(v ve ec ct to or r& v v, s sh ho or rt t s s, I In nd de ex x i i) { i in nt t i i1 1 = g ge et t_ _n nt th h(v v,2 2) ; / / exact match i in nt t i i2 2 = g ge et t_ _n nt th h(v v,s s) ; / / standard conversion: short to int i in nt t i i3 3 = g ge et t_ _n nt th h(v v,i i) ; / / user-defined conversion: Index to int } 13.4 Using Template Arguments to Specify Policy [temp.policy] Consider how to sort strings. Three concepts are involved: the string, the element type, and the cri- teria used by the sort algorithm for comparing string elements. We can’t hardwire the sorting criteria into the container because the container can’t (in general) impose its needs on the element types. We can’t hardwire the sorting criteria into the element type because there are many different ways of sorting elements. Consequently, the sorting criteria are built neither into the container nor into the element type. Instead, the criteria must be supplied when a specific operation needs to be performed. For exam- ple, if I have strings of characters representing names of Swedes, what collating criteria would I The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 13.4 Using Template Arguments to Specify Policy 339 like to use for a comparison? Two different collating sequences (numerical orderings of the charac- ters) are commonly used for sorting Swedish names. Naturally, neither a general string type nor a general sort algorithm should know about the conventions for sorting names in Sweden. Therefore, any general solution requires that the sorting algorithm be expressed in general terms that can be defined not just for a specific type but also for a specific use of a specific type. For example, let us generalize the standard C library function s st tr rc cm mp p() for S St tr ri in ng gs of any type T T (§13.2): t te em mp pl la at te e i in nt t c co om mp pa ar re e(c co on ns st t S St tr ri in ng g& s st tr r1 1, c co on ns st t S St tr ri in ng g& s st tr r2 2) { f fo or r(i in nt t i i=0 0; i i c cl la as ss s C Cm mp p { / / normal, default compare p pu ub bl li ic c: s st ta at ti ic c i in nt t e eq q(T T a a, T T b b) { r re et tu ur rn n a a==b b; } s st ta at ti ic c i in nt t l lt t(T T a a, T T b b) { r re et tu ur rn n a a s sw we ed de e1 1, S St tr ri in ng g s sw we ed de e2 2) { c co om mp pa ar re e< c ch ha ar r,C Cm mp p >(s sw we ed de e1 1,s sw we ed de e2 2) ; c co om mp pa ar re e< c ch ha ar r,L Li it te er ra at te e >(s sw we ed de e1 1,s sw we ed de e2 2) ; } Passing the comparison operations as a template parameter has two significant benefits compared to alternatives such as passing pointers to functions. Several operations can be passed as a single argument with no run-time cost. In addition, the comparison operators e eq q() and l lt t() are trivial to inline, whereas inlining a call through a pointer to function requires exceptional attention from a compiler. Naturally, comparison operations can be provided for user-defined types as well as built-in types. This is essential to allow general algorithms to be applied to types with nontrivial compari- son criteria (see §18.4). Each class generated from a class template gets a copy of each s st ta at ti ic c member of the class tem- plate (see §C.13.1). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.340 Templates Chapter 13 13.4.1 Default Template Parameters [temp.default] Explicitly specifying the comparison criteria for each call is tedious. Fortunately, it is easy to pick a default so that only uncommon comparison criteria have to be explicitly specified. This can be implemented through overloading: t te em mp pl la at te e i in nt t c co om mp pa ar re e(c co on ns st t S St tr ri in ng g& s st tr r1 1, c co on ns st t S St tr ri in ng g& s st tr r2 2) ; / / compare using C t te em mp pl la at te e i in nt t c co om mp pa ar re e(c co on ns st t S St tr ri in ng g& s st tr r1 1, c co on ns st t S St tr ri in ng g& s st tr r2 2) ; / / compare using Cmp Alternatively, we can supply the normal convention as a default template argument: t te em mp pl la at te e > i in nt t c co om mp pa ar re e(c co on ns st t S St tr ri in ng g& s st tr r1 1, c co on ns st t S St tr ri in ng g& s st tr r2 2) { f fo or r(i in nt t i i=0 0; i i s sw we ed de e1 1, S St tr ri in ng g s sw we ed de e2 2) { c co om mp pa ar re e(s sw we ed de e1 1,s sw we ed de e2 2) ; / / use Cmp c co om mp pa ar re e(s sw we ed de e1 1,s sw we ed de e2 2) ; / / use Literate } A less esoteric example (for non-Swedes) is comparing with and without taking case into account: c cl la as ss s N No o_ _c ca as se e { /* ... */ }; v vo oi id d f f(S St tr ri in ng g s s1 1, S St tr ri in ng g s s2 2) { c co om mp pa ar re e(s s1 1,s s2 2) ; / / case sensitive c co om mp pa ar re e(s s1 1,s s2 2) ; / / not sensitive to case } The technique of supplying a policy through a template argument and then defaulting that argument to supply the most common policy is widely used in the standard library (e.g., §18.4). Curiously enough, it is not used for b ba as si ic c_ _s st tr ri in ng g (§13.2, Chapter 20) comparisons. Template parameters used to express policies are often called ‘‘traits.’’ For example, the standard library string relies on c ch ha ar r_ _t tr ra ai it ts s (§20.2.1), the standard algorithms on iterator traits (§19.2.2), and the standard library containers on a al ll lo oc ca at to or rs s (§19.4). The semantic checking of a default argument for a template parameter is done if and (only) when that default argument is actually used. In particular, as long as we refrain from using the default template argument C Cm mp p we can c co om mp pa ar re e() strings of a type X X for which C Cm mp p wouldn’t compile (say, because < wasn’t defined for an X X). This point is crucial in the design of the standard containers, which rely on a template argument to specify default values (§16.3.4). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 13.5 Specialization 341 13.5 Specialization [temp.special] By default, a template gives a single definition to be used for every template argument (or combina- tion of template arguments) that a user can think of. This doesn’t always make sense for someone writing a template. I might want to say, ‘‘if the template argument is a pointer, use this implemen- tation; if it is not, use that implementation’’ or ‘‘give an error unless the template argument is a pointer derived from class M My y_ _b ba as se e.’’ Many such design concerns can be addressed by providing alternative definitions of the template and having the compiler choose between them based on the template arguments provided where they are used. Such alternative definitions of a template are called user-defined specializations, or simply, user specializations. Consider likely uses of a V Ve ec ct to or r template: t te em mp pl la at te e c cl la as ss s V Ve ec ct to or r { / / general vector type T T* v v; i in nt t s sz z; p pu ub bl li ic c: V Ve ec ct to or r() ; V Ve ec ct to or r(i in nt t) ; T T& e el le em m(i in nt t i i) { r re et tu ur rn n v v[i i] ; } T T& o op pe er ra at to or r[](i in nt t i i) ; v vo oi id d s sw wa ap p(V Ve ec ct to or r&) ; / / ... }; V Ve ec ct to or r v vi i; V Ve ec ct to or r v vp ps s; V Ve ec ct to or r v vs s; V Ve ec ct to or r v vp pc c; V Ve ec ct to or r v vp pn n; Most V Ve ec ct to or rs will be V Ve ec ct to or rs of some pointer type. There are several reasons for this, but the pri- mary reason is that to preserve run-time polymorphic behavior, we must use pointers (§2.5.4, §12.2.6). That is, anyone who practices object-oriented programming and also uses type-safe con- tainers (such as the standard library containers) will end up with a lot of containers of pointers. The default behavior of most C++ implementations is to replicate the code for template func- tions. This is good for run-time performance, but unless care is taken it leads to code bloat in criti- cal cases such as the V Ve ec ct to or r example. Fortunately, there is an obvious solution. Containers of pointers can share a single implementa- tion. This can be expressed through specialization. First, we define a version (a specialization) of V Ve ec ct to or r for pointers to v vo oi id d: t te em mp pl la at te e<> c cl la as ss s V Ve ec ct to or r { v vo oi id d** p p; / / ... v vo oi id d*& o op pe er ra at to or r[](i in nt t i i) ; }; This specialization can then be used as the common implementation for all V Ve ec ct to or rs of pointers. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.342 Templates Chapter 13 The t te em mp pl la at te e<> prefix says that this is a specialization that can be specified without a template parameter. The template arguments for which the specialization is to be used are specified in <> brackets after the name. That is, the says that this definition is to be used as the imple- mentation of every V Ve ec ct to or r for which T T is void* . The V Ve ec ct to or r is a complete specialization. That is, there is no template parameter to specify or deduce when we use the specialization; V Ve ec ct to or r is used for V Ve ec ct to or rs declared like this: V Ve ec ct to or r v vp pv v; To define a specialization that is used for every V Ve ec ct to or r of pointers and only for V Ve ec ct to or rs of pointers, we need a partial specialization: t te em mp pl la at te e c cl la as ss s V Ve ec ct to or r : p pr ri iv va at te e V Ve ec ct to or r { p pu ub bl li ic c: t ty yp pe ed de ef f V Ve ec ct to or r B Ba as se e; V Ve ec ct to or r() : B Ba as se e() {} e ex xp pl li ic ci it t V Ve ec ct to or r(i in nt t i i) : B Ba as se e(i i) {} T T*& e el le em m(i in nt t i i) { r re et tu ur rn n s st ta at ti ic c_ _c ca as st t(B Ba as se e: :e el le em m(i i)) ; } T T*& o op pe er ra at to or r[](i in nt t i i) { r re et tu ur rn n s st ta at ti ic c_ _c ca as st t(B Ba as se e: :o op pe er ra at to or r[](i i)) ; } / / ... }; The specialization pattern after the name says that this specialization is to be used for every pointer type; that is, this definition is to be used for every V Ve ec ct to or r with a template argument that can be expressed as T T*. For example: V Ve ec ct to or r v vp ps s; / / is so T is Shape V Ve ec ct to or r v vp pp pi i; / / is so T is int* Note that when a partial specialization is used, a template parameter is deduced from the specializa- tion pattern; the template parameter is not simply the actual template argument. In particular, for V Ve ec ct to or r, T T is S Sh ha ap pe e and not S Sh ha ap pe e*. Given this partial specialization of V Ve ec ct to or r, we have a shared implementation for all V Ve ec ct to or rs of pointers. The V Ve ec ct to or r class is simply an interface to v vo oi id d* implemented exclusively through derivation and inline expansion. It is important that this refinement of the implementation of V Ve ec ct to or r is achieved without affect- ing the interface presented to users. Specialization is a way of specifying alternative implementa- tions for different uses of a common interface. Naturally, we could have given the general V Ve ec ct to or r and the V Ve ec ct to or r of pointers different names. However, when I tried that, many people who should have known better forgot to use the pointer classes and found their code much larger than expected. In this case, it is much better to hide the crucial implementation details behind a common interface. This technique proved successful in curbing code bloat in real use. People who do not use a technique like this (in C++ or in other languages with similar facilities for type parameterization) have found that replicated code can cost megabytes of code space even in moderately-sized pro- grams. By eliminating the time needed to compile those additional versions of the vector opera- tions, this technique can also cut compile and link times dramatically. Using a single specialization The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 13.5 Specialization 343 to implement all lists of pointers is an example of the general technique of minimizing code bloat by maximizing the amount of shared code. The general template must be declared before any specialization. For example: t te em mp pl la at te e c cl la as ss s L Li is st t { /* ... */ }; t te em mp pl la at te e c cl la as ss s L Li is st t { /* ... */ }; / / error: general template after specialization The critical information supplied by the general template is the set of template parameters that the user must supply to use it or any of its specializations. Consequently, a declaration of the general case is sufficient to allow the declaration or definition of a specialization: t te em mp pl la at te e c cl la as ss s L Li is st t; t te em mp pl la at te e c cl la as ss s L Li is st t { /* ... */ }; If used, the general template needs to be defined somewhere (§13.7). If a user specializes a template somewhere, that specialization must be in scope for every use of the template with the type for which it was specialized. For example: t te em mp pl la at te e c cl la as ss s L Li is st t { /* ... */ }; L Li is st t l li i; t te em mp pl la at te e c cl la as ss s L Li is st t { /* ... */ }; / / error Here, L Li is st t was specialized for i in nt t* after L Li is st t had been used. All specializations of a template must be declared in the same namespace as the template itself. If used, a specialization that is explicitly declared (as opposed to generated from a more general template) must also be explicitly defined somewhere (§13.7). In other words, explicitly specializ- ing a template implies that no definition is generated for that specialization. 13.5.1 Order of Specializations [temp.special.order] One specialization is more specialized than another if every argument list that matches its special- ization pattern also matches the other, but not vice versa. For example: t te em mp pl la at te e c cl la as ss s V Ve ec ct to or r; / / general t te em mp pl la at te e c cl la as ss s V Ve ec ct to or r; / / specialized for any pointer t te em mp pl la at te e<> c cl la as ss s V Ve ec ct to or r; / / specialized for void* Every type can be used as a template argument for the most general V Ve ec ct to or r, but only pointers can be used for V Ve ec ct to or r and only v vo oi id d*s can be used for V Ve ec ct to or r. The most specialized version will be preferred over the others in declarations of objects, point- ers, etc., (§13.5) and in overload resolution (§13.3.2). A specialization pattern can be specified in terms of types composed using the constructs allowed for template parameter deduction (§13.3.1). The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.344 Templates Chapter 13 13.5.2 Template Function Specialization [temp.special.fct] Naturally, specialization is also useful for template functions. Consider the Shell sort from §7.7 and §13.3. It compares elements using < and swaps elements using detailed code. A better defini- tion would be: t te em mp pl la at te e b bo oo ol l l le es ss s(T T a a, T T b b) { r re et tu ur rn n a a v vo oi id d s so or rt t(V Ve ec ct to or r& v v) { c co on ns st t s si iz ze e_ _t t n n = v v.s si iz ze e() ; f fo or r (i in nt t g ga ap p=n n/2 2; 0 0 correctly because < will compare the two c ch ha ar r*s. That is, it will compare the addresses of the first c ch ha ar r in each string. Instead, we would like it to compare the characters pointed to. A simple specialization of l le es ss s() for c co on ns st t c ch ha ar r* will take care of that: t te em mp pl la at te e<> b bo oo ol l l le es ss s(c co on ns st t c ch ha ar r* a a, c co on ns st t c ch ha ar r* b b) { r re et tu ur rn n s st tr rc cm mp p(a a,b b)<0 0; } As for classes (§13.5), the t te em mp pl la at te e<> prefix says that this is a specialization that can be specified without a template parameter. The after the template function name means that this specialization is to be used in cases where the template argument is c co on ns st t c ch ha ar r*. Because the tem- plate argument can be deduced from the function argument list, we need not specify it explicitly. So, we could simplify the definition of the specialization: t te em mp pl la at te e<> b bo oo ol l l le es ss s<>(c co on ns st t c ch ha ar r* a a, c co on ns st t c ch ha ar r* b b) { r re et tu ur rn n s st tr rc cm mp p(a a,b b)<0 0; } Given the t te em mp pl la at te e<> prefix, the second empty <> is redundant, so we would typically simply write: t te em mp pl la at te e<> b bo oo ol l l le es ss s(c co on ns st t c ch ha ar r* a a, c co on ns st t c ch ha ar r* b b) { r re et tu ur rn n s st tr rc cm mp p(a a,b b)<0 0; } I prefer this shorter form of declaration. Consider the obvious definition of s sw wa ap p(): The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 13.5.2 Template Function Specialization 345 t te em mp pl la at te e v vo oi id d s sw wa ap p(T T& x x, T T& y y) { T T t t = x x; / / copy x to temporary x x = y y; / / copy y to x y y = t t; / / copy temporary to y } This is rather inefficient when invoked for V Ve ec ct to or rs of V Ve ec ct to or rs; it swaps V Ve ec ct to or rs by copying all ele- ments. This problem can also be solved by appropriate specialization. A V Ve ec ct to or r object will itself hold only sufficient data to give indirect access to the elements (like s st tr ri in ng g; §11.12, §13.2). Thus, a swap can be done by swapping those representations. To be able to manipulate that representa- tion, I provided V Ve ec ct to or r with a member function s sw wa ap p() (§13.5): t te em mp pl la at te e v vo oi id d V Ve ec ct to or r: :s sw wa ap p(V Ve ec ct to or r & a a) / / swap representations { s sw wa ap p(v v,a a.v v) ; s sw wa ap p(s sz z,a a.s sz z) ; } This member s sw wa ap p() can now be used to define a specialization of the general s sw wa ap p(): t te em mp pl la at te e v vo oi id d s sw wa ap p(V Ve ec ct to or r& a a, V Ve ec ct to or r& b b) { a a.s sw wa ap p(b b) ; } These specializations of l le es ss s() and s sw wa ap p() are used in the standard library (§16.3.9, §20.3.16). In addition, they are examples of widely applicable techniques. Specialization is useful when there is a more efficient alternative to a general algorithm for a set of template arguments (here, s sw wa ap p()). In addition, specialization comes in handy when an irregularity of an argument type causes the general algorithm to give an undesired result (here, l le es ss s()). These ‘‘irregular types’’ are often the built-in pointer and array types. 13.6 Derivation and Templates [temp.derive] Templates and derivation are mechanisms for building new types out of existing ones, and gener- ally for writing useful code that exploits various forms of commonality. As shown in §3.7.1, §3.8.5, and §13.5, combinations of the two mechanisms are the basis for many useful techniques. Deriving a template class from a non-template class is a way of providing a common implemen- tation for a set of templates. The list from §13.5 is a good example of this: t te em mp pl la at te e c cl la as ss s l li is st t : p pr ri iv va at te e l li is st t { /* ... */ }; Another way of looking at such examples is that a template is used to provide an elegant and type- safe interface to an otherwise unsafe and inconvenient-to-use facility. Naturally, it is often useful to derive one template class from another. One use of a base class is as a building block in the implementation of further classes. If the data or operations in such a base The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.346 Templates Chapter 13 class depend on a template parameter of a derived class, the base itself must be parameterized; V Ve ec c from §3.7.1 is an example of this: t te em mp pl la at te e c cl la as ss s v ve ec ct to or r { /* ... */ }; t te em mp pl la at te e c cl la as ss s V Ve ec c : p pu ub bl li ic c v ve ec ct to or r { /* ... */ }; The overload resolution rules for template functions ensure that functions work ‘‘correctly’’ for such derived types (§13.3.2). Having the same template parameter for the base and derived class is the most common case, but it is not a requirement. Interesting, although less frequently used, techniques rely on passing the derived type itself to the base class. For example: t te em mp pl la at te e c cl la as ss s B Ba as si ic c_ _o op ps s { / / basic operators on containers b bo oo ol l o op pe er ra at to or r==(c co on ns st t C C&) c co on ns st t; / / compare all elements b bo oo ol l o op pe er ra at to or r!=(c co on ns st t C C&) c co on ns st t; / / ... }; t te em mp pl la at te e c cl la as ss s M Ma at th h_ _c co on nt ta ai in ne er r : p pu ub bl li ic c B Ba as si ic c_ _o op ps s< M Ma at th h_ _c co on nt ta ai in ne er r > { p pu ub bl li ic c: s si iz ze e_ _t t s si iz ze e() c co on ns st t; T T& o op pe er ra at to or r[](s si iz ze e_ _t t) ; / / ... }; This allows the definition of the basic operations on containers to be separate from the definition of the containers themselves and defined once only. However, the definition of operations such as == and != must be expressed in terms of both the container and its elements, so the base class needs to be passed to the container template. Assuming that a M Ma at th h_ _c co on nt ta ai in ne er r is similar to a traditional vector, the definitions of a B Ba as si ic c_ _o op ps s member would look something like this: t te em mp pl la at te e b bo oo ol l B Ba as si ic c_ _o op ps s: :o op pe er ra at to or r==(c co on ns st t C C& a a) c co on ns st t { i if f (s si iz ze e() != a a.s si iz ze e()) r re et tu ur rn n f fa al ls se e; f fo or r (i in nt t i i = 0 0; i i c cl la as ss s M Mc co on nt ta ai in ne er r { C C e el le em me en nt ts s; p pu ub bl li ic c: / / ... T T& o op pe er ra at to or r[](s si iz ze e_ _t t i i) { r re et tu ur rn n e el le em me en nt ts s[i i] ; } The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 13.6 Derivation and Templates 347 f fr ri ie en nd d b bo oo ol l o op pe er ra at to or r==(c co on ns st t M Mc co on nt ta ai in ne er r&, c co on ns st t M Mc co on nt ta ai in ne er r&) ; / / compare elements f fr ri ie en nd d b bo oo ol l o op pe er ra at to or r!=(c co on ns st t M Mc co on nt ta ai in ne er r&, c co on ns st t M Mc co on nt ta ai in ne er r&) ; / / ... }; t te em mp pl la at te e c cl la as ss s M My y_ _a ar rr ra ay y { /* ... */ }; M Mc co on nt ta ai in ne er r< d do ou ub bl le e,M My y_ _a ar rr ra ay y > m mc c; A class generated from a class template is a perfectly ordinary class. Consequently, it can have f fr ri ie en nd d functions (§C.13.2). In this case, I used f fr ri ie en nd ds to achieve the conventional symmetric argu- ment style for == and != (§11.3.2). One might also consider passing a template rather than a con- tainer as the C C argument in such cases (§13.2.3). 13.6.1 Parameterization and Inheritance [temp.inherit] A template parameterizes the definition of a type or a function with another type. Code implement- ing the template is identical for all parameter types, as is most code using the template. An abstract class defines an interface. Much code for different implementations of the abstract class can be shared in class hierarchies, and most code using the abstract class doesn’t depend on its implemen- tation. From a design perspective, the two approaches are so close that they deserve a common name. Since both allow an algorithm to be expressed once and applied to a variety of types, people sometimes refer to both as p po ol ly ym mo or rp ph hi ic c. To distinguish them, what virtual functions provide is called run-time polymorphism, and what templates offer is called compile-time polymorphism or parametric polymorphism. So when do we choose to use a template and when do we rely on an abstract class? In either case, we manipulate objects that share a common set of operations. If no hierarchical relationship is required between these objects, they are best used as template arguments. If the actual types of these objects cannot be known at compile-time, they are best represented as classes derived from a common abstract class. If run-time efficiency is at a premium, that is, if inlining of operations is essential, a template should be used. This issue is discussed in greater detail in §24.4.1. 13.6.2 Member Templates [temp.member] A class or a class template can have members that are themselves templates. For example: t te em mp pl la at te e c cl la as ss s c co om mp pl le ex x { S Sc ca al la ar r r re e, i im m; p pu ub bl li ic c: t te em mp pl la at te e c co om mp pl le ex x(c co on ns st t c co om mp pl le ex x& c c) : r re e(c c.r re e) , i im m(c c.i im m) { } / / ... }; c co om mp pl le ex x c cf f(0 0,0 0) ; c co om mp pl le ex x c cd d = c cf f; / / ok: uses float to double conversion The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.348 Templates Chapter 13 c cl la as ss s Q Qu ua ad d { / / no conversion to int }; c co om mp pl le ex x c cq q; c co om mp pl le ex x c ci i = c cq q; / / error: no Quad to int conversion In other words, you can construct a c co om mp pl le ex x from a c co om mp pl le ex x if and only if you can ini- tialize a T T1 1 by a T T2 2. That seems reasonable. Unfortunately, C++ accepts some unreasonable conversions between built-in types, such as from d do ou ub bl le e to i in nt t. Truncation problems could be caught at run time using a checked conversion in the style of i im mp pl li ic ci it t_ _c ca as st t (§13.3.1) and c ch he ec ck ke ed d (§C.6.2.6): t te em mp pl la at te e c cl la as ss s c co om mp pl le ex x { S Sc ca al la ar r r re e, i im m; p pu ub bl li ic c: c co om mp pl le ex x() : r re e(0 0) , i im m(0 0) { } c co om mp pl le ex x(c co on ns st t c co om mp pl le ex x& c c) : r re e(c c.r re e) , i im m(c c.i im m) { } t te em mp pl la at te e c co om mp pl le ex x(c co on ns st t c co om mp pl le ex x& c c) : r re e(c ch he ec ck ke ed d_ _c ca as st t(c c.r re ea al l())) , i im m(c ch he ec ck ke ed d_ _c ca as st t(c c.i im ma ag g())) { } / / ... }; For completeness, I added a default constructor and a copy constructor. Curiously enough, a tem- plate constructor is never used to generate a copy constructor, so without the explicitly declared copy constructor, a default copy constructor would have been generated. In that case, that gener- ated copy constructor would have been identical to the one I explicitly specified. A member template cannot be v vi ir rt tu ua al l. For example: c cl la as ss s S Sh ha ap pe e { / / ... t te em mp pl la at te e v vi ir rt tu ua al l b bo oo ol l i in nt te er rs se ec ct t(c co on ns st t T T&) c co on ns st t =0 0; / / error: virtual template }; This must be illegal. If it were allowed, the traditional virtual function table technique for imple- menting virtual functions (§2.5.5) could not be used. The linker would have to add a new entry to the virtual table for class S Sh ha ap pe e each time someone called i in nt te er rs se ec ct t() with a new argument type. 13.6.3 Inheritance Relationships [temp.rel.inheritance] A class template is usefully understood as a specification of how particular types are to be created. In other words, the template implementation is a mechanism that generates types when needed based on the user’s specification. Consequently, a class template is sometimes called a type generator. As far as the C++ language rules are concerned, there is no relationship between two classes generated from a single class template. For example: c cl la as ss s S Sh ha ap pe e { /* ... */ }; c cl la as ss s C Ci ir rc cl le e : p pu ub bl li ic c S Sh ha ap pe e { /* ... */ }; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 13.6.3 Inheritance Relationships 349 Given these declarations, people sometimes try to treat a s se et t as a s se et t. This is a serious logical error based on a flawed argument: ‘‘A C Ci ir rc cl le e is a S Sh ha ap pe e, so a set of C Ci ir rc cl le es s is also a set of S Sh ha ap pe es s; therefore, I should be able to use a set of C Ci ir rc cl le es s as a set of S Sh ha ap pe es s.’’ The ‘‘there- fore’’ part of this argument doesn’t hold. The reason is that a set of C Ci ir rc cl le es guarantees that the member of the set are C Ci ir rc cl le es s; a set of S Sh ha ap pe es does not provide that guarantee. For example: c cl la as ss s T Tr ri ia an ng gl le e : p pu ub bl li ic c S Sh ha ap pe e { /* ... */ }; v vo oi id d f f(s se et t& s s) { / / ... s s.i in ns se er rt t(n ne ew w T Tr ri ia an ng gl le e()) ; / / ... } v vo oi id d g g(s se et t& s s) { f f(s s) ; / / error, type mismatch: s is a set, not a set } This won’t compile because there is no built-in conversion from s se et t& to s se et t&. Nor should there be. The guarantee that the members of a s se et t are C Ci ir rc cl le es allows us to safely and efficiently apply C Ci ir rc cl le e-specific operations, such as determining the radius, to members of the set. If we allowed a s se et t to be treated as a s se et t, we could no longer main- tain that guarantee. For example, f f() inserts a T Tr ri ia an ng gl le e* into its s se et t argument. If the s se et t could have been a s se et t, the fundamental guarantee that a s se et t contains C Ci ir rc cl le e*s only would have been violated. 13.6.3.1 Template Conversions [temp.mem.temp] The example in the previous section demonstrates that there cannot be any default relationship between classes generated from the same templates. However, for some templates we would like to express such a relationship. For example, when we define a pointer template, we would like to reflect inheritance relationships among the objects pointed to. Member templates (§13.6.2) allow us to specify many such relationships where desired. Consider: t te em mp pl la at te e c cl la as ss s P Pt tr r { / / pointer to T T T* p p; p pu ub bl li ic c: P Pt tr r(T T*) ; t te em mp pl la at te e o op pe er ra at to or r P Pt tr r () ; / / convert Ptr to Ptr / / ... }; We would like to define the conversion operators to provide the inheritance relationships we are accustomed to for built-in pointers for these user-defined P Pt tr rs. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.350 Templates Chapter 13 v vo oi id d f f(P Pt tr r p pc c) { P Pt tr r p ps s = p pc c; / / should work P Pt tr r p pc c2 2 = p ps s; / / should give error } We want to allow the first initialization if and only if S Sh ha ap pe e really is a direct or indirect public base class of C Ci ir rc cl le e. In general, we need to define the conversion operator so that the P Pt tr r to P Pt tr r conversion is accepted if and only if a T T* can be assigned to a T T2 2*. That can be done like this: t te em mp pl la at te e t te em mp pl la at te e P Pt tr r: :o op pe er ra at to or r P Pt tr r () { r re et tu ur rn n P Pt tr r(p p) ; } The return statement will compile if and only if p p (which is a T T*) can be an argument to the P Pt tr r(T T2 2*) constructor. Therefore, if T T* can be implicitly converted into a T T2 2*, the P Pt tr r to P Pt tr r conversion will work. For example v vo oi id d f f(P Pt tr r p pc c) { P Pt tr r p ps s = p pc c; / / ok: can convert Circle* to Shape* P Pt tr r p pc c2 2 = p ps s; / / error: cannot convert Shape* to Circle* } Be careful to define logically meaningful conversions only. Note that the template parameter lists of a template and its template member cannot be com- bined. For example: t te em mp pl la at te e / / error P Pt tr r: :o op pe er ra at to or r P Pt tr r () { r re et tu ur rn n P Pt tr r(p p) ; } 13.7 Source Code Organization [temp.source] There are two obvious ways of organizing code using templates: [1] Include template definitions before their use in a translation unit. [2] Include template declarations (only) before their use in a translation unit, and compile their definitions separately. In addition, template functions are sometimes first declared, then used, and finally defined in a sin- gle translation unit. To see the differences between the two main approaches, consider a simple template: #i in nc cl lu ud de e t te em mp pl la at te e v vo oi id d o ou ut t(c co on ns st t T T& t t) { s st td d: :c ce er rr r << t t; } We could call this o ou ut t.c c and #i in nc cl lu ud de e it wherever o ou ut t() was needed. For example: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 13.7 Source Code Organization 351 / / user1.c: #i in nc cl lu ud de e "o ou ut t.c c" / / use out() / / user2.c: #i in nc cl lu ud de e "o ou ut t.c c" / / use out() That is, the definition of o ou ut t() and all declarations it depends on are #i in nc cl lu ud de ed in several different compilation units. It is up to the compiler to generate code when needed (only) and to optimize the process of reading redundant definitions. This strategy treats template functions the same way as inline functions. One obvious problem with this is that everything on which the definition of o ou ut t() depends is added to each file using o ou ut t(), thus increasing the amount of information that the compiler must process. Another problem is that users may accidentally come to depend on declarations included only for the benefit of the definition of o ou ut t(). This danger can be minimized by using name- spaces, by avoiding macros, and generally by reducing the amount of information included. The separate compilation strategy is the logical conclusion of this line of thinking: if the tem- plate definition isn’t included in the user code, none of its dependencies can affect that code. Thus we split the original o ou ut t.c c into two files: / / out.h: t te em mp pl la at te e v vo oi id d o ou ut t(c co on ns st t T T& t t) ; / / out.c: #i in nc cl lu ud de e #i in nc cl lu ud de e "o ou ut t.h h" e ex xp po or rt t t te em mp pl la at te e v vo oi id d o ou ut t(c co on ns st t T T& t t) { s st td d: :c ce er rr r << t t; } The file o ou ut t.c c now holds all of the information needed to define o ou ut t(), and o ou ut t.h h holds only what is needed to call it. A user #i in nc cl lu ud de es only the declaration (the interface): / / user1.c: #i in nc cl lu ud de e "o ou ut t.h h" / / use out() / / user2.c: #i in nc cl lu ud de e "o ou ut t.h h" / / use out() This strategy treats template functions the same way it does non-inline functions. The definition (in o ou ut t.c c) is compiled separately, and it is up to the implementation to find the definition of o ou ut t() when needed. This strategy also puts a burden on the implementation. Instead of having to filter out redundant copies of a template definition, the implementation must find the unique definition when needed. Note that to be accessible from other compilation units, a template definition must be explicitly declared e ex xp po or rt t (§9.2.3). This can be done by adding e ex xp po or rt t to the definition or to a preceding declaration. Otherwise, the definition must be in scope wherever the template is used. Which strategy or combination of strategies is best depends on the compilation and linkage The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.352 Templates Chapter 13 system used, the kind of application you are building, and the external constraints on the way you build systems. Generally, inline functions and other small functions that primarily call other tem- plate functions are candidates for inclusion into every compilation unit in which they are used. On an implementation with average support from the linker for template instantiation, doing this can speed up compilation and improve error messages. Including a definition makes it vulnerable to having its meaning affected by macros and decla- rations in the context into which it is included. Consequently, larger template functions and tem- plate functions with nontrivial context dependencies are better compiled separately. Also, if the definition of a template requires a large number of declarations, these declarations can have unde- sirable side effects if they are included into the context in which the template is used. I consider the approach of separately compiling template definitions and including declarations only in user code ideal. However, the application of ideals must be tempered by practical con- straints, and separate compilation of templates is expensive on some implementations. Whichever strategy is used, non-i in nl li in ne e s st ta at ti ic c members (§C.13.1) must have a unique definition in some compilation unit. This implies that such members are best not used for templates that are otherwise included in many translation units. One ideal is for code to work the same whether it is compiled as a single unit or separated into several separately translated units. That ideal should be approached by restricting a template definition’s dependency on its environment rather than by trying to carry as much as possible of its definition context with it into the instantiation process. 13.8 Advice [temp.advice] [1] Use templates to express algorithms that apply to many argument types; §13.3. [2] Use templates to express containers; §13.2. [3] Provide specializations for containers of pointers to minimize code size; §13.5. [4] Always declare the general form of a template before specializations; §13.5. [5] Declare a specialization before its use; §13.5. [6] Minimize a template definition’s dependence on its instantiation contexts; §13.2.5, §C.13.8. [7] Define every specialization you declare; §13.5. [8] Consider if a template needs specializations for C-style strings and arrays; §13.5.2. [9] Parameterize with a policy object; §13.4. [10] Use specialization and overloading to provide a single interface to implementations of the same concept for different types; §13.5. [11] Provide a simple interface for simple cases and use overloading and default arguments to express less common cases; §13.5, §13.4. [12] Debug concrete examples before generalizing to a template; §13.2.1. [13] Remember to e ex xp po or rt t template definitions that need to be accessible from other translation units; §13.7. [14] Separately compile large templates and templates with nontrivial context dependencies; §13.7. [15] Use templates to express conversions but define those conversions very carefully; §13.6.3.1. [16] Where necessary, constrain template arguments using a c co on ns st tr ra ai in nt t() member function; §13.9[16]. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 13.8 Advice 353 [17] Use explicit instantiation to minimize compile time and link time; §C.13.10. [18] Prefer a template over derived classes when run-time efficiency is at a premium; §13.6.1. [19] Prefer derived classes over a template if adding new variants without recompilation is impor- tant; §13.6.1. [20] Prefer a template over derived classes when no common base can be defined; §13.6.1. [21] Prefer a template over derived classes when built-in types and structures with compatibility constraints are important; §13.6.1. 13.9 Exercises [temp.exercises] 1. (∗2) Fix the errors in the definition of L Li is st t from §13.2.5 and write out C++ code equivalent to what the compiler must generate for the definition of L Li is st t and the function f f(). Run a small test case using your hand-generated code and the code generated by the compiler from the tem- plate version. If possible on your system given your knowledge, compare the generated code. 2. (∗3) Write a singly-linked list class template that accepts elements of any type derived from a class L Li in nk k that holds the information necessary to link elements. This is called an intrusive list. Using this list, write a singly-linked list that accepts elements of any type (a non-intrusive list). Compare the performance of the two list classes and discuss the tradeoffs between them. 3. (∗2.5) Write intrusive and non-intrusive doubly-linked lists. What operations should be pro- vided in addition to the ones you found necessary to supply for a singly-linked list? 4. (∗2) Complete the S St tr ri in ng g template from §13.2 based on the S St tr ri in ng g class from §11.12. 5. (∗2) Define a s so or rt t() that takes its comparison criterion as a template argument. Define a class R Re ec co or rd d with two data members c co ou un nt t and p pr ri ic ce e. Sort a v ve ec ct to or r on each data member. 6. (∗2) Implement a q qs so or rt t() template. 7. (∗2) Write a program that reads (k ke ey y,v va al lu ue e) pairs and prints out the sum of the v va al lu ue es corre- sponding to each distinct k ke ey y. Specify what is required for a type to be a k ke ey y and a v va al lu ue e. 8. (∗2.5) Implement a simple M Ma ap p class based on the A As ss so oc c class from §11.8. Make sure M Ma ap p works correctly using both C-style strings and s st tr ri in ng gs as keys. Make sure M Ma ap p works correctly for types with and without default constructors. Provide a way of iterating over the elements of a M Ma ap p. 9. (∗3) Compare the performance of the word count program from §11.8 against a program not using an associative array. Use the same style of I/O in both cases. 10. (∗3) Re-implement M Ma ap p from §13.9[8] using a more suitable data structure (e.g., a red-black tree or a Splay tree). 11. (∗2.5) Use M Ma ap p to implement a topological sort function. Topological sort is described in [Knuth,1968] vol. 1 (second edition), pg 262. 12. (∗1.5) Make the sum program from §13.9[7] work correctly for names containing spaces; for example, ‘‘thumb tack.’’ 13. (∗2) Write r re ea ad dl li in ne e() templates for different kinds of lines. For example (item,count,price). 14. (∗2) Use the technique outlined for L Li it te er ra at te e in §13.4 to sort strings in reverse lexicographical order. Make sure the technique works both for C++ implementations where c ch ha ar r is s si ig gn ne ed d and for C++ implementations where it is u un ns si ig gn ne ed d. Use a variant of that technique to provide a sort that is not case-sensitive. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.354 Templates Chapter 13 15. (∗1.5) Construct an example that demonstrates at least three differences between a function tem- plate and a macro (not counting the differences in definition syntax). 16. (∗2) Devise a scheme that ensures that the compiler tests general constraints on the template arguments for every template for which an object is constructed. It is not sufficient just to test constraints of the form ‘‘the argument T T must be a class derived from M My y_ _b ba as se e.’’ The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved._ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ 14 _ _______________________________________________________________________________________________________________________________________________________________ _ _______________________________________ Exception Handling Don´t interrupt me while I´m interrupting. ± Winston S. Churchill Error handling Ð grouping of exceptions Ð catching exceptions Ð catch all Ð re- throw Ð resource management Ð a au ut to o_ _p pt tr r Ð exceptions and n ne ew w Ð resource exhaus- tion Ð exceptions in constructors Ð exceptions in destructors Ð exceptions that are not errors Ð exception specifications Ð unexpected exceptions Ð uncaught exceptions Ð exceptions and efficiency Ð error-handling alternatives Ð standard exceptions Ð advice Ð exercises. 14.1 Error Handling [except.error] As pointed out in §8.3, the author of a library can detect run-time errors but does not in general have any idea what to do about them. The user of a library may know how to cope with such errors but cannot detect them ± or else they would have been handled in the user’s code and not left for the library to find. The notion of an exception is provided to help deal with such problems. The fundamental idea is that a function that finds a problem it cannot cope with throws an exception, hoping that its (direct or indirect) caller can handle the problem. A function that wants to handle that kind of problem can indicate that it is willing to catch that exception (§2.4.2, §8.3). This style of error handling compares favorably with more traditional techniques. Consider the alternatives. Upon detecting a problem that cannot be handled locally, the program could: [1] terminate the program, [2] return a value representing ‘‘error,’’ [3] return a legal value and leave the program in an illegal state, or [4] call a function supplied to be called in case of ‘‘error.’’ The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.356 Exception Handling Chapter 14 Case [1], ‘‘terminate the program,’’ is what happens by default when an exception isn’t caught. For most errors, we can and must do better. In particular, a library that doesn’t know about the pur- pose and general strategy of the program in which it is embedded cannot simply e ex xi it t() or a ab bo or rt t(). A library that unconditionally terminates cannot be used in a program that cannot afford to crash. One way of viewing exceptions is as a way of giving control to a caller when no meaning- ful action can be taken locally. Case [2], ‘‘return an error value,’’ isn’t always feasible because there is often no acceptable ‘‘error value.’’ For example, if a function returns an i in nt t, every i in nt t might be a plausible result. Even where this approach is feasible, it is often inconvenient because every call must be checked for the error value. This can easily double the size of a program (§14.8). Consequently, this approach is rarely used systematically enough to detect all errors. Case [3], ‘‘return a legal value and leave the program in an illegal state,’’ has the problem that the calling function may not notice that the program has been put in an illegal state. For example, many standard C library functions set the global variable e er rr rn no o to indicate an error (§20.4.1, §22.3). However, programs typically fail to test e er rr rn no o consistently enough to avoid consequential errors caused by values returned from failed calls. Furthermore, the use of global variables for recording error conditions doesn’t work well in the presence of concurrency. Exception handling is not meant to handle problems for which case [4], ‘‘call an error-handler function,’’ is relevant. However, in the absence of exceptions, an error-handler function has exactly the three other cases as alternatives for how it handles the error. For a further discussion of error-handling functions and exceptions, see §14.4.5. The exception-handling mechanism provides an alternative to the traditional techniques when they are insufficient, inelegant, and error-prone. It provides a way of explicitly separating error- handling code from ‘‘ordinary’’ code, thus making the program more readable and more amenable to tools. The exception-handling mechanism provides a more regular style of error handling, thus simplifying cooperation between separately written program fragments. One aspect of the exception-handling scheme that will appear novel to C and Pascal program- mers is that the default response to an error (especially to an error in a library) is to terminate the program. The traditional response has been to muddle through and hope for the best. Thus, excep- tion handling makes programs more ‘‘brittle’’ in the sense that more care and effort must be taken to get a program to run acceptably. This seems preferable, though, to getting wrong results later in the development process ± or after the development process is considered complete and the pro- gram is handed over to innocent users. Where termination is unacceptable, we can catch all excep- tions (§14.3.2) or catch all exceptions of a specific kind (§14.6.2). Thus, an exception terminates a program only if a programmer allows it to terminate. This is preferable to the unconditional termi- nation that happens when a traditional incomplete recovery leads to a catastrophic error. Sometimes people have tried to alleviate the unattractive aspects of ‘‘muddling through’’ by writing out error messages, putting up dialog boxes asking the user for help, etc. Such approaches are primarily useful in debugging situations in which the user is a programmer familiar with the structure of the program. In the hands of nondevelopers, a library that asks the (possibly absent) user/operator for help is unacceptable. Also, in many cases error messages have no place to go (say, if the program runs in an environment in which c ce er rr r doesn’t connect to anything a user notices); they would be incomprehensible to an end user anyway. At a minimum, the error mes- sage might be in the wrong natural language (say, in Finnish to a English user). Worse, the error The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 14.1 Error Handling 357 message would typically refer to library concepts completely unknown to a user (say, ‘‘bad argu- ment to atan2,’’ caused by bad input to a graphics system). A good library doesn’t ‘‘blabber’’ in this way. Exceptions provide a way for code that detects a problem from which it cannot recover to pass the problem on to some part of the system that might be able to recover. Only a part of the system that has some idea of the context in which the program runs has any chance of composing a meaningful error message. The exception-handling mechanism can be seen as a run-time analog to the compile-time type checking and ambiguity control mechanisms. It makes the design process more important and can increase the work needed to get an initial and buggy version of a program running. However, the result is code that has a much better chance to run as expected, to run as an acceptable part of a larger program, to be comprehensible to other programmers, and to be amenable to manipulation by tools. Similarly, exception handling provides specific language features to support ‘‘good style’’ in the same way other C++ features support ‘‘good style’’ that can be practiced only informally and incompletely in languages such as C and Pascal. It should be recognized that error handling will remain a difficult task and that the exception- handling mechanism ± although more formalized than the techniques it replaces ± is still relatively unstructured compared with language features involving only local control flow. The C++ exception-handling mechanism provides the programmer with a way of handling errors where they are most naturally handled, given the structure of a system. Exceptions make the complexity of error handling visible. However, exceptions are not the cause of that complexity. Be careful not to blame the messenger for bad news. This may be a good time to review §8.3, where the basic syntax, semantics, and style-of-use aspects of exception handling are presented. 14.1.1 Alternative Views on Exceptions [except.views] ‘‘Exception’’ is one of those words that means different things to different people. The C++ exception-handling mechanism is designed to support handling of errors and other exceptional con- ditions (hence the name). In particular, it is intended to support error handling in programs com- posed of independently developed components. The mechanism is designed to handle only synchronous exceptions, such as array range checks and I/O errors. Asynchronous events, such as keyboard interrupts and certain arithmetic errors, are not necessarily exceptional and are not handled directly by this mechanism. Asynchronous events require mechanisms fundamentally different from exceptions (as defined here) to handle them cleanly and efficiently. Many systems offer mechanisms, such as signals, to deal with asynchrony, but because these tend to be system-dependent, they are not described here. The exception-handling mechanism is a nonlocal control structure based on stack unwinding (§14.4) that can be seen as an alternative return mechanism. There are therefore legitimate uses of exceptions that have nothing to do with errors (§14.5). However, the primary aim of the exception-handling mechanism and the focus of this chapter is error handling and the support of fault tolerance. Standard C++ doesn’t have the notion of a thread or a process. Consequently, exceptional cir- cumstances relating to concurrency are not discussed here. The concurrency facilities available on your system are described in its documentation. Here, I’ll just note that the C++ exception- The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.358 Exception Handling Chapter 14 handling mechanism was designed to be effective in a concurrent program as long as the program- mer (or system) enforces basic concurrency rules, such as properly locking a shared data structure while using it. The C++ exception-handling mechanisms are provided to report and handle errors and excep- tional events. However, the programmer must decide what it means to be exceptional in a given program. This is not always easy (§14.5). Can an event that happens most times a program is run be considered exceptional? Can an event that is planned for and handled be considered an error? The answer to both questions is yes. ‘‘Exceptional’’ does not mean ‘‘almost never happens’’ or ‘‘disastrous.’’ It is better to think of an exception as meaning ‘‘some part of the system couldn’t do what it was asked to do.’’ Usually, we can then try something else. Exception t th hr ro ow ws should be infrequent compared to function calls or the structure of the system has been obscured. However, we should expect most large programs to t th hr ro ow w and c ca at tc ch h at least some exceptions in the course of a normal and successful run. 14.2 Grouping of Exceptions [except.grouping] An exception is an object of some class representing an exceptional occurrence. Code that detects an error (often a library) t th hr ro ow ws an object (§8.3). A piece of code expresses desire to handle an exception by a c ca at tc ch h clause. The effect of a t th hr ro ow w is to unwind the stack until a suitable c ca at tc ch h is found (in a function that directly or indirectly invoked the function that threw the exception). Often, exceptions fall naturally into families. This implies that inheritance can be useful to structure exceptions and to help exception handling. For example, the exceptions for a mathemati- cal library might be organized like this: c cl la as ss s M Ma at th he er rr r { }; c cl la as ss s O Ov ve er rf fl lo ow w: p pu ub bl li ic c M Ma at th he er rr r { }; c cl la as ss s U Un nd de er rf fl lo ow w: p pu ub bl li ic c M Ma at th he er rr r { }; c cl la as ss s Z Ze er ro od di iv vi id de e: p pu ub bl li ic c M Ma at th he er rr r { }; / / ... This allows us to handle any M Ma at th he er rr r without caring precisely which kind it is. For example: v vo oi id d f f() { t tr ry y { / / ... } c ca at tc ch h (O Ov ve er rf fl lo ow w) { / / handle Overflow or anything derived from Overflow } c ca at tc ch h (M Ma at th he er rr r) { / / handle any Matherr that is not Overflow } } Here, an O Ov ve er rf fl lo ow w is handled specifically. All other M Ma at th he er rr r exceptions will be handled by the general case. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 14.2 Grouping of Exceptions 359 Organizing exceptions into hierarchies can be important for robustness of code. For example, consider how you would handle all exceptions from a library of mathematical functions without such a grouping mechanism. This would have to be done by exhaustively listing the exceptions: v vo oi id d g g() { t tr ry y { / / ... } c ca at tc ch h (O Ov ve er rf fl lo ow w) { /* ... */ } c ca at tc ch h (U Un nd de er rf fl lo ow w) { /* ... */ } c ca at tc ch h (Z Ze er ro od di iv vi id de e) { /* ... */ } } This is not only tedious, but a programmer can easily forget to add an exception to the list. Con- sider what would be needed if we didn’t group math exceptions. When we added a new exception to the math library, every piece of code that tried to handle every math exception would have to be modified. In general, such universal update is not feasible after the initial release of the library. Often, there is no way of finding every relevant piece of code. Even when there is, we cannot in general assume that every piece of source code is available or that we would be willing to make changes if it were. These recompilation and maintenance problems would lead to a policy that no new exceptions can be added to a library after its first release; that would be unacceptable for almost all libraries. This reasoning leads exceptions to be defined as per-library or per-subsystem class hierarchies (§14.6.2). Please note that neither the built-in mathematical operations nor the basic math library (shared with C) reports arithmetic errors as exceptions. One reason for this is that detection of some arith- metic errors, such as divide-by-zero, are asynchronous on many pipelined machine architectures. The M Ma at th he er rr r hierarchy described here is only an illustration. The standard library exceptions are described in §14.10. 14.2.1 Derived Exceptions [except.derived] The use of class hierarchies for exception handling naturally leads to handlers that are interested only in a subset of the information carried by exceptions. In other words, an exception is typically caught by a handler for its base class rather than by a handler for its exact class. The semantics for catching and naming an exception are identical to those of a function accepting an argument. That is, the formal argument is initialized with the argument value (§7.2). This implies that the excep- tion thrown is ‘‘sliced’’ to the exception caught (§12.2.3). For example: c cl la as ss s M Ma at th he er rr r { / / ... v vi ir rt tu ua al l v vo oi id d d de eb bu ug g_ _p pr ri in nt t() c co on ns st t { c ce er rr r << "M Ma at th h e er rr ro or r"; } }; c cl la as ss s I In nt t_ _o ov ve er rf fl lo ow w: p pu ub bl li ic c M Ma at th he er rr r { c co on ns st t c ch ha ar r* o op p; i in nt t a a1 1, a a2 2; The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.360 Exception Handling Chapter 14 p pu ub bl li ic c: I In nt t_ _o ov ve er rf fl lo ow w(c co on ns st t c ch ha ar r* p p, i in nt t a a, i in nt t b b) { o op p = p p; a a1 1 = a a; a a2 2 = b b; } v vi ir rt tu ua al l v vo oi id d d de eb bu ug g_ _p pr ri in nt t() c co on ns st t { c ce er rr r << o op p << ´(´ << a a1 1 << ´,´ << a a2 2 << ´)´; } / / ... }; v vo oi id d f f() { t tr ry y { g g() ; } c ca at tc ch h (M Ma at th he er rr r m m) { / / ... } } When the M Ma at th he er rr r handler is entered, m m is a M Ma at th he er rr r object ± even if the call to g g() threw I In nt t_ _o ov ve er rf fl lo ow w. This implies that the extra information found in an I In nt t_ _o ov ve er rf fl lo ow w is inaccessible. As always, pointers or references can be used to avoid losing information permanently. For example, we might write: i in nt t a ad dd d(i in nt t x x, i in nt t y y) { i if f ((x x>0 0 && y y>0 0 && x x>I IN NT T_ _M MA AX X-y y) || (x x<0 0 && y y<0 0 && x x p p; v vo oi id d i in ni it t() ; p pu ub bl li ic c: Z Z(i in nt t s s) : p p(s s) { i in ni it t() ; } / / ... }; The memory used by p p is now managed by v ve ec ct to or r. If i in ni it t() throws an exception, the memory acquired will be freed when the destructor for p p is (implicitly) invoked. 14.4.2 Auto_ptr [except.autoptr] The standard library provides the template class a au ut to o_ _p pt tr r, which supports the ‘‘resource acquisition is initialization’’ technique. Basically, an a au ut to o_ _p pt tr r is initialized by a pointer and can be derefer- enced in the way that a pointer can. Also, the object pointed to will be implicitly deleted at the end of the a au ut to o_ _p pt tr r’s scope. For example: v vo oi id d f f(P Po oi in nt t p p1 1, P Po oi in nt t p p2 2, a au ut to o_ _p pt tr r p pc c, S Sh ha ap pe e* p pb b) / / remember to delete pb on exit { a au ut to o_ _p pt tr r p p(n ne ew w R Re ec ct ta an ng gl le e(p p1 1,p p2 2)) ; / / p points to a rectangle a au ut to o_ _p pt tr r p pb bo ox x(p pb b) ; p p->r ro ot ta at te e(4 45 5) ; / / use auto_ptr exactly as a Shape* / / ... i if f (i in n_ _a a_ _m me es ss s) t th hr ro ow w M Me es ss s() ; / / ... } Here the R Re ec ct ta an ng gl le e, the S Sh ha ap pe e pointed to by p pb b, and the C Ci ir rc cl le e pointed to by p pc c are deleted whether or not an exception is thrown. To achieve this ownership semantics (also called destructive copy semantics), a au ut to o_ _p pt tr rs have a copy semantics that differs radically from that of ordinary pointers: When one a au ut to o_ _p pt tr r is copied into another, the source no longer points to anything. Because copying an a au ut to o_ _p pt tr r modifies it, a c co on ns st t a au ut to o_ _p pt tr r cannot be copied. The a au ut to o_ _p pt tr r template is declared in . It can be described by an implementation: The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.368 Exception Handling Chapter 14 t te em mp pl la at te e c cl la as ss s s st td d: :a au ut to o_ _p pt tr r { t te em mp pl la at te e s st tr ru uc ct t a au ut to o_ _p pt tr r_ _r re ef f { /* ... */ }; / / helper class X X* p pt tr r; p pu ub bl li ic c: t ty yp pe ed de ef f X X e el le em me en nt t_ _t ty yp pe e; e ex xp pl li ic ci it t a au ut to o_ _p pt tr r(X X* p p =0 0) t th hr ro ow w() { p pt tr r=0 0; } a au ut to o_ _p pt tr r(a au ut to o_ _p pt tr r& a a) t th hr ro ow w() { p pt tr r=a a.p pt tr r; a a.p pt tr r=0 0; } / / note: not const auto_ptr& t te em mp pl la at te e a au ut to o_ _p pt tr r(a au ut to o_ _p pt tr r& a a) t th hr ro ow w() { p pt tr r=a a.p pt tr r; a a.p pt tr r=0 0; } a au ut to o_ _p pt tr r& o op pe er ra at to or r=(a au ut to o_ _p pt tr r& a a) t th hr ro ow w() { p pt tr r=a a.p pt tr r; a a.p pt tr r=0 0; } t te em mp pl la at te e a au ut to o_ _p pt tr r& o op pe er ra at to or r=(a au ut to o_ _p pt tr r& a a) t th hr ro ow w() { p pt tr r=a a.p pt tr r; a a.p pt tr r=0 0; } ~a au ut to o_ _p pt tr r() t th hr ro ow w() { d de el le et te e p pt tr r; } X X& o op pe er ra at to or r*() c co on ns st t t th hr ro ow w() { r re et tu ur rn n *p pt tr r; } X X* o op pe er ra at to or r->() c co on ns st t t th hr ro ow w() { r re et tu ur rn n p pt tr r; } X X* g ge et t() c co on ns st t t th hr ro ow w() { r re et tu ur rn n p pt tr r; } / / extract pointer X X* r re el le ea as se e() t th hr ro ow w() { X X* t t = p pt tr r; p pt tr r=0 0; r re et tu ur rn n t t; } / / relinquish ownership v vo oi id d r re es se et t(X X* p p =0 0) t th hr ro ow w() { i if f (p p!=p pt tr r) { d de el le et te e p pt tr r; p pt tr r=p p; } } a au ut to o_ _p pt tr r(a au ut to o_ _p pt tr r_ _r re ef f) t th hr ro ow w() ; / / copy from auto_ptr_ref t te em mp pl la at te e o op pe er ra at to or r a au ut to o_ _p pt tr r_ _r re ef f() t th hr ro ow w() ; / / copy from auto_ptr_ref t te em mp pl la at te e o op pe er ra at to or r a au ut to o_ _p pt tr r() t th hr ro ow w() ; / / destructive copy from auto_ptr }; The purpose of a au ut to o_ _p pt tr r_ _r re ef f is to implement the destructive copy semantics for ordinary a au ut to o_ _p pt tr rs while making it impossible to copy a c co on ns st t a au ut to o_ _p pt tr r. The template constructor and template assignment ensures that an a au ut to o_ _p pt tr r can be implicitly converted to a a au ut to o_ _p pt tr r if a D D* can be converted to a B B*. For example: v vo oi id d g g(C Ci ir rc cl le e* p pc c) { a au ut to o_ _p pt tr r p p2 2 = p pc c; / / now p2 is responsible for deletion a au ut to o_ _p pt tr r p p3 3 = p p2 2; / / now p3 is responsible for deletion (and p2 isn’t) p p2 2->m m = 7 7; / / programmer error: p2.get()==0 S Sh ha ap pe e* p ps s = p p3 3.g ge et t() ; / / extract the pointer from an auto_ptr a au ut to o_ _p pt tr r a ap ps s = p p3 3; / / transfer of ownership and convert type a au ut to o_ _p pt tr r p p4 4 = p p; / / programmer error: now p4 is also responsible for deletion } The effect of having more than one a au ut to o_ _p pt tr r own an object is undefined; most likely the object will be deleted twice (with bad effects). Note that a au ut to o_ _p pt tr r’s destructive copy semantics means that it does not meet the requirements for elements of a standard container or for standard algorithms such as s so or rt t(). For example: v vo oi id d h h(v ve ec ct to or r< a au ut to o_ _p pt tr r >& v v) / / dangerous: use of auto_ptr in container { s so or rt t(v v.b be eg gi in n() ,v v.e en nd d()) ; / / Don’t do this: The sort will probably mess up v } Clearly, a au ut to o_ _p pt tr r isn’t a general smart pointer. However, it provides the service for which it was designed ± exception safety for automatic pointers ± with essentially no overhead. The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 14.4.3 Caveat 369 14.4.3 Caveat [except.caveat] Not all programs need to be resilient against all forms of failure, and not all resources are critical enough to warrant the effort to protect them using ‘‘resource acquisition is initialization,’’ a au ut to o_ _p pt tr r, and c ca at tc ch h(...). For example, for many programs that simply read an input and run to completion, the most suitable response to a serious run-time error is to abort the process (after pro- ducing a suitable diagnostic). That is, let the system release all acquired resources and let the user re-run the program with a more suitable input. The strategy discussed here is intended for applica- tions for which such a simplistic response to a run-time error is unacceptable. In particular, a library designer usually cannot make assumptions about the fault tolerance requirements of a pro- gram using the library and is thus forced to avoid all unconditional run-time failures and to release all resources before a library function returns to the calling program. The ‘‘resource acquisition is initialization’’ strategy, together with the use of exceptions to signal failure, is suitable for many such libraries. 14.4.4 Exceptions and New [except.new] Consider: v vo oi id d f f(A Ar re en na a& a a, X X* b bu uf ff fe er r) { X X* p p1 1 = n ne ew w X X; X X* p p2 2 = n ne ew w X X[1 10 0] ; X X* p p3 3 = n ne ew w(b bu uf ff fe er r[1 10 0]) X X; / / place X in buffer (no deallocation needed) X X* p p4 4 = n ne ew w(b bu uf ff fe er r[1 11 1]) X X[1 10 0] ; X X* p p5 5 = n ne ew w(a a) X X; / / allocation from Arena a (deallocate from a) X X* p p6 6 = n ne ew w(a a) X X[1 10 0] ; } What happens if X X´s s constructor throws an exception? Is the memory allocated by the o op pe er ra at to or r n ne ew w() freed? For the ordinary case, the answer is yes, so the initializations of p p1 1 and p p2 2 don’t cause memory leaks. When the placement syntax (§10.4.11) is used, the answer cannot be that simple. Some uses of that syntax allocate memory, which then ought to be released; however, some don’t. Furthermore, the point of using the placement syntax is to achieve nonstandard allocation, so nonstandard freeing is typically required. Consequently, the action taken depends on the allocator used. If an allocator Z Z: :o op pe er ra at to or r n ne ew w() is used, Z Z: :o op pe er ra at to or r d de el le et te e() is invoked if it exists; otherwise, no deallocation is attempted. Arrays are handled equivalently (§15.6.1). This strategy correctly han- dles the standard library placement n ne ew w operator (§10.4.11), as well as any case in which the pro- grammer has provided a matching pair of allocation and deallocation functions. 14.4.5 Resource Exhaustion [except.exhaust] A recurring programming problem is what to do when an attempt to acquire a resource fails. For example, previously we blithely opened files (using f fo op pe en n()) and requested memory from the free store (using operator n ne ew w) without worrying about what happened if the file wasn’t there or if we The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.370 Exception Handling Chapter 14 had run out of free store. When confronted with such problems, programmers come up with two styles of solutions: Resumption: Ask some caller to fix the problem and carry on. Termination: Abandon the computation and return to some caller. In the former case, a caller must be prepared to help out with resource acquisition problems in unknown pieces of code. In the latter, a caller must be prepared to cope with failure of the attempt to acquire the resource. The latter is in most cases far simpler and allows a system to maintain a better separation of levels of abstraction. Note that it is not the program that terminates when one uses the termination strategy; only an individual computation terminates. ‘‘Termination’’ is the tra- ditional term for a strategy that returns from a ‘‘failed’’ computation to an error handler associated with a caller (which may re-try the failed computation), rather than trying to repair a bad situation and resume from the point at which the problem was detected. In C++, the resumption model is supported by the function-call mechanism and the termination model is supported by the exception-handling mechanism. Both can be illustrated by a simple implementation and use of the standard library o op pe er ra at to or r n ne ew w(): v vo oi id d* o op pe er ra at to or r n ne ew w(s si iz ze e_ _t t s si iz ze e) { f fo or r (;;) { i if f (v vo oi id d* p p = m ma al ll lo oc c(s si iz ze e)) r re et tu ur rn n p p; / / try to find memory i if f (_ _n ne ew w_ _h ha an nd dl le er r == 0 0) t th hr ro ow w b ba ad d_ _a al ll lo oc c() ; / / no handler: give up _ _n ne ew w_ _h ha an nd dl le er r() ; / / ask for help } } Here, I use the standard C library m ma al ll lo oc c() to do the real search for memory; other implementa- tions of o op pe er ra at to or r n ne ew w() may choose other ways. If memory is found, o op pe er ra at to or r n ne ew w() can return a pointer to it. Otherwise, o op pe er ra at to or r n ne ew w() calls the _ _n ne ew w_ _h ha an nd dl le er r. If the _ _n ne ew w_ _h ha an nd dl le er r can find more memory for m ma al ll lo oc c() to allocate, all is fine. If it can’t, the handler cannot return to o op pe er ra at to or r n ne ew w() without causing an infinite loop. The _ _n ne ew w_ _h ha an nd dl le er r() might then choose to throw an exception, thus leaving the mess for some caller to handle: v vo oi id d m my y_ _n ne ew w_ _h ha an nd dl le er r() { i in nt t n no o_ _o of f_ _b by yt te es s_ _f fo ou un nd d = f fi in nd d_ _s so om me e_ _m me em mo or ry y() ; i if f (n no o_ _o of f_ _b by yt te es s_ _f fo ou un nd d < m mi in n_ _a al ll lo oc ca at ti io on n) t th hr ro ow w b ba ad d_ _a al ll lo oc c() ; / / give up } Somewhere, there ought to be a try_block with a suitable handler: t tr ry y { / / ... } c ca at tc ch h (b ba ad d_ _a al ll lo oc c) { / / somehow respond to memory exhaustion } The _ _n ne ew w_ _h ha an nd dl le er r used in the implementation of o op pe er ra at to or r n ne ew w() is a pointer to a function main- tained by the standard function s se et t_ _n ne ew w_ _h ha an nd dl le er r(). If I want m my y_ _n ne ew w_ _h ha an nd dl le er r() to be used as The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.Section 14.4.5 Resource Exhaustion 371 the _ _n ne ew w_ _h ha an nd dl le er r, I say: s se et t_ _n ne ew w_ _h ha an nd dl le er r(&m my y_ _n ne ew w_ _h ha an nd dl le er r) ; If I also want to catch b ba ad d_ _a al ll lo oc c, I might say: v vo oi id d f f() { v vo oi id d(*o ol ld dn nh h)() = s se et t_ _n ne ew w_ _h ha an nd dl le er r(&m my y_ _n ne ew w_ _h ha an nd dl le er r) ; t tr ry y { / / ... } c ca at tc ch h (b ba ad d_ _a al ll lo oc c) { / / ... } c ca at tc ch h (...) { s se et t_ _n ne ew w_ _h ha an n