Movatterモバイル変換


[0]ホーム

URL:


home|C++|FAQ|technical FAQ|publications|WG21 papers|TC++PL|Tour++|Programming|D&E|bio|interviews|videos|quotes|applications|guidelines|compilers

Posting to comp.lang.c++

Sometime -- in the spring of 1993, I think -- I posted a message tocomp.lang.c++ as part of a debate of how one should approach learning C++.This message has been widely circulated and even re-printed in a coupleof books.It is part of the "Interest and Use" chapter ofThe Design and Evolution of C++.

Apart from converting the ASCII message to HTML, I have not edited it here.


There has - under various headings - been several related discussionsabout the proper way to learn C++, C++'s relation to C, C++'s relationto Smalltalk, the difference (or not) between data abstraction andobject-oriented programming, etc.

I think the practical concern underlying many of these discussions is:

Given that I don't have much time to learn new techniquesand concepts, how do I start using C++ effectively?
It is clear that to use C++ ``best'' in an arbitrary situation youneed a deep understanding of many concepts and techniques, but thatcan only be achieved through years of study and experiments. It islittle help to tell a novice (a novice with C++, typically not anovice with programming in general), first to gain a thoroughunderstanding of C, Smalltalk, CLOS, Pascal, ML, Eiffel, assembler,capability based systems, OODMBSs, program verification techniques,etc., and then apply the lessons learned to C++ on his or her nextproject. All of those topics are worthy of study and would - in thelong run - help, but practical programmers (and students) cannottake years off from whatever they are doing for a comprehensivestudy of programming languages and techniques.

On the other hand, most novices understand that ``a little knowledgeis a dangerous thing'' and would like some assurance that the littlethey can afford time to learn before/while starting their next projectwill be of help and not a distraction or a hinderance to the successof that project. They would also like to be confident that the littlenew they can absorb immediately can be part of a path that can leadto the more comprehensive understanding actually desired rather thanan isolated skill leading nowhere further.

Naturally, more than one approach can fulfill these criteria andexactly which to choose depends on the individual's background,immediate needs, and the time available. I think many educators,trainers, and posters to the net underestimate the imporatanceof this: after all, it appears so much more cost effective - andeasier - to ``educate'' people in large batches rather thanbothering with individuals.

Consider a few common questions:

I don't claim to have the only answers ``the (only) right answers''to these questions. As I said the ``right'' answer depends on thecircumstances. Most C++ textbook writers, teachers, and programmershave their own answers. For example, I seem to remember that the C++FAQ discusses these questions. My answers are based on years ofprogramming in C++ and other languages, teaching short C++ designand programming courses (mainly to professional programmers),consulting about to introduction of and use of C++, discussing C++,and generally thinking about programming, design, and C++.

I don't know C or C++, should I learn C first?

