“Any clod can have the facts, but having opinions is an art.” Charles McCabe, San Francisco Chronicle

directly matches a sound design. How- ever, now is the time to experiment and The Real see which techniques will suit particular people, organizations, and projects. Much of The ++ Programming Language is devoted to these techniques Open Channel Stroustrup and the trade-offs they represent. The most visible aspects of what makes this progress feasible are the “new” major language facilities—tem- Interview plates, exceptions, runtime type infor- mation, and namespaces—and the new standard library. The minor improve- ments to language details are also impor- tant. We have had most of the facilities In Design and Evolution of C++ (Addi- available for years now, but haven’t been son Wesley, 1994), Bjarne Stroustrup able to rely on them where we needed argued that “a programming language portability and production quality. This is really a very tiny part of the world, has forced us to take suboptimal and as such, it ought not be taken too approaches to design and implementa- seriously. Keep a sense of proportion tion of our libraries and applications. and most importantly keep a sense of However, soon (this year) all major humor. Among major programming implementations will provide solid sup- languages, C++ is the richest source of port for Standard C++. puns and jokes. That is no accident.” From a language and programming- For the past few months, a hoax techniques perspective, the most signifi- interview between Stroustrup and cant change to C++ is the continuing Computer has been making the rounds The father of C++ increase in emphasis on statically verifi- in cyberspace. While we regret the inci- able type safety and the increased flexi- dent, it offers us a welcome oppor- explains why Standard bility of templates. Flexible templates are tunity to have the father of C++ share C++ isn’t just an object- necessary to make the emphasis on type his insights on Standard C++ and soft- oriented language. safety pay off in terms of elegance and ware development in general. We can efficiency. also attest to his continued sense of proportion and humor—he suggests C++ community in myriad direct and Feasibility of new techniques that the fictitious interview would have not-so-direct ways. Obviously, we will Computer: You say that “often what an been a much funnier parody had he get better implementations as compiler experienced C++ programmer has failed written it himself. providers start shifting attention from to notice over the years is not the intro- —Scott Hamilton, Computer catching up with the standards commit- duction of new features as such, but tee to quality-of-implementation issues. rather the changes in relationships STANDARD C++ This is already happening. between features that make fundamental Computer: ISO approved the Standard Standards-conforming implementa- new programming techniques feasible.” C++ in November 1997, and you pub- tions will prove a boon to tools and Could you give some examples of how lished a third edition of your The C++ library suppliers by providing a larger this might be applicable to Standard C++? Programming Language (Addison Wes- common platform to build for. Stroustrup: It is easy to study the rules of ley, 1997). How has C++ evolved over the The standard gives the programmer an overloading and of templates without past few years and what does the ISO opportunity to be more adventurous noticing that together they are one of the standard mean for the C++ community? with new techniques. Programming keys to elegant and efficient type-safe Stroustrup: It is great to finally have a styles that used to be unrealistic in pro- containers. This connection becomes complete, detailed, and stable definition duction code are becoming realistic obvious only when you look into the fun- of C++. This will be a great help to the propositions. Thus, more flexible, gen- damental algorithms that are common to eral, faster, and more maintainable code most uses of containers. Consider the can be written. program segment in Figure 1a. The first Editor: Will Tracz, Lockheed Martin Federal Naturally, we should keep cool and call of count() counts the number of Systems, MD 0210, Owego, NY 13827-3998; not indulge in orgies of “advanced” tech- occurrences of the value 7 in a vector of [email protected] niques. There are still no miracles, and integers. The second call of count() the best code is still the code that most counts the number of occurrences of the

