home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / C++-faq / part3 < prev    next >
Internet Message Format  |  2000-03-01  |  44KB

  1. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!newsfeed.sgi.net!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!newsfeed.novia.net.MISMATCH!novia!nntp3.cerf.net!nntp2.cerf.net!news.cerf.net!not-for-mail
  2. From: mpcline@nic.cerf.net (Marshall Cline)
  3. Newsgroups: comp.lang.c++,comp.answers,news.answers,alt.comp.lang.learn.c-c++
  4. Subject: C++ FAQ (part 3 of 10)
  5. Followup-To: comp.lang.c++
  6. Date: 29 Feb 2000 20:06:34 GMT
  7. Organization: ATT Cerfnet
  8. Lines: 1011
  9. Approved: news-answers-request@mit.edu
  10. Distribution: world
  11. Expires: +1 month
  12. Message-ID: <89h8sa$btq$1@news.cerf.net>
  13. Reply-To: cline@parashift.com (Marshall Cline)
  14. NNTP-Posting-Host: nic1.san.cerf.net
  15. X-Trace: news.cerf.net 951854794 12218 192.215.81.88 (29 Feb 2000 20:06:34 GMT)
  16. X-Complaints-To: abuse@cerf.net
  17. NNTP-Posting-Date: 29 Feb 2000 20:06:34 GMT
  18. Summary: Please read this before posting to comp.lang.c++
  19. Xref: senator-bedfellow.mit.edu comp.lang.c++:453821 comp.answers:39861 news.answers:178220 alt.comp.lang.learn.c-c++:40799
  20.  
  21. Archive-name: C++-faq/part3
  22. Posting-Frequency: monthly
  23. Last-modified: Feb 29, 2000
  24. URL: http://marshall-cline.home.att.net/cpp-faq-lite/
  25.  
  26. AUTHOR: Marshall Cline / cline@parashift.com / 972-931-9470
  27.  
  28. COPYRIGHT: This posting is part of "C++ FAQ Lite."  The entire "C++ FAQ Lite"
  29. document is Copyright(C)1991-2000 Marshall Cline, Ph.D., cline@parashift.com.
  30. All rights reserved.  Copying is permitted only under designated situations.
  31. For details, see section [1].
  32.  
  33. NO WARRANTY: THIS WORK IS PROVIDED ON AN "AS IS" BASIS.  THE AUTHOR PROVIDES NO
  34. WARRANTY WHATSOEVER, EITHER EXPRESS OR IMPLIED, REGARDING THE WORK, INCLUDING
  35. WARRANTIES WITH RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
  36. PURPOSE.
  37.  
  38. C++-FAQ-Lite != C++-FAQ-Book: This document, C++ FAQ Lite, is not the same as
  39. the C++ FAQ Book.  The book (C++ FAQs, Cline and Lomow, Addison-Wesley) is 500%
  40. larger than this document, and is available in bookstores.  For details, see
  41. section [3].
  42.  
  43. ==============================================================================
  44.  
  45. SECTION [5]: Netiquette when posting to comp.lang.c++
  46.  
  47.  
  48. [5.1] What does IMHO mean? (or IMO, IMNSHO, FWIW, OTOH, etc.)? [UPDATED!]
  49.  
  50. [Recently added IMAO thanks to Charles R Martin (on 1/00).]
  51.  
  52. Here's a partial list of acronyms in alphabetical order:
  53.  * AFAICS = As far as I can see
  54.  * BTW = By the way
  55.  * FWIW = For what it's worth
  56.  * FYI = For your information
  57.  * IMHO = In my humble opinion (egoless)
  58.  * IMAO = In my arrogant opinion (a lot of ego)
  59.  * IMNSHO = In my not-so humble opinion (a lot of ego)
  60.  * IMO = In my opinion (a little ego)
  61.  * KUTGW = Keep Up The Good Work
  62.  * MYOB = Mind your own business
  63.  * OTOH = On the other hand
  64.  * RTFM = Read the ___ manual
  65.  * SO = Significant other (as in, "My SO and I went for a walk...")
  66.  
  67. BTW my SO says, "FWIW IMNSHO 'KUTGW' is rare; OTOH it may be helpful to
  68. somebody."
  69.  
  70. For more acronyms please see www.astro.umd.edu/~marshall/abbrev.html.
  71.  
  72. ==============================================================================
  73.  
  74. [5.2] How do I get comp.lang.c++ to do my homework problem for me?
  75.  
  76. Shame on you!
  77.  
  78. Please do not post your homework questions to comp.lang.c++.
  79.  
  80. ==============================================================================
  81.  
  82. [5.3] What should I do if I see someone else posting a homework problem?
  83.  
  84. When a slackard[5.2] asks comp.lang.c++ to do their homework for them,
  85. answering their question is the worst thing for them.  Please don't do it!
  86. Instead you can use the following table of "frequently asked homework
  87. assignments" to give them a hint/pointer:
  88.  
  89. ===TABLE-BEGIN=== (yea, I know; it's pathetic; the HTML version is better)
  90.  
  91. ===TABLE-ROW===
  92. If someone asks...
  93. ---
  94. ...then here's a brief answer:
  95.  
  96. ===TABLE-ROW===
  97. How do I do Equation Parsing in C++?
  98. ---
  99. Use a stack of operators to convert infix to postfix, then a stack of operands
  100. to evaluate the postfix expression.
  101.  
  102. ===TABLE-ROW===
  103. How do I do Shortest Path in C++?
  104. ---
  105. Look up Dijkstra's algorithm and backtracking.
  106.  
  107. ===TABLE-ROW===
  108. How do I do Sorting in C++?
  109. ---
  110. Look up heapsort, quicksort, merge sort, internal and external sorting.
  111.  
  112. ===TABLE-ROW===
  113. How do I do Minimum Spanning Trees in C++?
  114. ---
  115. Look up Kruskal and/or Prim's algorithm.
  116.  
  117. ===TABLE-ROW===
  118. How do I do Combinations and/or Permutations in C++?
  119. ---
  120. See your algorithms book.
  121.  
  122. ===TABLE-ROW===
  123. How do I do <some small essay problem; obviously contrived for a school
  124. assignment; too well defined to to be from the real world> in C++?
  125. ---
  126. Do it yourself. If you get stuck, ask a specific question.
  127.  
  128. ===TABLE-END===
  129.  
  130. [If anyone has other suggestions that should go into this table, please let me
  131. know; thanks; (cline@parashift.com)].
  132.  
  133. ==============================================================================
  134.  
  135. [5.4] How can I find out about general netiquette so I don't embarrass myself?
  136.  
  137. Key guidelines:
  138.  * Do not say, "Please respond by e-mail because I don't normally read this
  139.    newsgroup".  If you don't have enough time for the newsgroup, don't expect
  140.    the newsgroup to have enough time for you.
  141.  * Do not post questions that are answered in the newsgroup's FAQ.  That's like
  142.    saying your time (to read the FAQ) is more valuable than the time of
  143.    hundreds and hundreds of others (to answer your question).  Tres uncool.
  144.    Read the FAQ first![5.5]
  145.  * Do not cross post your question to a big pile of newsgroups.  Post to the
  146.    newsgroup (singular) that best fits your question[5.8].  If you don't get an
  147.    answer in the "right" newsgroup, post somewhere else but redirect followups
  148.    back to the "right" newsgroup.
  149.  * Do include a working e-mail address in your signature.  If your From:
  150.    address is not correct, please notify your system administrator.  Until it's
  151.    fixed, add a Reply-to: line that gives your correct e-mail address.
  152.  
  153. Many more general netiquette questions are answered in the newsgroup
  154. news.announce.newusers.  This newsgroup contains many must-read articles for
  155. new users.
  156.  
  157. ==============================================================================
  158.  
  159. [5.5] What do I do if someone else posts a question that's already in the FAQ?
  160.  
  161. Please don't answer a question that's already in the FAQ.  Instead politely but
  162. firmly point the questioner to the FAQ using the following template:
  163.  
  164.     Subject: It's in the FAQ (was: Original_Subject_Goes_Here)
  165.  
  166.     > Original_Question_Goes_Here [...]
  167.  
  168.     This issue is covered in the C++ FAQ.
  169.     You can get the FAQ at:
  170.         http://marshall-cline.home.att.net/cpp-faq-lite/
  171.  
  172.     Please read the FAQ.
  173.  
  174. If you're willing to help in this effort, consider yourself "deputized" to
  175. point people to the FAQ using something like the above template.  With your
  176. help, hopefully we can improve the signal-to-noise ratio on comp.lang.c++ and
  177. thereby preserve it as a valuable resource.
  178.  
  179. Note #1: Please don't give them the location of the appropriate FAQ.  E.g.,
  180. don't say, "Look at FAQ [10.3]" or "Look in section [10]".  It's the old
  181. give-them-a-fish vs. teach-them-to-fish problem.
  182.  
  183. Note #2: Please be polite.  I'm hoping we can avoid "RTFM" or "RTFFAQ"
  184. euphemisms (or worse!).
  185.  
  186. Thanks for any help you can give in this matter.
  187.  
  188. ==============================================================================
  189.  
  190. [5.6] What makes a good Subject: line?
  191.  
  192. Be descriptive:
  193.  * Bad: "Subject: HELP"
  194.  * Bad: "Subject: C++ problem"
  195.  * Bad: "Subject: SEX SEX SEX"
  196.  * Good: "Subject: Problem new'ing a multi-dimensional array"
  197.  
  198. Mention your compiler/version if you think it's relevant.
  199.  
  200. ==============================================================================
  201.  
  202. [5.7] How do I post a question about code that doesn't work correctly?
  203.  
  204. Key guidelines:
  205.  
  206.  1. Post compile'able code: avoid ellipses, such as void f() { ... }
  207.  
  208.  2. Post complete code: put in all necessary #includes and declarations of
  209.     needed types and functions
  210.  
  211.  3. Post minimal code: just enough to demonstrate the problem; skip I/O and
  212.     calls to libraries if possible
  213.  
  214.  4. Post one compilation unit: if possible, combine Foo.h into Foo.cpp
  215.  
  216.  5. Post the tools you used: compiler name, version number, operating system,
  217.     etc
  218.  
  219.  6. Post the tool options you used: libraries, exact compiler and linker
  220.     options, etc
  221.  
  222.  7. Post the exact messages you received; differentiate between compiler,
  223.     linker, and runtime messages
  224.  
  225. As always, make sure your question isn't already in the FAQ.  Use the subject
  226. index to check.
  227.  
  228. ==============================================================================
  229.  
  230. [5.8] Which newsgroup should I post my questions?
  231.  
  232. Only post to comp.lang.c++ if your question is about the C++ language itself.
  233. For example, C++ code design, syntax, style, rules, bugs, etc.
  234. Operating-specific questions (e.g., about Windows NT / 95 / 3.x, UNIX, etc.)
  235. should go to an operating-system-specific newsgroup (see below), not to
  236. comp.lang.c++.
  237.  
  238. Here are some other potentially relevant newsgroups:
  239.  * comp.lang.c++.moderated
  240.    - A moderated variant of comp.lang.c++
  241.    - The moderator's job is to keep the signal-to-noise ratio higher than in
  242.      comp.lang.c++
  243.  * comp.object
  244.    - Mostly OO design issues, with less emphasis on OO programming)
  245.    - That group's FAQ contains an excellent introduction to OO along with an
  246.      overview of OO terms and concepts
  247.  * comp.std.c++
  248.    - Discussion directly related to the evolving ANSI/ISO C++ standard
  249.    - The evolving ANSI/ISO C++ standard is discussed below
  250.  * comp.os.ms-windows.programmer.tools.*
  251.    - This group is intended for discussions about the selection and use of
  252.      tools for Windows software development
  253.  * comp.os.ms-windows.programmer.misc
  254.    - This group is for all other discussions about Windows software development
  255.    - There's one FAQ list for all the comp.os.ms-windows.programmer.* groups
  256.    - Sample topic: Accessing C++ classes in a DLL
  257.    - Sample topic: A dialog as an MDI child window [with OWL]
  258.    - Sample topic: Disabled menu choices become enabled [with MFC]
  259.    - Sample topic: Using STRICT with windows.h
  260.    - Sample topic: A programmer's bibliography
  261.  * comp.os.msdos.programmer
  262.    - Much of the traffic is about language products, chiefly from Borland and
  263.      Microsoft
  264.    - Note: The FAQ for this group is not available at rtfm.mit.edu; it is at
  265.      ftp://oak.oakland.edu/pub/msdos/info and ftp://garbo.uwasa.fi/pc/doc-net
  266.    - Sample topic: How can I read a character without [waiting for] the Enter
  267.      key?
  268.    - Sample topic: How can I read, create, change, or delete the volume label?
  269.    - Sample topic: How do I configure a COM port and use it to transmit data?
  270.    - Sample topic: How can a C program send control codes to my printer?
  271.    - Sample topic: How can I find the Microsoft mouse position and button
  272.      status?
  273.    - Sample topic: How can I write a TSR (terminate-stay-resident) utility?
  274.    - Sample topic: How can I contact [Borland, Microsoft]?
  275.  * comp.os.msdos.programmer.turbovision
  276.    - Borland's character-mode framework
  277.  * comp.unix.programmer
  278.    - Sample topic: How do I use popen() to open a process for reading and
  279.      writing?
  280.    - Sample topic: How do I sleep() in a C program for less than one second?
  281.  * comp.unix.solaris
  282.    - Covers SunOS 4.x and Solaris
  283.    - Sample topic: Signal Primer
  284.    - Sample topic: Waiting for Children to Exit
  285.  * gnu.g++.help
  286.    - Sample topic: Where can I find a demangler?
  287.    - Sample topic: Getting gcc/g++ binaries for Solaris 2.x
  288.    - Sample topic: What documentation exists for g++ 2.x?
  289.  * comp.sys.mac.programmer.* and comp.sys.mac.oop.*
  290.    - Macintosh issues
  291.  * gnu.g++.bug
  292.    - Bug reports for g++; see the g++ docs
  293.  * comp.lang.c
  294.    - FAQ is posted monthly, and is maintained by Steve Summit
  295.    - Sample topic: I'm confused.  NULL is guaranteed to be 0, but the null
  296.      pointer is not?
  297.    - Sample topic: So what is meant by the "equivalence of pointers and arrays"
  298.      in C?
  299.    - Sample topic: Why doesn't printf("%d\n", i++ * i++); work?
  300.    - Sample topic: How can I write a function that takes a variable number of
  301.      arguments? [stdarg.h or varargs.h]
  302.    - Sample topic: How do I declare an array of pointers to functions returning
  303.      pointers to functions returning pointers to characters?
  304.  * comp.graphics
  305.    - Issues revolving around graphics programming
  306.  * comp.sources.wanted
  307.    - If you want some source code for something, post your request there
  308.  * comp.programming
  309.    - General programming issues
  310.  
  311. ==============================================================================
  312.  
  313. [5.9] How do I get the FAQs for a particular newsgroup? [UPDATED!]
  314.  
  315. [Recently added www.faqs.org thanks to Dan Kegel (on 1/00).]
  316.  
  317. Let me count the ways...
  318.  
  319. FAQs (Frequently Asked Questions lists) are available 24-hours a day via:
  320.  * The web: www.faqs.org/
  321.  * ftp: ftp://rtfm.mit.edu/pub/usenet/
  322.  * e-mail: send a message with the line "help" to mail-server@rtfm.mit.edu
  323.  * usenet: many FAQs are available in the newsgroup news.answers
  324.  
  325. Please, PLEASE do not send e-mail to me!
  326.  
  327. ==============================================================================
  328.  
  329. SECTION [6]: Big Picture issues
  330.  
  331.  
  332. [6.1] Is C++ a practical language?
  333.  
  334. Yes.
  335.  
  336. C++ is a practical tool.  It's not perfect[6.2], but it's useful.
  337.  
  338. In the world of industrial software, C++ is viewed as a solid, mature,
  339. mainstream tool.  It has widespread industry support which makes it "good" from
  340. an overall business perspective.
  341.  
  342. ==============================================================================
  343.  
  344. [6.2] Is C++ a perfect language?
  345.  
  346. Nope.
  347.  
  348. C++ wasn't designed to demonstrate what a perfect OO language looks like.  It
  349. was designed to be a practical tool for solving real world problems.  It has a
  350. few warts, but the only place where it's appropriate to keep fiddling with
  351. something until it's perfect is in a pure academic setting.  That wasn't C++'s
  352. goal.
  353.  
  354. ==============================================================================
  355.  
  356. [6.3] What's the big deal with OO?
  357.  
  358. Object-oriented techniques are the best way we know of to develop large,
  359. complex software applications and systems.
  360.  
  361. OO hype: the software industry is "failing" to meet demands for large, complex
  362. software systems.  But this "failure" is actually due to our successes: our
  363. successes have propelled users to ask for more.  Unfortunately we created a
  364. market hunger that the "structured" analysis, design and programming techniques
  365. couldn't satisfy.  This required us to create a better paradigm.
  366.  
  367. C++ is an OO programming language.  C++ can also be used as a traditional
  368. programming language (as "as a better C").  However if you use it "as a better
  369. C," don't expect to get the benefits of object-oriented programming.
  370.  
  371. ==============================================================================
  372.  
  373. [6.4] Is C++ better than Ada? (or Visual Basic, C, FORTRAN, Pascal, Smalltalk,
  374.       or any other language?)
  375.  
  376. This question generates much much more heat than light.  Please read the
  377. following before posting some variant of this question.
  378.  
  379. In 99% of the cases, programming language selection is dominated by business
  380. considerations, not by technical considerations.  Things that really end up
  381. mattering are things like availability of a programming environment for the
  382. development machine, availability of runtime environment(s) for the deployment
  383. machine(s), licensing/legal issues of the runtime and/or development
  384. environments, availability of trained developers, availability of consulting
  385. services, and corporate culture/politics.  These business considerations
  386. generally play a much greater role than compile time performance, runtime
  387. performance, static vs. dynamic typing, static vs. dynamic binding, etc.
  388.  
  389. Anyone who argues in favor of one language over another in a purely technical
  390. manner (i.e., who ignores the dominant business issues) exposes themself as a
  391. techie weenie, and deserves not to be heard.
  392.  
  393. ==============================================================================
  394.  
  395. [6.5] Who uses C++?
  396.  
  397. Lots and lots of companies and government sites.  Lots.
  398.  
  399. The number of C++ developers increases 20-30% every year.  You can imagine that
  400. five people are becoming C++ developers while you read this FAQ.
  401.  
  402. Growth is one of several critical features of C++[6.7].
  403.  
  404. ==============================================================================
  405.  
  406. [6.6] How long does it take to learn OO/C++?
  407.  
  408. Companies successfully teach standard industry "short courses," where a
  409. university semester course is compressed into one 40 hour work week.  But
  410. regardless of where you get your training, make sure the courses have a
  411. hands-on element, since most people learn best when they have projects to help
  412. the concepts "gel." But even if they have the best training, they're not ready
  413. yet.
  414.  
  415. It takes 6-12 months to become proficient in OO/C++.  Less if the developers
  416. have easy access to a "local" body of experts, more if there isn't a "good"
  417. general purpose C++ class library available.  To become one of these experts
  418. who can mentor others takes around 3 years.
  419.  
  420. Some people never make it.  You don't have a chance unless you are teachable
  421. and have personal drive.  As a bare minimum on "teachability," you have to be
  422. able to admit when you've been wrong.  As a bare minimum on "drive," you must
  423. be willing to put in some extra hours (it's a lot easier to learn some new
  424. facts than it is to change your paradigm [i.e., to change the way you think; to
  425. change your notion of goodness; to change your mental model of the world of
  426. technology]).
  427.  
  428. Two things you should do:
  429.  * Bring in a "mentor"[26.1]
  430.  * Get your people two books: one to tell them what is legal[26.6], another to
  431.    tell them what is moral[26.5]
  432.  
  433. Two things you should not do:
  434.  * You should not bother having your people trained in C as a stepping-stone to
  435.    learning OO/C++[26.2]
  436.  * You should not bother having your people trained in Smalltalk as a
  437.    stepping-stone to learning OO/C++[26.3]
  438.  
  439. ==============================================================================
  440.  
  441. [6.7] What are some features of C++ from a business perspective?
  442.  
  443. Here are a few features of OO/C++ from a business perspective:
  444.  * C++ has a huge installed base[6.5], which means you'll have multi-vendor
  445.    support for tools, environments, consulting services, etc.[6.4], plus you'll
  446.    have a very valuable line-item on your resume
  447.  * C++ lets developers provide simplified interfaces[7.3] to software chunks,
  448.    which improves the defect-rate when those chunks are (re)used
  449.  * C++ lets you exploit developer's intuition through operator
  450.    overloading[13.2], which reduces the learning curve for (re)users
  451.  * C++ localizes access[7.4] to a software chunk, which reduces the cost of
  452.    changes.
  453.  * C++ reduces the safety-vs.-usability tradeoff[7.5], which improves the cost
  454.    of (re)using a chunk of software.
  455.  * C++ reduces the safety-vs.-speed tradeoff[9.2], which improves defect rates
  456.    without degrading performance.
  457.  * C++ gives you inheritance and dynamic binding[6.8] which let old code call
  458.    new code[6.9], making it possible to quickly extend/adapt your software to
  459.    hit narrow market windows.
  460.  
  461. ==============================================================================
  462.  
  463. [6.8] Are virtual functions (dynamic binding) central to OO/C++? [UPDATED!]
  464.  
  465. [Recently reworded the second paragraph thanks to Stan Brown (on 1/00).]
  466.  
  467. Yes!
  468.  
  469. Without virtual functions[20], C++ wouldn't be object-oriented.  Operator
  470. overloading[13] and non-virtual member functions are great, but they are, after
  471. all, just syntactic sugar for the more typical C notion of passing a pointer to
  472. a struct to a function.  STL and other "generic programming" techniques are
  473. great too, but virtual functions are still at the heart of object-oriented
  474. programming using C++.
  475.  
  476. From a business perspective, there is very little reason to switch from
  477. straight C to C++ without virtual functions (we'll ignore generic programming
  478. and STL in this FAQ).  Technical people often think that there is a large
  479. difference between C and non-OO C++, but without OO, difference usually isn't
  480. enough to justify the cost of training developers, new tools, etc.  In other
  481. words, if I were to advise a manager regarding whether to switch from C to
  482. non-OO C++ (i.e., to switch languages but not paradigms), I'd probably
  483. discourage him or her unless there were compelling tool-oriented reasons.  From
  484. a business perspective, OO can help make systems extensible andadaptable, but
  485. just the syntax of C++ classes without OO may not even reduce the maintenance
  486. cost, and it surely adds to the training cost significantly.
  487.  
  488. Bottom line: C++ without virtual is not OO.  Programming with classes but
  489. without dynamic binding is called "object based," but not "object oriented."
  490. Throwing out virtual functions is the same as throwing out OO.  All you have
  491. left is object-based programming, similar to the original Ada language (the new
  492. Ada language, by the way, supports true OO rather than just object-based
  493. programming).
  494.  
  495. ==============================================================================
  496.  
  497. [6.9] I'm from Missouri.  Can you give me a simple reason why virtual functions
  498.       (dynamic binding) make a big difference?
  499.  
  500. Overview: Dynamic binding can improve reuse by letting old code call new code.
  501.  
  502. Before OO came along, reuse was accomplished by having new code call old code.
  503. For example, a programmer might write some code that called some reusable code
  504. such as printf().
  505.  
  506. With OO, reuse can also be accomplished by having old code call new code.  For
  507. example, a programmer might write some code that is called by a framework that
  508. was written by their great, great grandfather.  There's no need to change
  509. great-great-grandpa's code.  In fact, it doesn't even need to be recompiled.
  510. Even if all you have left is the object file and the source code that
  511. great-great-grandpa wrote was lost 25 years ago, that ancient object file will
  512. call the new extension without anything falling apart.
  513.  
  514. That is extensibility, and that is OO.
  515.  
  516. ==============================================================================
  517.  
  518. [6.10] Is C++ backward compatible with ANSI/ISO-C?
  519.  
  520. Almost.
  521.  
  522. C++ is as close as possible to compatible with C, but no closer.  In practice,
  523. the major difference is that C++ requires prototypes, and that f() declares a
  524. function that takes no parameters (in C, f() is the same as f(...)).
  525.  
  526. There are some very subtle differences as well, like sizeof('x') is equal to
  527. sizeof(char) in C++ but is equal to sizeof(int) in C.  Also, C++ puts structure
  528. "tags" in the same namespace as other names, whereas C requires an explicit
  529. struct (e.g., the typedef struct Fred Fred; technique still works, but is
  530. redundant in C++).
  531.  
  532. ==============================================================================
  533.  
  534. [6.11] Is C++ standardized? [UPDATED!]
  535.  
  536. [Recently changed "American National Standards Organization" to "American
  537. National Standards Institute" thanks to Mark Jones; also reworded first
  538. paragraph thanks to Stan Brown (on 1/00).]
  539.  
  540. Yes.
  541.  
  542. The C++ standard was finalized and adopted by ISO (International Organization
  543. for Standardization) as well as several national standards organizations such
  544. as ANSI (The American National Standards Institute), BSI (The British Standards
  545. Institute), DIN (The German National Standards Organization).  The ISO standard
  546. has been finalized and adopted by unanimous vote November 14, 1997.
  547.  
  548. The ANSI-C++ committee is called "X3J16".  The ISO C++ standards group is
  549. called "WG21".  The major players in the ANSI/ISO C++ standards process
  550. includes just about everyone: representatives from Australia, Canada, Denmark,
  551. France, Germany, Ireland, Japan, the Netherlands, New Zealand, Sweden, the UK,
  552. and the USA, along with representatives from about a hundred companies and many
  553. interested individuals.  Major players include AT&T, Ericsson, Digital,
  554. Borland, Hewlett Packard, IBM, Mentor Graphics, Microsoft, Silicon Graphics,
  555. Sun Microsystems, and Siemens.  After about 8 years of work, this standard is
  556. now complete.  On November 14, 1997, the standard was approved by a unanimous
  557. vote of the countries that had representatives present in Morristown.
  558.  
  559. ==============================================================================
  560.  
  561. [6.12] Where can I get a copy of the ANSI/ISO C++ standard? [UPDATED!]
  562.  
  563. [Recently changed the URL for the electronic copy of the Standard thanks to
  564. Wolfgang Haefelinger (on 3/00).]
  565.  
  566. You can get a paper copy of the standard from the National Committee for
  567. Information Technology Standards (NCITS, pronounced "insights"; this is the new
  568. name of the organization that used to be called "X3").  The contact person is
  569. Monica Vega, 202-626-5739 or 202-626-5738.  Ask for document FDC 14882, and be
  570. prepared to pay some money -- the document is not free.  Documents from NCITS
  571. are typically shipped 2-day FedEx within the continental US.
  572.  
  573. You can also get a paper copy via the web (cost (US dollars): $175): go to
  574. www.ansi.org, choose Catalogs/Standards Information, then choose "ANSI-ISO-IEC
  575. Online Catalog".  Search for "14882".  The document you're looking for is
  576. designated "ISO/IEC 14882-1998," with title "Information Technology -
  577. Programming Languages - C++."
  578.  
  579. You can also download an electronic copy via the web (it's a 2.5MB PDF file;
  580. cost (US dollars): $18): go to
  581. webstore.ansi.org/product.asp?sku=ISO%2FIEC+14882%2D1998.  To read the
  582. document, download the Adobe Acrobat reader.
  583.  
  584. Finally, you can read the ISO committee's press release here
  585. <http://www.research.att.com/~bs/iso_release.html>.  This press release is
  586. readable by non-programmers.
  587.  
  588. ==============================================================================
  589.  
  590. SECTION [7]: Classes and objects
  591.  
  592.  
  593. [7.1] What is a class?
  594.  
  595. The fundamental building block of OO software.
  596.  
  597. A class defines a data type, much like a struct would be in C.  In a computer
  598. science sense, a type consists of both a set of states and a set of operations
  599. which transition between those states.  Thus int is a type because it has both
  600. a set of states and it has operations like i + j or i++, etc.  In exactly the
  601. same way, a class provides a set of (usually public:) operations, and a set of
  602. (usually non-public:) data bits representing the abstract values that instances
  603. of the type can have.
  604.  
  605. You can imagine that int is a class that has member functions called
  606. operator++, etc. (int isn't really a class, but the basic analogy is this: a
  607. class is a type, much like int is a type.)
  608.  
  609. Note: a C programmer can think of a class as a C struct whose members default
  610. to private.  But if that's all you think of a class, then you probably need to
  611. experience a personal paradigm shift.
  612.  
  613. ==============================================================================
  614.  
  615. [7.2] What is an object?
  616.  
  617. A region of storage with associated semantics.
  618.  
  619. After the declaration int i; we say that "i is an object of type int." In
  620. OO/C++, "object" usually means "an instance of a class." Thus a class defines
  621. the behavior of possibly many objects (instances).
  622.  
  623. ==============================================================================
  624.  
  625. [7.3] When is an interface "good"?
  626.  
  627. When it provides a simplified view of a chunk of software, and it is expressed
  628. in the vocabulary of a user (where a "chunk" is normally a class or a tight
  629. group of classes[14.2], and a "user" is another developer rather than the
  630. ultimate customer).
  631.  * The "simplified view" means unnecessary details are intentionally hidden.
  632.    This reduces the user's defect-rate.
  633.  * The "vocabulary of users" means users don't need to learn a new set of words
  634.    and concepts.  This reduces the user's learning curve.
  635.  
  636. ==============================================================================
  637.  
  638. [7.4] What is encapsulation?
  639.  
  640. Preventing unauthorized access to some piece of information or functionality.
  641.  
  642. The key money-saving insight is to separate the volatile part of some chunk of
  643. software from the stable part.  Encapsulation puts a firewall around the chunk,
  644. which prevents other chunks from accessing the volatile parts; other chunks can
  645. only access the stable parts.  This prevents the other chunks from breaking if
  646. (when!) the volatile parts are changed.  In context of OO software, a "chunk"
  647. is normally a class or a tight group of classes[14.2].
  648.  
  649. The "volatile parts" are the implementation details.  If the chunk is a single
  650. class, the volatile part is normally encapsulated using the private: and/or
  651. protected: keywords[19.5].  If the chunk is a tight group of classes[14.2],
  652. encapsulation can be used to deny access to entire classes in that group.
  653. Inheritance[19] can also be used as a form of encapsulation[22.2].
  654.  
  655. The "stable parts" are the interfaces.  A good interface provides a simplified
  656. view in the vocabulary of a user[7.3], and is designed from the
  657. outside-in[13.10] (here a "user" means another developer, not the end-user who
  658. buys the completed application).  If the chunk is a single class, the interface
  659. is simply the class's public: member functions and friend[14] functions.  If
  660. the chunk is a tight group of classes[14.2], the interface can include several
  661. of the classes in the chunk.
  662.  
  663. Designing a clean interface and separating that interface from its
  664. implementation[22.1] merely allows users to use the interface.  But
  665. encapsulating (putting "in a capsule") the implementation forces users to use
  666. the interface.
  667.  
  668. ==============================================================================
  669.  
  670. [7.5] How does C++ help with the tradeoff of safety vs. usability?
  671.  
  672. In C, encapsulation[7.4] was accomplished by making things static in a
  673. compilation unit or module.  This prevented another module from accessing the
  674. static stuff.  (By the way, that use is now deprecated: don't do that in C++.)
  675.  
  676. Unfortunately this approach doesn't support multiple instances of the data,
  677. since there is no direct support for making multiple instances of a module's
  678. static data.  If multiple instances were needed in C, programmers typically
  679. used a struct.  But unfortunately C structs don't support encapsulation[7.4].
  680. This exacerbates the tradeoff between safety (information hiding) and usability
  681. (multiple instances).
  682.  
  683. In C++, you can have both multiple instances and encapsulation via a class.
  684. The public: part of a class contains the class's interface, which normally
  685. consists of the class's public: member functions and its friend[14] functions.
  686. The private: and/or protected:[19.5] parts of a class contain the class's
  687. implementation, which is typically where the data lives.
  688.  
  689. The end result is like an "encapsulated struct." This reduces the tradeoff
  690. between safety (information hiding) and usability (multiple instances).
  691.  
  692. ==============================================================================
  693.  
  694. [7.6] How can I prevent other programmers from violating encapsulation by
  695.       seeing the private parts of my class?
  696.  
  697. Not worth the effort -- encapsulation is for code, not people.
  698.  
  699. It doesn't violate encapsulation for a programmer to see the private: and/or
  700. protected:[19.5] parts of your class, so long as they don't write code that
  701. somehow depends on what they saw.  In other words, encapsulation doesn't
  702. prevent people from knowing about the inside of a class; it prevents the code
  703. they write from becoming dependent on the insides of the class.  Your company
  704. doesn't have to pay a "maintenance cost" to maintain the gray matter between
  705. your ears; but it does have to pay a maintenance cost to maintain the code that
  706. comes out of your finger tips.  What you know as a person doesn't increase
  707. maintenance cost, provided the code they write depends on the interface rather
  708. than the implementation.
  709.  
  710. Besides, this is rarely if ever a problem.  I don't know any programmers who
  711. have intentionally tried to access the private parts of a class.  "My
  712. recommendation in such cases would be to change the programmer, not the code"
  713. [James Kanze; used with permission].
  714.  
  715. ==============================================================================
  716.  
  717. [7.7] Is Encapsulation a Security device?
  718.  
  719. No.
  720.  
  721. Encapsulation != security.
  722.  
  723. Encapsulation prevents mistakes, not espionage.
  724.  
  725. ==============================================================================
  726.  
  727. [7.8] What's the difference between the keywords struct and class?
  728.  
  729. The members and base classes of a struct are public by default, while in class,
  730. they default to private.  Note: you should make your base classes explicitly
  731. public, private, or protected, rather than relying on the defaults.
  732.  
  733. struct and class are otherwise functionally equivalent.
  734.  
  735. OK, enough of that squeaky clean techno talk.  Emotionally, most developers
  736. make a strong distinction between a class and a struct.  A struct simply feels
  737. like an open pile of bits with very little in the way of encapsulation or
  738. functionality.  A class feels like a living and responsible member of society
  739. with intelligent services, a strong encapsulation barrier, and a well defined
  740. interface.  Since that's the connotation most people already have, you should
  741. probably use the struct keyword if you have a class that has very few methods
  742. and has public data (such things do exist in well designed systems!), but
  743. otherwise you should probably use the class keyword.
  744.  
  745. ==============================================================================
  746.  
  747. SECTION [8]: References
  748.  
  749.  
  750. [8.1] What is a reference?
  751.  
  752. An alias (an alternate name) for an object.
  753.  
  754. References are frequently used for pass-by-reference:
  755.  
  756.     void swap(int& i, int& j)
  757.     {
  758.       int tmp = i;
  759.       i = j;
  760.       j = tmp;
  761.     }
  762.  
  763.     int main()
  764.     {
  765.       int x, y;
  766.       // ...
  767.       swap(x,y);
  768.     }
  769.  
  770. Here i and j are aliases for main's x and y respectively.  In other words, i is
  771. x -- not a pointer to x, nor a copy of x, but x itself.  Anything you do to i
  772. gets done to x, and vice versa.
  773.  
  774. OK.  That's how you should think of references as a programmer.  Now, at the
  775. risk of confusing you by giving you a different perspective, here's how
  776. references are implemented.  Underneath it all, a reference i to object x is
  777. typically the machine address of the object x.  But when the programmer says
  778. i++, the compiler generates code that increments x.  In particular, the address
  779. bits that the compiler uses to find x are not changed.  A C programmer will
  780. think of this as if you used the C style pass-by-pointer, with the syntactic
  781. variant of (1) moving the & from the caller into the callee, and (2)
  782. eliminating the *s.  In other words, a C programmer will think of i as a macro
  783. for (*p), where p is a pointer to x (e.g., the compiler automatically
  784. dereferences the underlying pointer; i++ is changed to (*p)++; i = 7 is
  785. automatically changed to *p = 7).
  786.  
  787. Important note: Even though a reference is often implemented using an address
  788. in the underlying assembly language, please do not think of a reference as a
  789. funny looking pointer to an object.  A reference is the object.  It is not a
  790. pointer to the object, nor a copy of the object.  It is the object.
  791.  
  792. ==============================================================================
  793.  
  794. [8.2] What happens if you assign to a reference?
  795.  
  796. You change the state of the referent (the referent is the object to which the
  797. reference refers).
  798.  
  799. Remember: the reference is the referent, so changing the reference changes the
  800. state of the referent.  In compiler writer lingo, a reference is an "lvalue"
  801. (something that can appear on the left hand side of an assignment operator).
  802.  
  803. ==============================================================================
  804.  
  805. [8.3] What happens if you return a reference?
  806.  
  807. The function call can appear on the left hand side of an assignment operator.
  808.  
  809. This ability may seem strange at first.  For example, no one thinks the
  810. expression f() = 7 makes sense.  Yet, if a is an object of class Array, most
  811. people think that a[i] = 7 makes sense even though a[i] is really just a
  812. function call in disguise (it calls Array::operator[](int), which is the
  813. subscript operator for class Array).
  814.  
  815.     class Array {
  816.     public:
  817.       int size() const;
  818.       float& operator[] (int index);
  819.       // ...
  820.     };
  821.  
  822.     int main()
  823.     {
  824.       Array a;
  825.       for (int i = 0; i < a.size(); ++i)
  826.         a[i] = 7;    // This line invokes Array::operator[](int)
  827.     }
  828.  
  829. ==============================================================================
  830.  
  831. [8.4] How can you reseat a reference to make it refer to a different object?
  832.  
  833. No way.
  834.  
  835. You can't separate the reference from the referent.
  836.  
  837. Unlike a pointer, once a reference is bound to an object, it can not be
  838. "reseated" to another object.  The reference itself isn't an object (it has no
  839. identity; taking the address of a reference gives you the address of the
  840. referent; remember: the reference is its referent).
  841.  
  842. In that sense, a reference is similar to a const pointer[18.5] such as
  843. int* const p (as opposed to a pointer to const[18.4] such as const int* p).  In
  844. spite of the gross similarity, please don't confuse references with pointers;
  845. they're not at all the same.
  846.  
  847. ==============================================================================
  848.  
  849. [8.5] When should I use references, and when should I use pointers?
  850.  
  851. Use references when you can, and pointers when you have to.
  852.  
  853. References are usually preferred over pointers whenever you don't need
  854. "reseating"[8.4].  This usually means that references are most useful in a
  855. class's public interface.  References typically appear on the skin of an
  856. object, and pointers on the inside.
  857.  
  858. The exception to the above is where a function's parameter or return value
  859. needs a "sentinel" reference.  This is usually best done by returning/taking a
  860. pointer, and giving the NULL pointer this special significance (references
  861. should always alias objects, not a dereferenced NULL pointer).
  862.  
  863. Note: Old line C programmers sometimes don't like references since they provide
  864. reference semantics that isn't explicit in the caller's code.  After some C++
  865. experience, however, one quickly realizes this is a form of information hiding,
  866. which is an asset rather than a liability.  E.g., programmers should write code
  867. in the language of the problem rather than the language of the machine.
  868.  
  869. ==============================================================================
  870.  
  871. SECTION [9]: Inline functions
  872.  
  873.  
  874. [9.1] What's the deal with inline functions?
  875.  
  876. An inline function is a function whose code gets inserted into the caller's
  877. code stream.  Like a #define macro, inline functions improve performance by
  878. avoiding the overhead of the call itself and (especially!) by the compiler
  879. being able to optimize through the call ("procedural integration").
  880.  
  881. ==============================================================================
  882.  
  883. [9.2] How can inline functions help with the tradeoff of safety vs. speed?
  884.  
  885. In straight C, you can achieve "encapsulated structs" by putting a void* in a
  886. struct, in which case the void* points to the real data that is unknown to
  887. users of the struct.  Therefore users of the struct don't know how to interpret
  888. the stuff pointed to by the void*, but the access functions cast the void* to
  889. the approprate hidden type.  This gives a form of encapsulation.
  890.  
  891. Unfortunately it forfeits type safety, and also imposes a function call to
  892. access even trivial fields of the struct (if you allowed direct access to the
  893. struct's fields, anyone and everyone would be able to get direct access since
  894. they would of necessity know how to interpret the stuff pointed to by the
  895. void*; this would make it difficult to change the underlying data structure).
  896.  
  897. Function call overhead is small, but can add up.  C++ classes allow function
  898. calls to be expanded inline.  This lets you have the safety of encapsulation
  899. along with the speed of direct access.  Furthermore the parameter types of
  900. these inline functions are checked by the compiler, an improvement over C's
  901. #define macros.
  902.  
  903. ==============================================================================
  904.  
  905. [9.3] Why should I use inline functions? Why not just use plain old #define
  906.       macros? [UPDATED!]
  907.  
  908. [Recently added cross references to other evilness of macros (on 3/00).]
  909.  
  910. Because #define macros are evil[9.3], evil[34.1], evil[34.2], evil[34.3].
  911.  
  912. Unlike #define macros, inline functions avoid infamous macro errors since
  913. inline functions always evaluate every argument exactly once.  In other words,
  914. invoking an inline function is semantically just like invoking a regular
  915. function, only faster:
  916.  
  917.     // A macro that returns the absolute value of i
  918.     #define unsafe(i)  \
  919.             ( (i) >= 0 ? (i) : -(i) )
  920.  
  921.     // An inline function that returns the absolute value of i
  922.     inline
  923.     int safe(int i)
  924.     {
  925.       return i >= 0 ? i : -i;
  926.     }
  927.  
  928.     int f();
  929.  
  930.     void userCode(int x)
  931.     {
  932.       int ans;
  933.  
  934.       ans = unsafe(x++);   // Error! x is incremented twice
  935.       ans = unsafe(f());   // Danger! f() is called twice
  936.  
  937.       ans = safe(x++);     // Correct! x is incremented once
  938.       ans = safe(f());     // Correct! f() is called once
  939.     }
  940.  
  941. Also unlike macros, argument types are checked, and necessary conversions are
  942. performed correctly.
  943.  
  944. Macros are bad for your health; don't use them unless you have to.
  945.  
  946. ==============================================================================
  947.  
  948. [9.4] How do you tell the compiler to make a non-member function inline?
  949.  
  950. When you declare an inline function, it looks just like a normal function:
  951.  
  952.     void f(int i, char c);
  953.  
  954. But when you define an inline function, you prepend the function's definition
  955. with the keyword inline, and you put the definition into a header file:
  956.  
  957.     inline
  958.     void f(int i, char c)
  959.     {
  960.       // ...
  961.     }
  962.  
  963. Note: It's imperative that the function's definition (the part between the
  964. {...}) be placed in a header file, unless the function is used only in a single
  965. .cpp file.  In particular, if you put the inline function's definition into a
  966. .cpp file and you call it from some other .cpp file, you'll get an "unresolved
  967. external" error from the linker.
  968.  
  969. ==============================================================================
  970.  
  971. [9.5] How do you tell the compiler to make a member function inline?
  972.  
  973. When you declare an inline member function, it looks just like a normal member
  974. function:
  975.  
  976.     class Fred {
  977.     public:
  978.       void f(int i, char c);
  979.     };
  980.  
  981. But when you define an inline member function, you prepend the member
  982. function's definition with the keyword inline, and you put the definition into
  983. a header file:
  984.  
  985.     inline
  986.     void Fred::f(int i, char c)
  987.     {
  988.       // ...
  989.     }
  990.  
  991. It's usually imperative that the function's definition (the part between the
  992. {...}) be placed in a header file.  If you put the inline function's definition
  993. into a .cpp file, and if it is called from some other .cpp file, you'll get an
  994. "unresolved external" error from the linker.
  995.  
  996. ==============================================================================
  997.  
  998. [9.6] Is there another way to tell the compiler to make a member function
  999.       inline?
  1000.  
  1001. Yep: define the member function in the class body itself:
  1002.  
  1003.     class Fred {
  1004.     public:
  1005.       void f(int i, char c)
  1006.         {
  1007.           // ...
  1008.         }
  1009.     };
  1010.  
  1011. Although this is easier on the person who writes the class, it's harder on all
  1012. the readers since it mixes "what" a class does with "how" it does them.
  1013. Because of this mixture, we normally prefer to define member functions outside
  1014. the class body with the inline keyword[9.5].  The insight that makes sense of
  1015. this: in a reuse-oriented world, there will usually be many people who use your
  1016. class, but there is only one person who builds it (yourself); therefore you
  1017. should do things that favor the many rather than the few.
  1018.  
  1019. ==============================================================================
  1020.  
  1021. [9.7] Are inline functions guaranteed to make your performance better?
  1022.  
  1023. Nope.
  1024.  
  1025. Beware that overuse of inline functions can cause code bloat, which can in turn
  1026. have a negative performance impact in paging environments.
  1027.  
  1028. ==============================================================================
  1029.  
  1030. -- 
  1031. Marshall Cline / 972-931-9470 / mailto:cline@parashift.com
  1032.