No. Learn C++ first. The C subset of C++ is easier to learn for C/C++novices and easier to use than C itself. The reason is thatC++ provides better guarantees than C (stronger type checking).In addition, C++ provides many minor features, such as the `new'operator, that are notationally more convenient and less error-pronethan their C alternatives. Thus, if you plan to learn C and C++ (orjust C++) you shouldn't take the detour through C. To use C well,you need to know tricks and techniques that aren't anywhere nearas important or common in C++ as they are in C. Good C textbookstends (reasonably enough) to emphasize the techniques that youwill need for completing major projects in C. Good C++ textbooks,on the other hand, emphasizes techniques and features that leadto the use of C++ for data abstraction and object-oriented programming.Knowing the C++ constructs, their (lower-level) C alternatives aretrivially learned (if necessary).

To show my inclinations:

To learn C use:

Kernighan and Ritchie:The C programming Language (2nd edition)Prentice Hall, 1988.
as the primary textbook.

To learn C++ use

Stroustrup:The C++ Programming Language (2nd edition).Addison Wesley, 1991.
Both books have the advantage of combining a tutorial presentationof language features and techniques with a complete reference manual.Both describes their respective languages rather than particularimplementations and neither attempts to describe particular librariesshipped with particular implementations.

There are many other good textbooks and many other styles ofpresentation, but these are my favorites for comprehensionof concepts and styles. It is always wise to look carefullyat at least two sources of information to compensate for biasand possible shortcommings.

I want to do OOP, should I learn Smalltalk before C++?

No. If you plan to use C++, learn C++. Languages such as C++, Smalltalk,Simula, CLOS, Eiffel, etc., each has their own view of the key notionsof abstraction and inheritance and each support them in slightly differentways to support different notions of design. Learning Smalltalk willcertainly teach you valuable lessons, but it will not teach you how towrite programs in C++. In fact, unless you have the time to learn anddigest both the Smalltalk and the C++ concepts and techniques, usingSmalltalk as a learning tool can lead to poor C++ designs.

Naturally, learning both C++ and Smalltalk so that you can draw froma wider field of experience and examples is the ideal, but peoplewho haven't taken the time to digest all the new ideas often end up``writing Smalltalk in C++'' that is applying Smalltalk design notionsthat doesn't fit well in C++. This can be as sub-optimal writing C orFortran in C++.

One reason often quoted for learning Smalltalk is that it is ``pure''and thus force people to think and program ``object oriented.''I will not go into the discussion about ``purity'' beyond mentioningthat I think that a general purpose programming language ought toand can support more than one programming style (``paradigm'').

The point here is that styles that are appropriate and wellsupported in Smalltalk are not necessarily appropriate for C++.In particular, a slavish following of Smalltalk style in C++leads to inefficient, ugly, and hard to maintain C++ programs.The reason is that good C++ requires design that takes advantageof C++'s static type system rather than fights it. Smalltalksupport a dynamic type system (only) and that view translatedinto C++ leads to extensive unsafe and ugly casting.

I consider most casts in C++ programs signs of poor design. Somecasts are essential, but most aren't. In my experience, old-timeC programmers using C++ and C++ programmers introduced to OOPthrough Smalltalk are among the heaviest users of casts of thekind that could have been avoided by more careful design.

In addition, Smalltalk encourages people to see inheritance asthe sole or at least primary way of organizing programs and toorganize classes into single-rooted hierarchies. In C++, classesare types and inheritance is by no means the only means of organizingprograms. In particular, templates is the primary means forrepresenting container classes.

I am also deeply suspicious of arguments proclaiming the need to FORCEpeople to write in an object-oriented style. People who don't want tolearn can, on average, not be taught with reasonable effort and thereis in my experience no shortage of people who DO want to learn. Unlessyou manage to demonstrate the principle behind data abstraction andobject-oriented programming all you'll get is inappropriate ``barouque''misuses of the language features that support these notions - in C++,Smalltalk, or whatever.

See ``The C++ Programming (2nd Edition)'' and in particular Chapter 12for a more thorough discussion of the relation between C++ languagefeatures and design.

Should I start using C++ as an OOPL or as a better C?

That depends. Why do you want to start using C++? The answer to thatquestion ought to determine the way you approach C++; not someone-size-fits-all philosophy. In my experience the safest bet isto learn C++ ``bottom up,'' that is first learn the features C++provides for traditional procedural programming, the ``better C''sub-set, then learn to use and appreciate the data abstraction features,and then learn to use class hierarchies to organize sets of relatedclasses.

It is - in my opinion - dangerous to rush through the earlier stagesbecause there is too high a probability of missing some key point.

For example, an experience C programmer might consider the ``betterC'' subset of C ``well known'' and skip the 100 pages or so of atextbook that describes it. However, in doing so he might miss theability to overload functions, the difference between initializationand assignment, the use of the `new' operator for allocation, theexplanation of references, or some other minor feature in such a waythat it will come back to haunt him at a later stage where sufficientnew concepts are in play to complicate matters. If the concepts usedin the better C subset are known the 100 pages will only take a coupleof hours to learn and some details will be interesting and useful.If not, the time spent is essential.

