home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / C++-faq / part8 < prev   
Text File  |  2000-03-01  |  54KB  |  1,119 lines

  1. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!howland.erols.net!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 8 of 10)
  5. Followup-To: comp.lang.c++
  6. Date: 29 Feb 2000 20:07:15 GMT
  7. Organization: ATT Cerfnet
  8. Lines: 1098
  9. Approved: news-answers-request@mit.edu
  10. Distribution: world
  11. Expires: +1 month
  12. Message-ID: <89h8tj$bu3$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 951854835 12227 192.215.81.88 (29 Feb 2000 20:07:15 GMT)
  16. X-Complaints-To: abuse@cerf.net
  17. NNTP-Posting-Date: 29 Feb 2000 20:07:15 GMT
  18. Summary: Please read this before posting to comp.lang.c++
  19. Xref: senator-bedfellow.mit.edu comp.lang.c++:453818 comp.answers:39858 news.answers:178217 alt.comp.lang.learn.c-c++:40796
  20.  
  21. Archive-name: C++-faq/part8
  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 [24]: Inheritance -- private and protected inheritance
  46.  
  47.  
  48. [24.1] How do you express "private inheritance"?
  49.  
  50. When you use : private instead of : public.  E.g.,
  51.  
  52.     class Foo : private Bar {
  53.     public:
  54.       // ...
  55.     };
  56.  
  57. ==============================================================================
  58.  
  59. [24.2] How are "private inheritance" and "composition" similar?
  60.  
  61. private inheritance is a syntactic variant of composition (has-a).
  62.  
  63. E.g., the "Car has-a Engine" relationship can be expressed using composition:
  64.  
  65.     class Engine {
  66.     public:
  67.       Engine(int numCylinders);
  68.       void start();                 // Starts this Engine
  69.     };
  70.  
  71.     class Car {
  72.     public:
  73.       Car() : e_(8) { }             // Initializes this Car with 8 cylinders
  74.       void start() { e_.start(); }  // Start this Car by starting its Engine
  75.     private:
  76.       Engine e_;                    // Car has-a Engine
  77.     };
  78.  
  79. The same "has-a" relationship can also be expressed using private inheritance:
  80.  
  81.     class Car : private Engine {    // Car has-a Engine
  82.     public:
  83.       Car() : Engine(8) { }         // Initializes this Car with 8 cylinders
  84.       Engine::start;                // Start this Car by starting its Engine
  85.     };
  86.  
  87. There are several similarities between these two forms of composition:
  88.  * In both cases there is exactly one Engine member object contained in a Car
  89.  * In neither case can users (outsiders) convert a Car* to an Engine*
  90.  
  91. There are also several distinctions:
  92.  * The first form is needed if you want to contain several Engines per Car
  93.  * The second form can introduce unnecessary multiple inheritance
  94.  * The second form allows members of Car to convert a Car* to an Engine*
  95.  * The second form allows access to the protected members of the base class
  96.  * The second form allows Car to override Engine's virtual[20] functions
  97.  
  98. Note that private inheritance is usually used to gain access into the
  99. protected: members of the base class, but this is usually a short-term solution
  100. (translation: a band-aid[24.3]).
  101.  
  102. ==============================================================================
  103.  
  104. [24.3] Which should I prefer: composition or private inheritance?
  105.  
  106. Use composition when you can, private inheritance when you have to.
  107.  
  108. Normally you don't want to have access to the internals of too many other
  109. classes, and private inheritance gives you some of this extra power (and
  110. responsibility).  But private inheritance isn't evil; it's just more expensive
  111. to maintain, since it increases the probability that someone will change
  112. something that will break your code.
  113.  
  114. A legitimate, long-term use for private inheritance is when you want to build a
  115. class Fred that uses code in a class Wilma, and the code from class Wilma needs
  116. to invoke member functions from your new class, Fred.  In this case, Fred calls
  117. non-virtuals in Wilma, and Wilma calls (usually pure virtuals[22.4]) in itself,
  118. which are overridden by Fred.  This would be much harder to do with
  119. composition.
  120.  
  121.     class Wilma {
  122.     protected:
  123.       void fredCallsWilma()
  124.         {
  125.           cout << "Wilma::fredCallsWilma()\n";
  126.           wilmaCallsFred();
  127.         }
  128.       virtual void wilmaCallsFred() = 0;   // A pure virtual function[22.4]
  129.     };
  130.  
  131.     class Fred : private Wilma {
  132.     public:
  133.       void barney()
  134.         {
  135.           cout << "Fred::barney()\n";
  136.           Wilma::fredCallsWilma();
  137.         }
  138.     protected:
  139.       virtual void wilmaCallsFred()
  140.         {
  141.           cout << "Fred::wilmaCallsFred()\n";
  142.         }
  143.     };
  144.  
  145. ==============================================================================
  146.  
  147. [24.4] Should I pointer-cast from a private derived class to its base class?
  148.  
  149. Generally, No.
  150.  
  151. From a member function or friend[14] of a privately derived class, the
  152. relationship to the base class is known, and the upward conversion from
  153. PrivatelyDer* to Base* (or PrivatelyDer& to Base&) is safe; no cast is needed
  154. or recommended.
  155.  
  156. However users of PrivatelyDer should avoid this unsafe conversion, since it is
  157. based on a private decision of PrivatelyDer, and is subject to change without
  158. notice.
  159.  
  160. ==============================================================================
  161.  
  162. [24.5] How is protected inheritance related to private inheritance?
  163.  
  164. Similarities: both allow overriding virtual[20] functions in the
  165. private/protected base class, neither claims the derived is a kind-of its base.
  166.  
  167. Dissimilarities: protected inheritance allows derived classes of derived
  168. classes to know about the inheritance relationship.  Thus your grand kids are
  169. effectively exposed to your implementation details.  This has both benefits (it
  170. allows subclasses of the protected derived class to exploit the relationship to
  171. the protected base class) and costs (the protected derived class can't change
  172. the relationship without potentially breaking further derived classes).
  173.  
  174. Protected inheritance uses the : protected syntax:
  175.  
  176.     class Car : protected Engine {
  177.     public:
  178.       // ...
  179.     };
  180.  
  181. ==============================================================================
  182.  
  183. [24.6] What are the access rules with private and protected inheritance?
  184.  
  185. Take these classes as examples:
  186.  
  187.     class B                    { /*...*/ };
  188.     class D_priv : private   B { /*...*/ };
  189.     class D_prot : protected B { /*...*/ };
  190.     class D_publ : public    B { /*...*/ };
  191.     class UserClass            { B b; /*...*/ };
  192.  
  193. None of the subclasses can access anything that is private in B.  In D_priv,
  194. the public and protected parts of B are private.  In D_prot, the public and
  195. protected parts of B are protected.  In D_publ, the public parts of B are
  196. public and the protected parts of B are protected (D_publ is-a-kind-of-a B).
  197. class UserClass can access only the public parts of B, which "seals off"
  198. UserClass from B.
  199.  
  200. To make a public member of B so it is public in D_priv or D_prot, state the
  201. name of the member with a B:: prefix.  E.g., to make member B::f(int,float)
  202. public in D_prot, you would say:
  203.  
  204.     class D_prot : protected B {
  205.     public:
  206.       using B::f;  // Note: Not using B::f(int,float)
  207.     };
  208.  
  209. ==============================================================================
  210.  
  211. SECTION [25]: Coding standards
  212.  
  213.  
  214. [25.1] What are some good C++ coding standards?
  215.  
  216. Thank you for reading this answer rather than just trying to set your own
  217. coding standards.
  218.  
  219. But beware that some people on comp.lang.c++ are very sensitive on this issue.
  220. Nearly every software engineer has, at some point, been exploited by someone
  221. who used coding standards as a "power play." Furthermore some attempts to set
  222. C++ coding standards have been made by those who didn't know what they were
  223. talking about, so the standards end up being based on what was the
  224. state-of-the-art when the standards setters where writing code.  Such
  225. impositions generate an attitude of mistrust for coding standards.
  226.  
  227. Obviously anyone who asks this question wants to be trained so they don't run
  228. off on their own ignorance, but nonetheless posting a question such as this one
  229. to comp.lang.c++ tends to generate more heat than light.
  230.  
  231. ==============================================================================
  232.  
  233. [25.2] Are coding standards necessary? Are they sufficient?
  234.  
  235. Coding standards do not make non-OO programmers into OO programmers; only
  236. training and experience do that.  If coding standards have merit, it is that
  237. they discourage the petty fragmentation that occurs when large organizations
  238. coordinate the activities of diverse groups of programmers.
  239.  
  240. But you really want more than a coding standard.  The structure provided by
  241. coding standards gives neophytes one less degree of freedom to worry about,
  242. which is good.  However pragmatic guidelines should go well beyond
  243. pretty-printing standards.  Organizations need a consistent philosophy of
  244. design and implementation.  E.g., strong or weak typing? references or pointers
  245. in interfaces? stream I/O or stdio? should C++ code call C code? vice versa?
  246. how should ABCs[22.3] be used? should inheritance be used as an implementation
  247. technique or as a specification technique? what testing strategy should be
  248. employed? inspection strategy? should interfaces uniformly have a get() and/or
  249. set() member function for each data member? should interfaces be designed from
  250. the outside-in or the inside-out? should errors be handled by try/catch/throw
  251. or by return codes? etc.
  252.  
  253. What is needed is a "pseudo standard" for detailed design. I recommend a
  254. three-pronged approach to achieving this standardization: training,
  255. mentoring[26.1], and libraries.  Training provides "intense instruction,"
  256. mentoring allows OO to be caught rather than just taught, and high quality C++
  257. class libraries provide "long term instruction." There is a thriving commercial
  258. market for all three kinds of "training." Advice by organizations who have been
  259. through the mill is consistent: Buy, Don't Build. Buy libraries, buy training,
  260. buy tools, buy consulting.  Companies who have attempted to become a
  261. self-taught tool-shop as well as an application/system shop have found success
  262. difficult.
  263.  
  264. Few argue that coding standards are "ideal," or even "good," however they are
  265. necessary in the kind of organizations/situations described above.
  266.  
  267. The following FAQs provide some basic guidance in conventions and styles.
  268.  
  269. ==============================================================================
  270.  
  271. [25.3] Should our organization determine coding standards from our C
  272.        experience?
  273.  
  274. No!
  275.  
  276. No matter how vast your C experience, no matter how advanced your C expertise,
  277. being a good C programmer does not make you a good C++ programmer.  Converting
  278. from C to C++ is more than just learning the syntax and semantics of the ++
  279. part of C++.  Organizations who want the promise of OO, but who fail to put the
  280. "OO" into "OO programming", are fooling themselves; the balance sheet will show
  281. their folly.
  282.  
  283. C++ coding standards should be tempered by C++ experts.  Asking comp.lang.c++
  284. is a start.  Seek out experts who can help guide you away from pitfalls.  Get
  285. training.  Buy libraries and see if "good" libraries pass your coding
  286. standards.  Do not set standards by yourself unless you have considerable
  287. experience in C++.  Having no standard is better than having a bad standard,
  288. since improper "official" positions "harden" bad brain traces.  There is a
  289. thriving market for both C++ training and libraries from which to pool
  290. expertise.
  291.  
  292. One more thing: whenever something is in demand, the potential for charlatans
  293. increases.  Look before you leap.  Also ask for student-reviews from past
  294. companies, since not even expertise makes someone a good communicator.
  295. Finally, select a practitioner who can teach, not a full time teacher who has a
  296. passing knowledge of the language/paradigm.
  297.  
  298. ==============================================================================
  299.  
  300. [25.4] What's the difference between <xxx> and <xxx.h> headers? [NEW!]
  301.  
  302. [Recently created thanks to Stan Brown (on 1/00).]
  303.  
  304. The headers in ISO Standard C++ don't have a .h suffix.  This is something the
  305. standards committee changed from former practice.  The details are different
  306. between headers that existed in C and those that are specific to C++.
  307.  
  308. The C++ standard library is guaranteed to have 18 standard headers from the C
  309. language.  These headers come in two standard flavors, <cxxx> and <xxx.h>
  310. (where xxx is the basename of the header, such as stdio, stdlib, etc).  These
  311. two flavors are identical except the <cxxx> versions provide their declarations
  312. in the std namespace only, and the <xyz.h> versions make them available both in
  313. std namespace and in the global namespace.  The committee did it this way so
  314. that existing C code could continue to be compiled in C++, however the <xyz.h>
  315. versions are deprecated, meaning they are standard now but might not be part of
  316. the standard in future revisions.  (See ISO clause D and subclause D.5 of the
  317. ISO C++ standard[6.12].)
  318.  
  319. The C++ standard library is also guaranteed to have 32 additional standard
  320. headers that have no direct counterparts in C, such as <iostream>, <string>,
  321. and <new>.  You may see things like #include <iostream.h> and so on in old
  322. code, and some compiler vendors offer .h versions for that reason.  But be
  323. careful: the .h versions, if available, may differ from the standard versions.
  324. And if you compile some units of a program with, for example, <iostream> and
  325. others with <iostream.h>, the program may not work.
  326.  
  327. For new projects, use only the <xxx> headers, not the <xxx.h> headers.
  328.  
  329. When modifying or extending existing code that uses the old header names, you
  330. should probably follow the practice in that code unless there's some important
  331. reason to switch to the standard headers (such as a facility available in
  332. standard <iostream> that was not available in the vendor's <iostream.h>).  If
  333. you need to standardize existing code, make sure to change all C++ headers in
  334. all program units including external libraries that get linked in to the final
  335. executable.
  336.  
  337. All of this affects the standard headers only.  You're free to name your own
  338. headers anything you like; see [25.8].
  339.  
  340. ==============================================================================
  341.  
  342. [25.5] Is the ?: operator evil since it can be used to create unreadable code?
  343.  
  344. No, but as always, remember that readability is one of the most important
  345. things.
  346.  
  347. Some people feel the ?: ternary operator should be avoided because they find it
  348. confusing at times compared to the good old if statement.  In many cases ?:
  349. tends to make your code more difficult to read (and therefore you should
  350. replace those usages of ?: with if statements), but there are times when the ?:
  351. operator is clearer since it can emphasize what's really happening, rather than
  352. the fact that there's an if in there somewhere.
  353.  
  354. Let's start with a really simple case.  Suppose you need to print the result of
  355. a function call.  In that case you should put the real goal (printing) at the
  356. beginning of the line, and bury the function call within the line since it's
  357. relatively incidental (this left-right thing is based on the intuitive notion
  358. that most developers think the first thing on a line is the most important
  359. thing):
  360.  
  361.     // Preferred (emphasizes the major goal -- printing):
  362.     cout << funct();
  363.  
  364.     // Not as good (emphasizes the minor goal -- a function call):
  365.     functAndPrintOn(cout);
  366.  
  367. Now let's extend this idea to the ?: operator.  Suppose your real goal is to
  368. print something, but you need to do some incidental decision logic to figure
  369. out what should be printed.  Since the printing is the most important thing
  370. conceptually, we prefer to put it first on the line, and we prefer to bury the
  371. incidental decision logic.  In the example code below, variable n represents
  372. the number of senders of a message; the message itself is being printed to
  373. cout:
  374.  
  375.     int n = /*...*/;   // number of senders
  376.  
  377.     // Preferred (emphasizes the major goal -- printing):
  378.     cout << "Please get back to " << (n==1 ? "me" : "us") << " soon!\n";
  379.  
  380.     // Not as good (emphasizes the minor goal -- a decision):
  381.     cout << "Please get back to ";
  382.     if (n==1)
  383.       cout << "me";
  384.     else
  385.       cout << "us";
  386.     cout << " soon!\n";
  387.  
  388. All that being said, you can get pretty outrageous and unreadable code ("write
  389. only code") using various combinations of ?:, &&, ||, etc.  For example,
  390.  
  391.     // Preferred (obvious meaning):
  392.     if (f())
  393.       g();
  394.  
  395.     // Not as good (harder to understand):
  396.     f() && g();
  397.  
  398. Personally I think the explicit if example is clearer since it emphasizes the
  399. major thing that's going on (a decision based on the result of calling f())
  400. rather than the minor thing (calling f()).  In other words, the use of if here
  401. is good for precisely the same reason that it was bad above: we want to major
  402. on the majors and minor on the minors.
  403.  
  404. In any event, don't forget that readability is the goal (at least it's one of
  405. the goals).  Your goal should not be to avoid certain syntactic constructs such
  406. as ?: or && or || or if -- or even goto.  If you sink to the level of a
  407. "Standards Bigot," you'll ultimately embarass yourself since there are always
  408. counterexamples to any syntax-based rule.  If on the other hand you emphasize
  409. broad goals and guidelines (e.g., "major on the majors," or "put the most
  410. important thing first on the line," or even "make sure your code is obvious and
  411. readable"), you're usually much better off.
  412.  
  413. Code must be written to be read, not by the compiler, but by another human
  414. being.
  415.  
  416. ==============================================================================
  417.  
  418. [25.6] Should I declare locals in the middle of a function or at the top?
  419.  
  420. Declare near first use.
  421.  
  422. An object is initialized (constructed) the moment it is declared.  If you don't
  423. have enough information to initialize an object until half way down the
  424. function, you should create it half way down the function when it can be
  425. initialized correctly.  Don't initialize it to an "empty" value at the top then
  426. "assign" it later.  The reason for this is runtime performance.  Building an
  427. object correctly is faster than building it incorrectly and remodeling it
  428. later.  Simple examples show a factor of 350% speed hit for simple classes like
  429. String.  Your mileage may vary; surely the overall system degradation will be
  430. less that 350%, but there will be degradation.  Unnecessary degradation.
  431.  
  432. A common retort to the above is: "we'll provide set() member functions for
  433. every datum in our objects so the cost of construction will be spread out."
  434. This is worse than the performance overhead, since now you're introducing a
  435. maintenance nightmare.  Providing a set() member function for every datum is
  436. tantamount to public data: you've exposed your implementation technique to the
  437. world.  The only thing you've hidden is the physical names of your member
  438. objects, but the fact that you're using a List and a String and a float, for
  439. example, is open for all to see.
  440.  
  441. Bottom line: Locals should be declared near their first use.  Sorry that this
  442. isn't familiar to C experts, but new doesn't necessarily mean bad.
  443.  
  444. ==============================================================================
  445.  
  446. [25.7] What source-file-name convention is best? foo.cpp? foo.C? foo.cc?
  447.  
  448. If you already have a convention, use it.  If not, consult your compiler to see
  449. what the compiler expects.  Typical answers are: .C, .cc, .cpp, or .cxx
  450. (naturally the .C extension assumes a case-sensitive file system to distinguish
  451. .C from .c).
  452.  
  453. We've often used both .cpp for our C++ source files, and we have also used .C.
  454. In the latter case, we supply the compiler option forces .c files to be treated
  455. as C++ source files (-Tdp for IBM CSet++, -cpp for Zortech C++, -P for Borland
  456. C++, etc.) when porting to case-insensitive file systems.  None of these
  457. approaches have any striking technical superiority to the others; we generally
  458. use whichever technique is preferred by our customer (again, these issues are
  459. dominated by business considerations, not by technical considerations).
  460.  
  461. ==============================================================================
  462.  
  463. [25.8] What header-file-name convention is best? foo.H? foo.hh? foo.hpp?
  464.  
  465. If you already have a convention, use it.  If not, and if you don't need your
  466. editor to distinguish between C and C++ files, simply use .h.  Otherwise use
  467. whatever the editor wants, such as .H, .hh, or .hpp.
  468.  
  469. We've tended to use either .hpp or .h for our C++ header files.
  470.  
  471. ==============================================================================
  472.  
  473. [25.9] Are there any lint-like guidelines for C++?
  474.  
  475. Yes, there are some practices which are generally considered dangerous.
  476. However none of these are universally "bad," since situations arise when even
  477. the worst of these is needed:
  478.  * A class Fred's assignment operator should return *this as a Fred& (allows
  479.    chaining of assignments)
  480.  * A class with any virtual[20] functions ought to have a virtual
  481.    destructor[20.4]
  482.  * A class with any of {destructor, assignment operator, copy constructor}
  483.    generally needs all 3
  484.  * A class Fred's copy constructor and assignment operator should have const in
  485.    the parameter: respectively Fred::Fred(const Fred&) and
  486.    Fred& Fred::operator= (const Fred&)
  487.  * When initializing an object's member objects in the constructor, always use
  488.    initialization lists rather than assignment.  The performance difference for
  489.    user-defined classes can be substantial (3x!)
  490.  * Assignment operators should make sure that self assignment[12.1] does
  491.    nothing, otherwise you may have a disaster[12.2].  In some cases, this may
  492.    require you to add an explicit test to your assignment operators[12.3].
  493.  * In classes that define both += and +, a += b and a = a + b should generally
  494.    do the same thing; ditto for the other identities of built-in types (e.g.,
  495.    a += 1 and ++a; p[i] and *(p+i); etc).  This can be enforced by writing the
  496.    binary operations using the op= forms.  E.g.,
  497.  
  498.        Fred operator+ (const Fred& a, const Fred& b)
  499.        {
  500.          Fred ans = a;
  501.          ans += b;
  502.          return ans;
  503.        }
  504.  
  505.    This way the "constructive" binary operators don't even need to be
  506. friends[14].  But it is sometimes possible to more efficiently implement common
  507. operations (e.g., if class Fred is actually String, and += has to
  508. reallocate/copy string memory, it may be better to know the eventual length
  509. from the beginning).
  510.  
  511. ==============================================================================
  512.  
  513. [25.10] Which is better: identifier names that_look_like_this or identifier
  514.         names thatLookLikeThis?
  515.  
  516. It's a precedent thing.  If you have a Pascal or Smalltalk background,
  517. youProbablySquashNamesTogether like this.  If you have an Ada background,
  518. You_Probably_Use_A_Large_Number_Of_Underscores like this.  If you have a
  519. Microsoft Windows background, you probably prefer the "Hungarian" style which
  520. means you jkuidsPrefix vndskaIdentifiers ncqWith ksldjfTheir nmdsadType.  And
  521. then there are the folks with a Unix C background, who abbr evthng n use vry
  522. srt idntfr nms.  (AND THE FORTRN PRGMRS LIMIT EVRYTH TO SIX LETTRS.)
  523.  
  524. So there is no universal standard.  If your organization has a particular
  525. coding standard for identifier names, use it.  But starting another Jihad over
  526. this will create a lot more heat than light.  From a business perspective,
  527. there are only two things that matter: The code should be generally readable,
  528. and everyone in the organization should use the same style.
  529.  
  530. Other than that, th difs r minr.
  531.  
  532. ==============================================================================
  533.  
  534. [25.11] Are there any other sources of coding standards?
  535.  
  536. Yep, there are several.
  537.  
  538. Here are a few sources that you might be able to use as starting points for
  539. developing your organization's coding standards:
  540.  * www.cs.princeton.edu/~dwallach/CPlusPlusStyle.html
  541.  * [The old URL is
  542.    <http://www.ses.com/~clarke/conventions/cppconventions_1.html> if anyone
  543.    knows the new URL, please let me know]
  544.  * www.oma.com/ottinger/Naming.html
  545.  * v2ma09.gsfc.nasa.gov/coding_standards.html
  546.  * fndaub.fnal.gov:8000/standards/standards.html
  547.  * cliffie.nosc.mil/~NAPDOC/docprj/cppcodingstd/
  548.  * www.possibility.com/cpp/
  549.     * groucho.gsfc.nasa.gov/Code_520/Code_522/Projects/DRSL/documents/templates/cpp_style_guide.html
  550.  * www.wildfire.com/~ag/Engineering/Development/C++Style/
  551.  * The Ellemtel coding guidelines are available at
  552.    - [The old URL is <http://web2.airmail.net/~rks/ellhome.htm> if anyone knows
  553.      the new URL, please let me know]
  554.    - [The old URL is <http://www.rhi.hi.is/~harri/cpprules.html> if anyone
  555.      knows the new URL, please let me know]
  556.    - [The old URL is <http://euagate.eua.ericsson.se/pub/eua/c++> if anyone
  557.      knows the new URL, please let me know]
  558.    - [The old URL is
  559.      <http://nestor.ceid.upatras.gr/programming/ellemtel/ellhome.htm> if anyone
  560.      knows the new URL, please let me know]
  561.    - www.doc.ic.ac.uk/lab/cplus/c++.rules/
  562.  
  563. Note: I do NOT warrant or endorse these URLs and/or their contents.  They are
  564. listed as a public service only.  I haven't checked their details, so I don't
  565. know if they'll help you or hurt you.  Caveat emptor.
  566.  
  567. ==============================================================================
  568.  
  569. SECTION [26]: Learning OO/C++
  570.  
  571.  
  572. [26.1] What is mentoring?
  573.  
  574. It's the most important tool in learning OO.
  575.  
  576. Object-oriented thinking is caught, not just taught.  Get cozy with someone who
  577. really knows what they're talking about, and try to get inside their head and
  578. watch them solve problems.  Listen.  Learn by emulating.
  579.  
  580. If you're working for a company, get them to bring someone in who can act as a
  581. mentor and guide.  We've seen gobs and gobs of money wasted by companies who
  582. "saved money" by simply buying their employees a book ("Here's a book; read it
  583. over the weekend; on Monday you'll be an OO developer").
  584.  
  585. ==============================================================================
  586.  
  587. [26.2] Should I learn C before I learn OO/C++?
  588.  
  589. Don't bother.
  590.  
  591. If your ultimate goal is to learn OO/C++ and you don't already know C, reading
  592. books or taking courses in C will not only waste your time, but it will teach
  593. you a bunch of things that you'll explicitly have to un-learn when you finally
  594. get back on track and learn OO/C++ (e.g., malloc()[16.3], printf()[15.1],
  595. unnecessary use of switch statements[20], error-code exception handling[17],
  596. unnecessary use of #define macros[9.3], etc.).
  597.  
  598. If you want to learn OO/C++, learn OO/C++.  Taking time out to learn C will
  599. waste your time and confuse you.
  600.  
  601. ==============================================================================
  602.  
  603. [26.3] Should I learn Smalltalk before I learn OO/C++?
  604.  
  605. Don't bother.
  606.  
  607. If your ultimate goal is to learn OO/C++ and you don't already know Smalltalk,
  608. reading books or taking courses in Smalltalk will not only waste your time, but
  609. it will teach you a bunch of things that you'll explicitly have to un-learn
  610. when you finally get back on track and learn OO/C++ (e.g., dynamic
  611. typing[27.3], non-subtyping inheritance[27.5], error-code exception
  612. handling[17], etc.).
  613.  
  614. Knowing a "pure" OO language doesn't make the transition to OO/C++ any easier.
  615. This is not a theory; we have trained and mentored literally thousands of
  616. software professionals in OO.  In fact, Smalltalk experience can make it harder
  617. for some people: they need to unlearn some rather deep notions about typing and
  618. inheritance in addition to needing to learn new syntax and idioms.  This
  619. unlearning process is especially painful and slow for those who cling to
  620. Smalltalk with religious zeal ("C++ is not like Smalltalk, therefore C++ is
  621. evil").
  622.  
  623. If you want to learn OO/C++, learn OO/C++.  Taking time out to learn Smalltalk
  624. will waste your time and confuse you.
  625.  
  626. Note: I sit on both the ANSI C++ (X3J16) and ANSI Smalltalk (X3J20)
  627. standardization committees[6.11].  I am not a language bigot[6.4].  I'm not
  628. saying C++ is better or worse than Smalltalk; I'm simply saying that they are
  629. different[27.1].
  630.  
  631. ==============================================================================
  632.  
  633. [26.4] Should I buy one book, or several?
  634.  
  635. At least two.
  636.  
  637. There are two categories of insight and knowledge in OO programming using C++.
  638. You're better off getting a "best of breed" book from each category rather than
  639. trying to find a single book that does an OK job at everything.  The two OO/C++
  640. programming categories are:
  641.  * C++ legality guides -- what you can and can't do in C++[26.6].
  642.  * C++ morality guides -- what you should and shouldn't do in C++[26.5].
  643.  
  644. Legality guides describe all language features with roughly the same level of
  645. emphasis; morality guides focus on those language features that you will use
  646. most often in typical programming tasks.  Legality guides tell you how to get a
  647. given feature past the compiler; morality guides tell you whether or not to use
  648. that feature in the first place.
  649.  
  650. Meta comments:
  651.  * Neither of these categories is optional.  You must have a good grasp of
  652.    both.
  653.  * These categories do not trade off against each other.  You shouldn't argue
  654.    in favor of one over the other.  They dove-tail.
  655.  
  656. ==============================================================================
  657.  
  658. [26.5] What are some best-of-breed C++ morality guides?
  659.  
  660. Here's my personal (subjective and selective) short-list of must-read C++
  661. morality guides, alphabetically by author:
  662.  * Cline, Lomow, and Girou, C++ FAQs, Second Edition, 587 pgs, Addison-Wesley,
  663.    1999, ISBN 0-201-30983-1.  Covers around 500 topics in a FAQ-like Q&A
  664.    format.
  665.  * Meyers, Effective C++, Second Edition, 224 pgs, Addison-Wesley, 1998, ISBN
  666.    0-201-92488-9.  Covers 50 topics in a short essay format.
  667.  * Meyers, More Effective C++, 336 pgs, Addison-Wesley, 1996, ISBN
  668.    0-201-63371-X.  Covers 35 topics in a short essay format.
  669.  
  670. Similarities: All three books are extensively illustrated with code examples.
  671. All three are excellent, insightful, useful, gold plated books.  All three have
  672. excellent sales records.
  673.  
  674. Differences: Cline/Lomow/Girou's examples are complete, working programs rather
  675. than code fragments or standalone classes.  Meyers contains numerous
  676. line-drawings that illustrate the points.
  677.  
  678. ==============================================================================
  679.  
  680. [26.6] What are some best-of-breed C++ legality guides?
  681.  
  682. Here's my personal (subjective and selective) short-list of must-read C++
  683. legality guides, alphabetically by author:
  684.  * Lippman and Lajoie, C++ Primer, Third Edition, 1237 pgs, Addison-Wesley,
  685.    1998, ISBN 0-201-82470-1.  Very readable/approachable.
  686.  * Stroustrup, The C++ Programming Language, Third Edition, 911 pgs,
  687.    Addison-Wesley, 1998, ISBN 0-201-88954-4.  Covers a lot of ground.
  688.  
  689. Similarities: Both books are excellent overviews of almost every language
  690. feature.  I reviewed them for back-to-back issues of C++ Report, and I said
  691. that they are both top notch, gold plated, excellent books.  Both have
  692. excellent sales records.
  693.  
  694. Differences: If you don't know C, Lippman's book is better for you.  If you
  695. know C and you want to cover a lot of ground quickly, Stroustrup's book is
  696. better for you.
  697.  
  698. ==============================================================================
  699.  
  700. [26.7] Are there other OO books that are relevant to OO/C++?
  701.  
  702. Yes! Tons!
  703.  
  704. The morality[26.5] and legality[26.6] categories listed above were for OO
  705. programming.  The areas of OO analysis and OO design are also relevant, and
  706. have their own best-of-breed books.
  707.  
  708. There are tons and tons of good books in these other areas.  The seminal book
  709. on OO design patterns is (in my personal, subjective and selective, opinion) a
  710. must-read book: Gamma et al., Design Patterns, 395 pgs, Addison-Wesley, 1995,
  711. ISBN 0-201-63361-2.  Describes "patterns" that commonly show up in good OO
  712. designs.  You must read this book if you intend to do OO design work.
  713.  
  714. ==============================================================================
  715.  
  716. [26.8] But those books are too advanced for me since I've never used any
  717.        programming language before; is there any hope for me?
  718.  
  719. Yes.
  720.  
  721. There are probably many C++ books that are targeted for people who are brand
  722. new programmers, but here's one that I've read: Heller, Who's afraid of C++?,
  723. AP Professional, 1996, ISBN 0-12-339097-4.
  724.  
  725. Note that you should supplement that book with one of the above books and/or
  726. the FAQ's sections on const correctness[18] and exception safety[17] since
  727. these topics aren't highlighted in that book.
  728.  
  729. ==============================================================================
  730.  
  731. SECTION [27]: Learning C++ if you already know Smalltalk
  732.  
  733.  
  734. [27.1] What's the difference between C++ and Smalltalk?
  735.  
  736. Both fully support the OO paradigm.  Neither is categorically and universally
  737. "better" than the other[6.4].  But there are differences.  The most important
  738. differences are:
  739.  * Static typing vs. dynamic typing[27.2]
  740.  * Whether inheritance must be used only for subtyping[27.5]
  741.  * Value vs. reference semantics[28]
  742.  
  743. Note: Many new C++ programmers come from a Smalltalk background.  If that's
  744. you, this section will tell you the most important things you need know to make
  745. your transition.  Please don't get the notion that either language is somehow
  746. "inferior" or "bad"[6.4], or that this section is promoting one language over
  747. the other (I am not a language bigot; I serve on both the ANSI C++ and ANSI
  748. Smalltalk standardization committees[6.11]).  Instead, this section is designed
  749. to help you understand (and embrace!) the differences.
  750.  
  751. ==============================================================================
  752.  
  753. [27.2] What is "static typing," and how is it similar/dissimilar to Smalltalk?
  754.  
  755. Static typing says the compiler checks the type safety of every operation
  756. statically (at compile-time), rather than to generate code which will check
  757. things at run-time.  For example, with static typing, the signature matching
  758. for function arguments is checked at compile time, not at run-time.  An
  759. improper match is flagged as an error by the compiler, not by the run-time
  760. system.
  761.  
  762. In OO code, the most common "typing mismatch" is invoking a member function
  763. against an object which isn't prepared to handle the operation.  E.g., if class
  764. Fred has member function f() but not g(), and fred is an instance of class
  765. Fred, then fred.f() is legal and fred.g() is illegal.  C++ (statically typed)
  766. catches the error at compile time, and Smalltalk (dynamically typed) catches
  767. the error at run-time.  (Technically speaking, C++ is like Pascal --pseudo
  768. statically typed-- since pointer casts and unions can be used to violate the
  769. typing system; which reminds me: only use pointer casts and unions as often as
  770. you use gotos).
  771.  
  772. ==============================================================================
  773.  
  774. [27.3] Which is a better fit for C++: "static typing" or "dynamic typing"?
  775.        [UPDATED!]
  776.  
  777. [Recently added cross references to evilness of macros (on 3/00).]
  778.  
  779. [For context, please read the previous FAQ[27.2]].
  780.  
  781. If you want to use C++ most effectively, use it as a statically typed language.
  782.  
  783. C++ is flexible enough that you can (via pointer casts, unions, and #define
  784. macros) make it "look" like Smalltalk.  But don't.  Which reminds me: try to
  785. avoid #define: it's evil[9.3], evil[34.1], evil[34.2], evil[34.3].
  786.  
  787. There are places where pointer casts and unions are necessary and even
  788. wholesome, but they should be used carefully and sparingly.  A pointer cast
  789. tells the compiler to believe you.  An incorrect pointer cast might corrupt
  790. your heap, scribble into memory owned by other objects, call nonexistent member
  791. functions, and cause general failures.  It's not a pretty sight.  If you avoid
  792. these and related constructs, you can make your C++ code both safer and faster,
  793. since anything that can be checked at compile time is something that doesn't
  794. have to be done at run-time.
  795.  
  796. If you're interested in using a pointer cast, use the new style pointer casts.
  797. The most common example of these is to change old-style pointer casts such as
  798. (X*)p into new-style dynamic casts such as dynamic_cast<X*>(p), where p is a
  799. pointer and X is a type.  In addition to dynamic_cast, there is static_cast and
  800. const_cast, but dynamic_cast is the one that simulates most of the advantages
  801. of dynamic typing (the other is the typeid() construct; for example,
  802. typeid(*p).name() will return the name of the type of *p).
  803.  
  804. ==============================================================================
  805.  
  806. [27.4] How do you use inheritance in C++, and is that different from Smalltalk?
  807.  
  808. Some people believe that the purpose of inheritance is code reuse.  In C++,
  809. this is wrong.  Stated plainly, "inheritance is not for code reuse."
  810.  
  811. The purpose of inheritance in C++ is to express interface compliance
  812. (subtyping), not to get code reuse.  In C++, code reuse usually comes via
  813. composition rather than via inheritance.  In other words, inheritance is mainly
  814. a specification technique rather than an implementation technique.
  815.  
  816. This is a major difference with Smalltalk, where there is only one form of
  817. inheritance (C++ provides private inheritance to mean "share the code but don't
  818. conform to the interface", and public inheritance to mean "kind-of").  The
  819. Smalltalk language proper (as opposed to coding practice) allows you to have
  820. the effect of "hiding" an inherited method by providing an override that calls
  821. the "does not understand" method.  Furthermore Smalltalk allows a conceptual
  822. "is-a" relationship to exist apart from the subclassing hierarchy (subtypes
  823. don't have to be subclasses; e.g., you can make something that is-a Stack yet
  824. doesn't inherit from class Stack).
  825.  
  826. In contrast, C++ is more restrictive about inheritance: there's no way to make
  827. a "conceptual is-a" relationship without using inheritance (the C++ work-around
  828. is to separate interface from implementation via ABCs[22.3]).  The C++ compiler
  829. exploits the added semantic information associated with public inheritance to
  830. provide static typing.
  831.  
  832. ==============================================================================
  833.  
  834. [27.5] What are the practical consequences of differences in Smalltalk/C++
  835.        inheritance?
  836.  
  837. [For context, please read the previous FAQ[27.4]].
  838.  
  839. Smalltalk lets you make a subtype that isn't a subclass, and allows you to make
  840. a subclass that isn't a subtype.  This allows Smalltalk programmers to be very
  841. carefree in putting data (bits, representation, data structure) into a class
  842. (e.g., you might put a linked list into class Stack).  After all, if someone
  843. wants an array-based-Stack, they don't have to inherit from Stack; they could
  844. inherit such a class from Array if desired, even though an ArrayBasedStack is
  845. not a kind-of Array!
  846.  
  847. In C++, you can't be nearly as carefree.  Only mechanism (member function
  848. code), but not representation (data bits) can be overridden in subclasses.
  849. Therefore you're usually better off not putting the data structure in a class.
  850. This leads to a stronger reliance on abstract base classes[22.3].
  851.  
  852. I like to think of the difference between an ATV and a Maseratti.  An ATV (all
  853. terrain vehicle) is more fun, since you can "play around" by driving through
  854. fields, streams, sidewalks, and the like.  A Maseratti, on the other hand, gets
  855. you there faster, but it forces you to stay on the road.  My advice to C++
  856. programmers is simple: stay on the road.  Even if you're one of those people
  857. who like the "expressive freedom" to drive through the bushes, don't do it in
  858. C++; it's not a good fit.
  859.  
  860. ==============================================================================
  861.  
  862. SECTION [28]: Reference and value semantics
  863.  
  864.  
  865. [28.1] What is value and/or reference semantics, and which is best in C++?
  866.  
  867. With reference semantics, assignment is a pointer-copy (i.e., a reference).
  868. Value (or "copy") semantics mean assignment copies the value, not just the
  869. pointer.  C++ gives you the choice: use the assignment operator to copy the
  870. value (copy/value semantics), or use a pointer-copy to copy a pointer
  871. (reference semantics).  C++ allows you to override the assignment operator to
  872. do anything your heart desires, however the default (and most common) choice is
  873. to copy the value.
  874.  
  875. Pros of reference semantics: flexibility and dynamic binding (you get dynamic
  876. binding in C++ only when you pass by pointer or pass by reference, not when you
  877. pass by value).
  878.  
  879. Pros of value semantics: speed.  "Speed" seems like an odd benefit for a
  880. feature that requires an object (vs. a pointer) to be copied, but the fact of
  881. the matter is that one usually accesses an object more than one copies the
  882. object, so the cost of the occasional copies is (usually) more than offset by
  883. the benefit of having an actual object rather than a pointer to an object.
  884.  
  885. There are three cases when you have an actual object as opposed to a pointer to
  886. an object: local objects, global/static objects, and fully contained member
  887. objects in a class.  The most important of these is the last ("composition").
  888.  
  889. More info about copy-vs-reference semantics is given in the next FAQs.  Please
  890. read them all to get a balanced perspective.  The first few have intentionally
  891. been slanted toward value semantics, so if you only read the first few of the
  892. following FAQs, you'll get a warped perspective.
  893.  
  894. Assignment has other issues (e.g., shallow vs. deep copy) which are not covered
  895. here.
  896.  
  897. ==============================================================================
  898.  
  899. [28.2] What is "virtual data," and how-can / why-would I use it in C++?
  900.  
  901. virtual data allows a derived class to change the exact class of a base class's
  902. member object.  virtual data isn't strictly "supported" by C++, however it can
  903. be simulated in C++.  It ain't pretty, but it works.
  904.  
  905. To simulate virtual data in C++, the base class must have a pointer to the
  906. member object, and the derived class must provide a new object to be pointed to
  907. by the base class's pointer.  The base class would also have one or more normal
  908. constructors that provide their own referent (again via new), and the base
  909. class's destructor would delete the referent.
  910.  
  911. For example, class Stack might have an Array member object (using a pointer),
  912. and derived class StretchableStack might override the base class member data
  913. from Array to StretchableArray.  For this to work, StretchableArray would have
  914. to inherit from Array, so Stack would have an Array*.  Stack's normal
  915. constructors would initialize this Array* with a new Array, but Stack would
  916. also have a (possibly protected:) constructor that would accept an Array* from
  917. a derived class.  StretchableArray's constructor would provide a
  918. new StretchableArray to this special constructor.
  919.  
  920. Pros:
  921.  * Easier implementation of StretchableStack (most of the code is inherited)
  922.  * Users can pass a StretchableStack as a kind-of Stack
  923.  
  924. Cons:
  925.  * Adds an extra layer of indirection to access the Array
  926.  * Adds some extra freestore allocation overhead (both new and delete)
  927.  * Adds some extra dynamic binding overhead (reason given in next FAQ)
  928.  
  929. In other words, we succeeded at making our job easier as the implementer of
  930. StretchableStack, but all our users pay for it[28.5].  Unfortunately the extra
  931. overhead was imposed on both users of StretchableStack and on users of Stack.
  932.  
  933. Please read the rest of this section.  (You will not get a balanced perspective
  934. without the others.)
  935.  
  936. ==============================================================================
  937.  
  938. [28.3] What's the difference between virtual data and dynamic data?
  939.  
  940. The easiest way to see the distinction is by an analogy with virtual
  941. functions[20]: A virtual member function means the declaration (signature) must
  942. stay the same in subclasses, but the definition (body) can be overridden.  The
  943. overriddenness of an inherited member function is a static property of the
  944. subclass; it doesn't change dynamically throughout the life of any particular
  945. object, nor is it possible for distinct objects of the subclass to have
  946. distinct definitions of the member function.
  947.  
  948. Now go back and re-read the previous paragraph, but make these substitutions:
  949.  * "member function" --> "member object"
  950.  * "signature" --> "type"
  951.  * "body" --> "exact class"
  952.  
  953. After this, you'll have a working definition of virtual data.
  954.  
  955. Another way to look at this is to distinguish "per-object" member functions
  956. from "dynamic" member functions.  A "per-object" member function is a member
  957. function that is potentially different in any given instance of an object, and
  958. could be implemented by burying a function pointer in the object; this pointer
  959. could be const, since the pointer will never be changed throughout the object's
  960. life.  A "dynamic" member function is a member function that will change
  961. dynamically over time; this could also be implemented by a function pointer,
  962. but the function pointer would not be const.
  963.  
  964. Extending the analogy, this gives us three distinct concepts for data members:
  965.  * virtual data: the definition (class) of the member object is overridable in
  966.    subclasses provided its declaration ("type") remains the same, and this
  967.    overriddenness is a static property of the subclass
  968.  * per-object-data: any given object of a class can instantiate a different
  969.    conformal (same type) member object upon initialization (usually a "wrapper"
  970.    object), and the exact class of the member object is a static property of
  971.    the object that wraps it
  972.  * dynamic-data: the member object's exact class can change dynamically over
  973.    time
  974.  
  975. The reason they all look so much the same is that none of this is "supported"
  976. in C++.  It's all merely "allowed," and in this case, the mechanism for faking
  977. each of these is the same: a pointer to a (probably abstract) base class.  In a
  978. language that made these "first class" abstraction mechanisms, the difference
  979. would be more striking, since they'd each have a different syntactic variant.
  980.  
  981. ==============================================================================
  982.  
  983. [28.4] Should I normally use pointers to freestore allocated objects for my
  984.        data members, or should I use "composition"?
  985.  
  986. Composition.
  987.  
  988. Your member objects should normally be "contained" in the composite object (but
  989. not always; "wrapper" objects are a good example of where you want a
  990. pointer/reference; also the N-to-1-uses-a relationship needs something like a
  991. pointer/reference).
  992.  
  993. There are three reasons why fully contained member objects ("composition") has
  994. better performance than pointers to freestore-allocated member objects:
  995.  * Extra layer of indirection every time you need to access the member object
  996.  * Extra freestore allocations (new in constructor, delete in destructor)
  997.  * Extra dynamic binding (reason given below)
  998.  
  999. ==============================================================================
  1000.  
  1001. [28.5] What are relative costs of the 3 performance hits associated with
  1002.        allocating member objects from the freestore?
  1003.  
  1004. The three performance hits are enumerated in the previous FAQ:
  1005.  * By itself, an extra layer of indirection is small potatoes
  1006.  * Freestore allocations can be a performance issue (the performance of the
  1007.    typical implementation of malloc() degrades when there are many allocations;
  1008.    OO software can easily become "freestore bound" unless you're careful)
  1009.  * The extra dynamic binding comes from having a pointer rather than an object.
  1010.    Whenever the C++ compiler can know an object's exact class, virtual[20]
  1011.    function calls can be statically bound, which allows inlining.  Inlining
  1012.    allows zillions (would you believe half a dozen :-) optimization
  1013.    opportunities such as procedural integration, register lifetime issues, etc.
  1014.    The C++ compiler can know an object's exact class in three circumstances:
  1015.    local variables, global/static variables, and fully-contained member objects
  1016.  
  1017. Thus fully-contained member objects allow significant optimizations that
  1018. wouldn't be possible under the "member objects-by-pointer" approach.  This is
  1019. the main reason that languages which enforce reference-semantics have
  1020. "inherent" performance challenges.
  1021.  
  1022. Note: Please read the next three FAQs to get a balanced perspective!
  1023.  
  1024. ==============================================================================
  1025.  
  1026. [28.6] Are "inline virtual" member functions ever actually "inlined"?
  1027.  
  1028. Occasionally...
  1029.  
  1030. When the object is referenced via a pointer or a reference, a call to a
  1031. virtual[20] function cannot be inlined, since the call must be resolved
  1032. dynamically.  Reason: the compiler can't know which actual code to call until
  1033. run-time (i.e., dynamically), since the code may be from a derived class that
  1034. was created after the caller was compiled.
  1035.  
  1036. Therefore the only time an inline virtual call can be inlined is when the
  1037. compiler knows the "exact class" of the object which is the target of the
  1038. virtual function call.  This can happen only when the compiler has an actual
  1039. object rather than a pointer or reference to an object.  I.e., either with a
  1040. local object, a global/static object, or a fully contained object inside a
  1041. composite.
  1042.  
  1043. Note that the difference between inlining and non-inlining is normally much
  1044. more significant than the difference between a regular function call and a
  1045. virtual function call.  For example, the difference between a regular function
  1046. call and a virtual function call is often just two extra memory references, but
  1047. the difference between an inline function and a non-inline function can be as
  1048. much as an order of magnitude (for zillions of calls to insignificant member
  1049. functions, loss of inlining virtual functions can result in 25X speed
  1050. degradation! [Doug Lea, "Customization in C++," proc Usenix C++ 1990]).
  1051.  
  1052. A practical consequence of this insight: don't get bogged down in the endless
  1053. debates (or sales tactics!) of compiler/language vendors who compare the cost
  1054. of a virtual function call on their language/compiler with the same on another
  1055. language/compiler.  Such comparisons are largely meaningless when compared with
  1056. the ability of the language/compiler to "inline expand" member function calls.
  1057. I.e., many language implementation vendors make a big stink about how good
  1058. their dispatch strategy is, but if these implementations don't inline member
  1059. function calls, the overall system performance would be poor, since it is
  1060. inlining --not dispatching-- that has the greatest performance impact.
  1061.  
  1062. Note: Please read the next two FAQs to see the other side of this coin!
  1063.  
  1064. ==============================================================================
  1065.  
  1066. [28.7] Sounds like I should never use reference semantics, right?
  1067.  
  1068. Wrong.
  1069.  
  1070. Reference semantics are A Good Thing.  We can't live without pointers.  We just
  1071. don't want our s/w to be One Gigantic Rats Nest Of Pointers.  In C++, you can
  1072. pick and choose where you want reference semantics (pointers/references) and
  1073. where you'd like value semantics (where objects physically contain other
  1074. objects etc).  In a large system, there should be a balance.  However if you
  1075. implement absolutely everything as a pointer, you'll get enormous speed hits.
  1076.  
  1077. Objects near the problem skin are larger than higher level objects.  The
  1078. identity of these "problem space" abstractions is usually more important than
  1079. their "value." Thus reference semantics should be used for problem-space
  1080. objects.
  1081.  
  1082. Note that these problem space objects are normally at a higher level of
  1083. abstraction than the solution space objects, so the problem space objects
  1084. normally have a relatively lower frequency of interaction.  Therefore C++ gives
  1085. us an ideal situation: we choose reference semantics for objects that need
  1086. unique identity or that are too large to copy, and we can choose value
  1087. semantics for the others.  Thus the highest frequency objects will end up with
  1088. value semantics, since we install flexibility where it doesn't hurt us (only),
  1089. and we install performance where we need it most!
  1090.  
  1091. These are some of the many issues the come into play with real OO design.
  1092. OO/C++ mastery takes time and high quality training.  If you want a powerful
  1093. tool, you've got to invest.
  1094.  
  1095. Don't stop now! Read the next FAQ too!!
  1096.  
  1097. ==============================================================================
  1098.  
  1099. [28.8] Does the poor performance of reference semantics mean I should
  1100.        pass-by-value?
  1101.  
  1102. Nope.
  1103.  
  1104. The previous FAQ were talking about member objects, not parameters.  Generally,
  1105. objects that are part of an inheritance hierarchy should be passed by reference
  1106. or by pointer, not by value, since only then do you get the (desired) dynamic
  1107. binding (pass-by-value doesn't mix with inheritance, since larger subclass
  1108. objects get "sliced" when passed by value as a base class object).
  1109.  
  1110. Unless compelling reasons are given to the contrary, member objects should be
  1111. by value and parameters should be by reference.  The discussion in the previous
  1112. few FAQs indicates some of the "compelling reasons" for when member objects
  1113. should be by reference.
  1114.  
  1115. ==============================================================================
  1116.  
  1117. -- 
  1118. Marshall Cline / 972-931-9470 / mailto:cline@parashift.com
  1119.