Isbn unicode the unicode consortium the unicode standard
1.1 The Structure of This Book [notes.intro]
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.Appendices: Appendices A through C 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.
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.
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.
The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T.
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.
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.
1.1.2 Exercises [notes.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.
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++.
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.
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 compatibility with C; 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 activity in C++. A well-designed user-defined type differs from a built-in type only in the way it is
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++ 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++.
Efficiency and Structure |
|
---|
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.
1.3.2 Philosophical Note [notes.philosophy]
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.
1.4 Historical Note [notes.historical]
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].
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.
12 |
|
Chapter 1 |
---|
1.5 Use of C++ [notes.use]
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,
1.6 C and C++ [notes.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.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, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T.
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).
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 [notes.suggestions]
|
Thinking about Programming in C++ |
|
---|
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).
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, arrays, and associative arrays 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 inheri-tance. It is best done using templates.
[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.
[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 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.
The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T.
Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.
Advice |
---|
1.8.1 References [notes.ref]
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.
August 1992.
X3 Secretariat: Standard – The C Language. X3J11/90-013. ISO Standard [C,1990]
ISO/IEC 9899. Computer and Business Equipment Manufacturers Association.[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.
Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.
18 Notes to the Reader Chapter 1
[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.
Ygeesh H. Kamath, Ruth E. Smilan, and Jean G. Smith: Reaping Benefits with [Kamath,1993]
Object-Oriented Technology. AT&T Technical Journal. Vol. 72 No. 5.[Koenig,1997] Andrew Koenig and Barbara Moo: Ruminations on C++. Addison Wesley Longman. Reading, Mass. 1997. ISBN 1-201-42339-1.
[Knuth,1968] Donald Knuth: The Art of Computer Programming. Addison-Wesley. Read- ing, Mass.
[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.
Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.
Section 1.8.1 References 19
[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.
[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.
Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.