110 Computer void f(vector& vi, list& ls) { int n1 = count(vi.begin(),vi.end(),7); int n2 = count(ls.begin(),ls.end(),”seven”); value “seven” in a list of strings. // ... There are ways of achieving this in } every language that allows overloading. (a) Given templates, we can write a single function that handles both calls, as template shown in Figure 1b. This template will int count(Iter first, Iter last, T value) expand into optimal code for the two { calls. This count() is roughly equiva- int c = 0; lent to the standard-library count() so while (first!=last) { a user will not have to write it. The if (*first == value) c++; count() function itself relies on over- ++first; loading: Obviously, the equality opera- } tor == is overloaded for integers and return c; strings (with the obvious meaning). In } addition, * and ++ are overloaded to (b) mean “dereference” and “refer to next element” for the iterator types for vec- Figure 1. Changes in relationships between features can make fundamental new programming tors and lists; that is, * and ++ are given techniques feasible: (a) A count algorithm for counting the number of occurrences of the value the meaning they have for pointers. 7 in a vector of integers, as well as the number of occurrences of the value “seven” in a list of This definition of count() illustrates strings becomes (b) a single function that handles both calls using a template. a couple of the key techniques used in the containers and algorithms part of the C++ standard library. These techniques are template useful, and they are not trivially discov- int count_if(Iter first, Iter last, Predicate pred) ered given only the basic language rules. { Consider a slightly more advanced int c = 0; variation of the count() example while (first!=last) { shown in Figure 2a. Instead of counting if (pred(*first)) c++; occurrences of a value, count_if() ++first; counts the number of elements that ful- } fill a predicate. For example, we can return c; count the number of elements with a } value less than 7 as shown in Figure 2b. (a) Generalizing this technique to handle comparisons with any value of any type bool less_than_7(int i) { return i<7; } requires us to define a function object— that is, a class whose objects can be void f2(vector& vi, list& li) invoked like functions, as shown in { Figure 3a. The constructor stores a ref- int n1 = count_if(vi.begin(),vi.end(),less_than_7); erence to the value we want to compare int n2 = count_if(li.begin(),li.end(),less_than_7); against, as in Figure 3b, and the applica- // ... tion operator (operator()) does the } comparison. In other words, count the (b) number of elements in vi that have a value less than the integer 7, and count Figure 2. More advanced variation of the count example that (a) counts the number of elements the number of elements in ls that have that meet a predicate—for example, (b) the number of elements with a value less than 7. a value less than the string “seven.” It may be worth mentioning that the code generated is very efficient and in techniques for using templates and over- Language features are fundamentally particular does not use function calls—or loading—and that, of course, is part of boring in isolation and they can distract similar relatively slow operations—to the purpose of presenting the examples from good system building—only in the implement comparisons, fetching the here. However, the bottom line is that context of programming techniques do next element, and so forth. these techniques allow you to write effi- they come alive. Undoubtedly, this code will look cient, type-safe, and generic code. People strange to someone who is not a C++ pro- familiar with functional languages will The Standard Library grammer and even to C++ programmers note that these techniques are similar to Computer: How was the Standard who have not yet internalized the latest techniques pioneered in those languages. Library defined and what impact will it

June 1998 111 template class Less_than { const T v; public: Less_than(const T& vv) :v(vv) {} // constructor bool operator()(const T& e) { return e& vi, list& ls) In particular, standard containers allow { both novices and experts to program at int n1 = count_if(vi.begin(),vi.end(), a higher level. Consider the simple pro- Less_than(7)); gram in Figure 4, which performs a sim- int n2 = count_if(ls.begin(),ls.end(), ple task simply. It does so without Less_than(“seven”)); macros, without explicit memory man- // ... agement or other low-level language } facilities, and without resource limita- tions. In particular, if some joker presents (b) the program with a 30,000 character “first name” the program will faithfully Figure 3. To handle comparisons with any value of any type, we define (a) a class whose objects print it back at him without overflow or can be invoked like functions (function object), with the constructor storing (b) a reference to other errors. the value we want to compare against. Using the standard library can and should revolutionize the way C++ is have on the C++ community? • uncompromising efficiency of sim- taught. It is now possible to learn C++ as Stroustrup: The most novel and interest- ple basic operations (for example, a higher level language. Students deal ing part of the standard library is the gen- array subscripting should not incur with the facilities for low-level program- eral and extensible framework for the cost of a function call); ming only when needed and only after containers and algorithms. It is often • type-safety (an object from a con- they’ve mastered enough of the language called the STL and is primarily the work tainer should be usable without to provide a suitable context for dis- of Alex Stepanov (then at Hewlett- explicit or implicit type conver- cussing low-level facilities. Packard Labs, now at Silicon Graphics). sion); Thus, the standard library will serve as Alex worked on providing uncompro- • generality (the library should pro- both a tool and as a teacher. misingly general and uncompromisingly vide several containers, such as vec- efficient fundamental algorithms which, tors, lists, and maps); and COMPLEXITY, C++, AND OOP for example, find an element in a data • extensibility (if the standard library Computer: In The C++ Programming structure, sort a container, or count the didn’t provide some container that Language, you say “Ordinary practical occurrences of a value in a data structure. I needed, I should be able to create programmers have achieved significant Such algorithms are fundamental to one and use it just as I would a stan- improvements in productivity, maintain- much computing. dard container). ability, flexibility, and quality in projects Alex worked with a variety of languages of just about any kind and scale.” Yet and had several collaborators over the By adopting STL with only minor mod- some critics maintain that C++, and OO years—notably David Musser (Rensselaer ifications and additions, we avoided the in general, are overly complex and give Polytechnic Institute), Meng Lee (HP dreaded design by committee. rise to corrective-maintenance and main- Labs), and Andrew Koenig (AT&T Labs). Clearly, a group of part-time volunteers tenance problems in large systems. Do My contribution to the STL was small, but (the C++ standards committee) can’t pro- these criticisms in any way correspond to I think important: I designed an adapter vide every library facility that a program- your own experiences as a developer of called mem_fun(). It allows standard mer would find useful. Consequently, a large systems in C++? algorithms to be used for containers of key issue was what to include in the stan- Stroustrup: In my personal experience, polymorphic objects, thus tying object-ori- dard library and what to leave to the OO design and OO programming lead to ented programming techniques neatly into industry and individuals to provide. better code than you get from more tra- the framework of We decided to use “what is needed for ditional procedural approaches—code the standard library. the communication between separately that is more flexible, more extensible, and Somewhat to my surprise, the STL developed libraries” as a guide to what to more maintainable without imposing sig- matched the set of criteria for a good set include. Thus, I/O, strings, and containers nificant performance overheads. There is of standard containers for C++ that I had became the major focus. We included the not as much hard evidence—as opposed developed over the years. After a year or C standard library and some facilities for to personal observations—as I would so of discussing and polishing the STL, numeric computation for historical rea- like, but several studies within AT&T the ISO C++ committee accepted the STL sons, but left out lots of potentially use- and elsewhere support this opinion. as a key part of the standard C++ library. ful facilitiessuch as better facilities for Two factors confound the issue: There My criteria included dates and currency, regular expression is no general agreement on what “object-

112 Computer int main() { cout << “Please enter your first name:\n”; string name; oriented” really is, and discussions rarely cin >> name; // read into name cout account for experience sufficiently. Much << “Hello“ << name << “!\n”; of “the trouble with OO” comes from } people with no significant OO experience approaching an ambitious project with Figure 4. Simple “Hello” program using Standard Library features to perform its task simply. some partially understood—yet dog- matic and typically limited—notion of what OO code must look like. the criteria for “goodness” (easy to JAVA AND C++ So what is OO? Certainly not every understand, flexible, efficient) are a Computer: That same argument for sim- good program is object-oriented, and not recursive descent parser, which is tradi- plicity could conceivably be extended to every object-oriented program is good. If tional procedural code. Another exam- Java, which might explain the 700,000 this were so, “object-oriented” would ple is the STL, which is a generic library Java programmers that Sun claims (com- simply be a synonym for “good,” and the of containers and algorithms depending pared to 1.5 million C++ programmers). concept would be a vacuous buzzword crucially on both traditional procedural You maintain that Java is not the language of little help when you need to make code and on parametric polymorphism. you would have designed even if C++ practical decisions. I tend to equate OOP I find languages that support just one needn’t be compatible with C. What else with heavy use of class hierarchies and programming paradigm constraining. do you have to say after having been asked virtual functions (called methods in some They buy their simplicity (whether real this question for the thousandth time? languages). This definition is historically or imagined) by putting programmers Stroustrup: These days, I’m always asked accurate because class hierarchies and into an intellectual straitjacket or by about Java, and it is very hard for me to virtual functions together with their pushing complexity from the language respond. If I say something negative, I accompanying design philosophy were into the applications. This is appropriate sound ungracious; if I say something pos- what distinguished from the other for special-purpose languages, but not itive, I feed into the commercial hype that languages of its time. In fact, it is this for general-purpose languages. surrounds Java and the unfortunate anti- aspect of Simula’s legacy that Smalltalk I have often characterized C++ as a gen- C++ propaganda that emanates from has most heavily emphasized. eral-purpose programming language with parts of the Java community. Defining OO as based on the use of a bias toward systems programming. I encourage people to consider the two class hierarchies and virtual functions is Think of it as “a better C” that supports languages according to their design crite- also practical in that it provides some ria and not just in the context of com- guidance as to where OO is likely to be • data abstraction, mercial rivalries. I outlined the design successful. You look for concepts that • object-oriented programming, and criteria for C++ in detail in The Design have a hierarchical ordering, for variants • generic programming. and Evolution of C++, and Java doesn’t of a concept that can share an imple- even start to meet those criteria. That’s mentation, and for objects that can be Naturally, this support for more than fine as long as programmers consider Java manipulated through a common inter- one approach to programming causes as a programming language among oth- face without being of exactly the same more complexity than supporting only ers and not a panacea. After all, C++ isn’t type. Given a few examples and a bit of one approach. I have noticed that this a perfect match for Java’s design aims experience, this can be the basis for a very viewthat there are design and pro- either. However, when Java is promoted powerful approach to design. gramming approaches with domains in as the sole programming language, its However, not every concept naturally which they are the bestoffends some flaws and limitations become serious. and usefully fits into a hierarchy, not every people. Clearly, I reject the view that there Here are a few examples where the cri- relationship among concepts is hierarchi- is one way that is right for everyone and teria applied to developing C++ led to cal, and not every problem is best for every problem. People who passion- significant differences. Unlike Java, C++ approached with a primary focus on ately want to believe that the world is supports objects. For example, some problems really basically simple react to this with a fury are primarily algorithmic. Consequently, a that goes beyond what I consider appro- • the ability to effectively compose a general-purpose programming language priate for discussing a programming lan- program out of parts written in dif- should support a variety of ways of think- guage. After all, a programming language ferent languages, ing and a variety of programming styles. is just one tool among many that we use • a variety of design and program- This variety results from the diversity of to construct our systems. ming styles, problems to be solved and the many ways The ideal way of resolving the two • user-defined types with efficiencies of solving them. C++ supports a variety of views would be to have a language that that approach built-in types, programming styles and is therefore more provides a set of simple primitives from • uniform treatment of built-in and appropriately called a multiparadigm, which all good programming styles can user-defined types, and rather than an object-oriented, language be efficiently supported. This has been • the ability to use generic containers (assuming you need a fancy label). repeatedly tried but not—in my opin- without runtime overhead (for Examples of designs that meet most of ion—achieved. example, the STL).

June 1998 113 Open Channel

I designed C++ so programmers could Given C++’s relative maturity at this I’d rather not specifically “rate” the write code that is both elegant and efficient. point, how would you rate the available available C++ tools. They are better than For many applications, C++ is still the best C++ development tools and what still they were, and most often as good or bet- choice when you don’t want to compro- needs to be done to improve? ter than any tools for any other language. mise between elegance and efficiency. Stroustrup: First, I’d like to see the basic However, as a programmer, I am natu- I wonder how people count “pro- tools such as compilers, debuggers, pro- rally impatient for more and better qual- grammers.” Is a student a programmer? filers, database interfaces, GUI builders, ity tools. Personally, I look forward to Is every compiler shipped counted as a CAD tools, and so forth fully support the better tools for analyzing C++ source programmer? I understand the number ISO standard. For example, I’d like to get code. I also hope that C++ implementa- quoted for C++; it is conservative and a database query result as an STL con- tion vendors will spend a slightly larger plausible. It is a good approximation of tainer or an istream of appropriately fraction of their budgets on improving the number of C++ implementations sold typed objects. Tool vendors have made a the quality and performance of their for real money last year. I wonder if Sun’s good start, but have much work to do in compilers rather than concentrating too Java number is as solid. Incidentally, tools that depend on compilers and other heavily on novelties. Real improvements based on the few hard numbers I have source code analyzers. in compilers are relatively cheap com- found—such as compiler sales, book My list of basic tools is a partial answer pared to what is spent on a new release sales, and C++ course attendance—I esti- of a complete C++ implementation. mate that the C++ user population is However, I fear that unless major users growing at 10 to 20 percent a year. Java has borrowed start demanding conformance testing And no, I’m not a Java fan. I dislike much from C++, but not and benchmarking, vendors will spend hype, I dislike marketing of program- as much as is often resources on what looks better in an ming tools to nonprogrammers, I dislike claimed and not with as advertisement. proprietary languages, and I like lots of much taste and programming languages. On the techni- understanding as one THE FUTURE cal side, Java never gave me the “Wow, Computer: I know you’ve been heavily that’s neat!” reaction that I have had could have wished for. involved in the C++ standards process, with many other languages. It provides but what other projects are you involved popular language features in a form that in currently and how will you continue I consider limiting. to the question about what has changed: working to evolve C++? Java has borrowed much from C++, Over the past few years, large numbers Stroustrup: I’m suffering from having but not as much as is often claimed and of programmers have come to depend on successfully completed a very large pro- not with as much taste and understand- elaborate tools to interface code with sys- ject. The ISO C++ standard is done. The ing as one could have wished for. To tems facilities. These tools are essential to third edition of The C++ Programming deliver on some of the key promises relieving programmers of tedious and Language is there to acquaint serious made for it, Java must grow. This evo- error-prone tasks, but come at a risk of programmers with what Standard C++ lution may compromise Java’s claim of the programmers (and their employers) has to offer and how best to use it. And being simpler than C++, but my guess is becoming captives of their tool suppliers. Design and Evolution documents the that the effort will make Java a better Often, these tools are far more complex design decisions that shaped C++. There language than it is today. Currently, Java than a traditional programming lan- is more to be done, but nothing that seems to be accumulating language fea- guage, and there are few standards. requires a full-time language designer. tures and “standard” libraries at quite I would encourage nonproprietary Now is the time to enjoy the flexibility a pace. I’m looking forward to seeing standards for tools and libraries. In the and power of C++ by writing code, what the Java version of templates will short term, say 10 years, many such stan- rather than focusing on possible changes. look like; as far as I know Sun hasn’t yet dards will be industry standards rather Apart from that, I’m taking the oppor- blessed any of the dozen or so dialects. than formal ISO or IEEE standards, but tunity to learn a few things—a couple of As Java and its community matures, it it is essential for the software industry’s new languages and something about how will hopefully adopt a sensible live-and- health that key interfaces be well-specified software is used in a large business—and let-live philosophy. This would allow and publicly available. With the increasing planning some experiments in distributed Java to take its place as one language importance of standards for system-level computing. ❖ among many in the tool chest of profes- objects such as COM and CORBA, it is sional programmers. particularly important that the C++ bind- ings to those be clean, well documented, TOOLS and simple to use. Unfortunately, such Computer: In what ways have systems “standards work”which is beneficial to Bjarne Stroustrup is head of the large- changed over the past few years, and everybodyis neglected because it pro- scale programming research department what still needs to be done in the C++ vides short-term competitive advantages at AT&T; [email protected];http:// arena and in systems design in general? to nobody. www.research.att.com/~bs/

114 Computer