Some people have expressed fear that this ``gradual approach'' leadspeople to write in C style forever. This is of course a possibleoutcome, but nowhere as likely as proponents of ``pure'' languagesand proponents of the use of ``force'' in teaching programming liketo believe. The key thing to realize is that using C++ well as adata abstraction and/or object-oriented language requires theunderstanding of a few new concepts that have no direct counterpartin languages such as C and Pascal.

C++ isn't just a new syntax for expressing the same old ideas -at least not for most programmers. This implies a need for education,rather than mere training. New concepts have to be learned andmastered through practice. Old and well-tried habits of work haveto be re-evaluated, and rather than dashing of doing things ``thegood old way'' new ways have to be considered - and often doingthings a new way will be harder and more time-consuming thanthe old way - when tried for the first time.

The overwhelming experience is that taking the time and making theeffort to learn the key data abstraction and object-oriented techniquesis worth while for almost all programmers and yields benefits notjust in the very long run but also on a three to twelve month timescale.There are benefits in using C++ without making this effort, but mostbenefits requires the extra effort to learn new concepts - I wouldwonder why anyone not willing to make that effort would switch to C++.

When approaching C++ for the first time, or for the first time aftersome time, take the time to read a good textbook or a few well chosenarticles (the C++ Report and the C++ Journal contain many). Maybe alsohave a look at the definition or the source code of some major libraryand consider the techniques and concepts used. This is also a good ideafor people who has used C++ for some time. Many could do with a reviewof the concepts and techniques. Much has happened to C++ and its associatedprogramming and design techniques since C++ first appeared. A quickcomparison of the 1st and the 2nd edition of ``The C++ ProgrammingLanguage'' should convince anyone of that.

How long does it take to learn C++?

Again, that depends. It depends both on your experience and on whatyou mean by ``learning C++.'' The syntax and basics for writing C++in the better C style plus defining and using a few simple classestakes a week or two for a programmer. That's the easy part. The maindifficulty, and the main fun and gain comes from mastering new designand programming techniques. Most experienced programmers I have talkedwith quotes times from a half year to one and a half year for becommingreally comfortable with C++ and the key data abstraction and object-oriented techniques it supports. That assumes that they learn on thejob and stay productive - usually by programming in a ``less adventurous''style of C++ during that period. If one could devote full time tolearning C++ one would be comfortable faster, but without actualapplication of the new ideas on real projects that degree of comfortcould be misleading. Object-oriented programming and object-orienteddesign are essentially practical - rather then theoretical - disciplines.Unapplied, or applied only to toy examples, these ideas can becomedangerous ``religions.''

Note that learning C++ is then primarily leaning programming and designtechniques, not language details. Having worked through a good textbookI would suggest a book on design such as

Grady Booch:Object Oriented Design with examplesBenjamin Cummings 1990.
which has the nice property of having longish examples in five differentlanguages (Ada, CLOS, C++, Smalltalk, and Object Pascal) and is thereforesomewhat immune to the language biogotry that mar some design discussions.The parts of the book I like best is the presentation the design conceptsand the example chapters.

Looking at design contrasts sharply with the approach of looking verycarefully at the details of the definition of C++ - usually using the ARM

Ellis & Stroustrup:The Annotated C++ Reference Manual.Addison-Wesley, 1990
which is a book containing much useful information, but no informationabout how to write C++ programs. A focus on details can be very distractingand lead to poor use of the language. You wouldn't try to learn a foreignlanguage from a dictionary and grammar, would you?

When learning C++, it is essential to keep the key design notions in mindso that one doesn't get lost in the language technical details. That done,learning and using C++ can be both fun and productive. A little C++ canlead to significant benefits compared to C, further efforts to understanddata abstraction and object-oriented techniques yields further benefits.

-Bjarne Stroustrup

home|C++|FAQ|technical FAQ|publications|WG21 papers|TC++PL|Tour++|Programming|D&E|bio|interviews|videos|quotes|applications|guidelines|compilers

[8]ページ先頭

©2009-2025 Movatter.jp