home *** CD-ROM | disk | FTP | other *** search
/ Monster Media 1993 #2 / Image.iso / internet / cppfaq.zip / CPPFAQ.TXT
Text File  |  1993-08-13  |  169KB  |  3,481 lines

  1. ==============================================================================
  2.  
  3.  Document: Frequently-Asked-Questions for comp.lang.c++
  4.  Revision: 09-July-93
  5.  
  6.  Author:  Marshall P. Cline, Ph.D.
  7.    Paradigm Shift, Inc.
  8.    One Park St. / Norwood, NY  13668
  9.    voice: 315-353-6100
  10.    fax:   315-353-6110
  11.    email: cline@parashift.com
  12.  
  13.  Copyright: Copyright (C), 1991-93 Marshall P. Cline, Ph.D.
  14.    Permission to copy all or part of this work is granted,
  15.    provided that the copies are not made or distributed
  16.    for resale (except nominal copying fee may be charged),
  17.    and provided that the NO WARRANTY, author-contact, and
  18.    copyright notice are retained verbatim & are displayed
  19.    conspicuously.  If anyone needs other permissions that
  20.    aren't covered by the above, please contact the author.
  21.  
  22.  NO WARRANTY: THIS WORK IS PROVIDED ON AN "AS IS" BASIS.  THE AUTHOR
  23.    PROVIDES NO WARRANTY WHATSOEVER, EITHER EXPRESS OR
  24.    IMPLIED, REGARDING THE WORK, INCLUDING WARRANTIES WITH
  25.    RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY
  26.    PARTICULAR PURPOSE.
  27.  
  28.  Availability: This is available via anonymous ftp
  29.    from: sun.soe.clarkson.edu [128.153.12.3]
  30.    in the file: pub/C++/FAQ
  31.  
  32.  Without FTP: You can also get it by sending electronic mail:
  33.    | To: archive-server@sun.soe.clarkson.edu
  34.    | Subject: send C++/FAQ
  35.    This will help those who don't have ftp.
  36.  
  37.  (NOTE: I hear the mail server is down; if you have problems,
  38.   send details and I'll look into it).
  39.  
  40.  See also: comp.lang.c's FAQ appears at the beginning of every
  41.    month in that newsgroup, and is maintained by
  42.    Steve Summit (scs@adm.mit.edu).
  43.  
  44. ==============================================================================
  45. SUBSECTION: Table of Contents
  46. ==============================================================================
  47.  
  48. PART01 -- Introduction and table of contents
  49. Table of Contents
  50. Nomenclature and Common Abbreviations
  51.  
  52. PART02 -- Environmental/managerial issues
  53. Q1: What is C++? What is OOP?
  54. Q2: What are some advantages of C++?
  55. Q3: Who uses C++?
  56. Q4: Are there any C++ standardization efforts underway?
  57. Q5: Where can I ftp a copy of the latest ANSI-C++ draft standard?
  58. Q6: Is C++ backward compatible with ANSI-C?
  59. Q7: How long does it take to learn C++?
  60.  
  61. PART03 -- Basics of the paradigm
  62. Q8: What is a class?
  63. Q9: What is an object?
  64. Q10: What is a reference?
  65. Q11: What happens if you assign to a reference?
  66. Q12: How can you reseat a reference to make it refer to a different object?
  67. Q13: When should I use references, and when should I use pointers?
  68. Q14: What are inline fns? What are their advantages? How are they declared?
  69.  
  70. PART04 -- Constructors and destructors
  71. Q15: What is a constructor?  Why would I ever use one?
  72. Q16: How can I make a constructor call another constructor as a primitive?
  73. Q17: What are destructors really for?  Why would I ever use them?
  74.  
  75. PART05 -- Operator overloading
  76. Q18: What is operator overloading?
  77. Q19: What operators can/cannot be overloaded?
  78. Q20: Can I create a `**' operator for `to-the-power-of' operations?
  79.  
  80. PART06 -- Friends
  81. Q21: What is a `friend'?
  82. Q22: Do `friends' violate encapsulation?
  83. Q23: What are some advantages/disadvantages of using friends?
  84. Q24: What does it mean that `friendship is neither inherited nor transitive'?
  85. Q25: When would I use a member function as opposed to a friend function?
  86.  
  87. PART07 -- Input/output via <iostream.h> and <stdio.h>
  88. Q26: How can I provide printing for a `class X'?
  89. Q27: Why should I use <iostream.h> instead of the traditional <stdio.h>?
  90. Q28: Printf/scanf weren't broken; why `fix' them with ugly shift operators?
  91.  
  92. PART08 -- Freestore management
  93. Q29: Does `delete ptr' delete the ptr or the pointed-to-data?
  94. Q30: Can I free() ptrs alloc'd with `new' or `delete' ptrs alloc'd w/ malloc()?
  95. Q31: Why should I use `new' instead of trustworthy old malloc()?
  96. Q32: Why doesn't C++ have a `realloc()' along with `new' and `delete'?
  97. Q33: How do I allocate / unallocate an array of things?
  98. Q34: What if I forget the `[]' when `delete'ing array allocated via `new X[n]'?
  99.  
  100. PART09 -- Debugging and error handling
  101. Q35: How can I handle a constructor that fails?
  102. Q36: How can I compile-out my debugging print statements?
  103.  
  104. PART10 -- Const correctness
  105. Q37: What is `const correctness'?
  106. Q38: Is `const correctness' a good goal?
  107. Q39: Is `const correctness' tedious?
  108. Q40: Should I try to get things const correct `sooner' or `later'?
  109. Q41: What is a `const member function'?
  110. Q42: What is an `inspector'?  What is a `mutator'?
  111. Q43: What is `casting away const in an inspector' and why is it legal?
  112. Q44: But doesn't `cast away const' mean lost optimization opportunities?
  113.  
  114. PART11 -- Inheritance
  115. Q45: What is inheritance?
  116. Q46: Ok, ok, but what is inheritance?
  117. Q47: How do you express inheritance in C++?
  118. Q48: What is `incremental programming'?
  119. Q49: Should I pointer-cast from a derived class to its base class?
  120. Q50: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
  121. Q51: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are bad?
  122. Inheritance -- virtual functions
  123. Q52: What is a `virtual member function'?
  124. Q53: What is dynamic dispatch?  Static dispatch?
  125. Q54: Can I override a non-virtual fn?
  126. Q55: Why do I get the warning "Derived::foo(int) hides Base::foo(double)"?
  127. Inheritance -- conformance
  128. Q56: Can I `revoke' or `hide' public member fns inherited from my base class?
  129. Q57: Is a `Circle' a kind-of an `Ellipse'?
  130. Q58: Are there other options to the `Circle is/isnot kind-of Ellipse' dilemma?
  131. Inheritance -- access rules
  132. Q59: Why can't I access `private' things in a base class from a derived class?
  133. Q60: What's the difference between `public:', `private:', and `protected:'?
  134. Q61: How can I protect subclasses from breaking when I change internal parts?
  135. Inheritance -- constructors and destructors
  136. Q62: Why does base ctor get *base*'s virtual fn instead of the derived version?
  137. Q63: Does a derived class dtor need to explicitly call the base destructor?
  138. Inheritance -- private and protected inheritance
  139. Q64: How do you express `private inheritance'?
  140. Q65: How are `private derivation' and `containment' similar? dissimilar?
  141. Q66: Should I pointer-cast from a `privately' derived class to its base class?
  142. Q67: Should I pointer-cast from a `protected' derived class to its base class?
  143. Q68: What are the access rules with `private' and `protected' inheritance?
  144. Q69: Do most C++ programmers use containment or private inheritance?
  145.  
  146. PART12 -- Abstraction
  147. Q70: What's the big deal of separating interface from implementation?
  148. Q71: How do I separate interface from implementation in C++ (like Modula-2)?
  149. Q72: What is an ABC (`abstract base class')?
  150. Q73: What is a `pure virtual' member function?
  151. Q74: How can I provide printing for an entire hierarchy rooted at `class X'?
  152. Q75: What is a `virtual destructor'?
  153. Q76: What is a `virtual constructor'?
  154.  
  155. PART13 -- Style guidelines
  156. Q77: What are some good C++ coding standards?
  157. Q78: Are coding standards necessary?  sufficient?
  158. Q79: Should our organization determine coding standards from our C experience?
  159. Q80: Should I declare locals in the middle of a fn or at the top?
  160. Q81: What source-file-name convention is best? `foo.C'? `foo.cc'? `foo.cpp'?
  161. Q82: What header-file-name convention is best? `foo.H'? `foo.hh'? `foo.hpp'?
  162. Q83: Are there any lint-like guidelines for C++?
  163.  
  164. PART14 -- C++/Smalltalk differences and keys to learning C++
  165. Q84: Why does C++'s FAQ have a section on Smalltalk? Is this Smalltalk-bashing?
  166. Q85: What's the difference between C++ and Smalltalk?
  167. Q86: What is `static typing', and how is it similar/dissimilar to Smalltalk?
  168. Q87: Which is a better fit for C++: `static typing' or `dynamic typing'?
  169. Q88: How can you tell if you have a dynamically typed C++ class library?
  170. Q89: Will `standard C++' include any dynamic typing primitives?
  171. Q90: How do you use inheritance in C++, and is that different from Smalltalk?
  172. Q91: What are the practical consequences of diffs in Smalltalk/C++ inheritance?
  173. Q92: Do you need to learn a `pure' OOPL before you learn C++?
  174. Q93: What is the NIHCL?  Where can I get it?
  175.  
  176. PART15 -- Reference and value semantics
  177. Q94: What is value and/or reference semantics, and which is best in C++?
  178. Q95: What is `virtual data', and how-can / why-would I use it in C++?
  179. Q96: What's the difference between virtual data and dynamic data?
  180. Q97: Should class subobjects be ptrs to freestore allocated objs, or contained?
  181. Q98: What are relative costs of the 3 performance hits of allocated subobjects?
  182. Q99: What is an `inline virtual member fn'?  Are they ever actually `inlined'?
  183. Q100: Sounds like I should never use reference semantics, right?
  184. Q101: Does the poor performance of ref semantics mean I should pass-by-value?
  185.  
  186. PART16 -- Linkage-to/relationship-with C
  187. Q102: How can I call a C function `f()' from C++ code?
  188. Q103: How can I create a C++ function `f()' that is callable by my C code?
  189. Q104: Why's the linker giving errors for C/C++ fns being called from C++/C fns?
  190. Q105: How can I pass an object of a C++ class to/from a C function?
  191. Q106: Can my C function access data in an object of a C++ class?
  192. Q107: Why do I feel like I'm `further from the machine' in C++ as opposed to C?
  193.  
  194. PART17 -- Pointers to member functions
  195. Q108: What is the type of `ptr-to-member-fn'?  Is it diffn't from `ptr-to-fn'?
  196. Q109: How can I ensure `X's objects are only created with new, not on the
  197. stack?
  198. Q110: How do I pass a ptr to member fn to a signal handler,X event
  199. callback,etc?
  200. Q111: Why am I having trouble taking the address of a C++ function?
  201. Q112: How do I declare an array of pointers to member functions?
  202.  
  203. PART18 -- Container classes and templates
  204. Q113: How can I insert/access/change elements from a linked list/hashtable/etc?
  205. Q114: What's the idea behind `templates'?
  206. Q115: What's the syntax / semantics for a `function template'?
  207. Q116: What's the syntax / semantics for a `class template'?
  208. Q117: What is a `parameterized type'?
  209. Q118: What is `genericity'?
  210. Q119: How can I fake templates if I don't have a compiler that supports them?
  211.  
  212. PART19 -- Nuances of particular implementations
  213. Q120: Why don't variable arg lists work for C++ on a Sun SPARCstation?
  214. Q121: GNU C++ (g++) produces big executables for tiny programs; Why?
  215. Q122: Is there a yacc-able C++ grammar?
  216. Q123: What is C++ 1.2?  2.0?  2.1?  3.0?
  217. Q124: How does the lang accepted by cfront 3.0 differ from that accepted by
  218. 2.1?
  219. Q125: Why are exceptions going to be implemented after templates? Why not both?
  220. Q126: What was C++ 1.xx, and how is it different from the current C++ language?
  221.  
  222. PART20 -- Miscellaneous technical and environmental issues
  223. Miscellaneous technical issues:
  224. Q127: Why are classes with static data members getting linker errors?
  225. Q128: What's the difference between the keywords struct and class?
  226. Q129: Why can't I overload a function by its return type?
  227. Q130: What is `persistence'?  What is a `persistent object'?
  228. Miscellaneous environmental issues:
  229. Q131: Is there a TeX or LaTeX macro that fixes the spacing on `C++'?
  230. Q132: Where can I access C++2LaTeX, a LaTeX pretty printer for C++ source?
  231. Q133: Where can I access `tgrind', a pretty printer for C++/C/etc source?
  232. Q134: Is there a C++-mode for GNU emacs?  If so, where can I get it?
  233. Q135: What is `InterViews'?
  234. Q136: Where can I get OS-specific questions answered (ex:BC++,DOS,Windows,etc)?
  235. Q137: Why does my DOS C++ program says `Sorry: floating point code not linked'?
  236.  
  237. ==============================================================================
  238. SUBSECTION: Nomenclature and Common Abbreviations
  239. ==============================================================================
  240.  
  241. Here are a few of the abbreviations/etc used in this article:
  242.  
  243.     term meaning
  244.     ==== ===========
  245.     ctor constructor
  246.     copy-ctor copy constructor (also `X(const X&)', pronounced `X-X-ref')
  247.     dtor destructor
  248.     fn  function
  249.     fns  functions
  250.     ptr  pointer, a C/C++ construct declared by:  int * p;
  251.     ref  reference, a C++ construct declared by:  int & r;
  252.     const a C++ keyword which is short for `constant'
  253.     OO  object-oriented
  254.     OOP  object-oriented programming
  255.     OOPL object-oriented programming language
  256.     method an alternate term for `member function'
  257.     message an alternate term for `invoking a member function'
  258.     NULL the `zero' or `empty' pointer (`NULL' in C, `0' in C++)
  259.  
  260. ==============================================================================
  261.  
  262.   ****  PART 02 -- Environmental/managerial issues  ****
  263.  
  264. ==============================================================================
  265.  
  266. Q1: What is C++? What is OOP?
  267.  
  268. C++ can be used simply as `a better C', but that is not its real advantage.
  269. C++ is an object-oriented programming language (OOPL).  OOPLs appear to be the
  270. current `top shelf' in the development of programming languages that can manage
  271. the complexity of large software systems.
  272.  
  273. Some OOP hype: software engineering is `failing' to provide the current users
  274. demands for large, complex software systems.  But this `failure' is actually
  275. due to SE's *successes*.  In other words, structured programming was developed
  276. to allow software engineers to design/build HUGE software systems (that's a
  277. success).  When users saw how successful these systems were, they said, `More
  278. --- give me MOOORRRREEEE'.  They wanted more power, more features, more
  279. flexibility.  100K line systems are almost commonplace nowadays, and they still
  280. want more.  Structured programming techniques, some say, begin to break down
  281. around 100K lines (the complexity gives the design team too many headaches, and
  282. fixing one problem breaks 5 more, etc).  So pragmatics demands a better
  283. paradigm than structured programming.  Hence OO-design.
  284.  
  285. ==============================================================================
  286.  
  287. Q2: What are some advantages of C++?
  288.  
  289. GROWTH OF C++: C++ is by far the most popular OOPL.  Knowing C++ is a good
  290. resume-stuffer.  But don't just use it as a better C, or you won't be using all
  291. its power.  Like any quality tool, C++ must be used the way it was designed to
  292. be used.  The number of C++ users is doubling every 7.5 to 9 months.  This
  293. exponential growth can't continue forever(!), but it is becoming a significant
  294. chunk of the programming market (it's already the dominant OOPL).
  295.  
  296. ENCAPSULATION: For those of you who aren't on a team constructing software
  297. mega-systems, what does C++ buy you?  Here's a trivial example.  Suppose you
  298. want a `Foible' data type.  One style of doing this in `C' is to create a
  299. `Foible.h' file that holds the `public interface', then stick all the
  300. implementation into a `Foible.c' file.  Encapsulation (hiding the details) can
  301. be achieved by making all data elements in `Foible.c' be `static'.  But that
  302. means you only get one `Foible' in the entire system, which is ok if `Foible'
  303. is a Screen or perhaps a HardDisk, but is lousy if Foible is a complex number
  304. or a line on the screen, etc.  Read on to see how it's done in `C' vs `C++'.
  305.  
  306. MULTIPLE INSTANCES: The `C' solution to the above `multiple instances' problem
  307. is to wrap all the data members in a struct (like a Pascal `record'), then pass
  308. these structs around as if they were the `ComplexNumber' or whatever.  But this
  309. loses encapsulation.  Other techniques can be devised which allow both multiple
  310. instances and encapsulation, however these lose on other accounts (ex:
  311. typedef'ing `Foible' to be `void*' loses type safety, and wrapping a `void*' in
  312. the Foible struct loses an extra layer of indirection).  So the `module'
  313. technique loses multiple instantiations, but the `struct' technique loses
  314. encapsulation.  C++ allows you to combine the best of both worlds - you can
  315. have what amount to structs whose data is hidden.
  316.  
  317. INLINE FUNCTION CALLS: The `encapsulated C' solution above requires a function
  318. call to access even trivial fields of the data type (if you allowed direct
  319. access to the struct's fields, the underlying data structure would become
  320. virtually impossible to change since too many pieces of code would *rely* on it
  321. being the `old' way).  Function call overhead is small, but can add up.  C++
  322. provides a solution by allowing function calls to be expanded `inline', so you
  323. have: the (1) safety of encapsulation, (2) convenience of multiple instances,
  324. (3) speed of direct access.  Furthermore the parameter types of these inline
  325. functions are checked by the compiler, an improvement over C's #define macros.
  326.  
  327. OVERLOADING OPERATORS: For the `ComplexNumber' example, you want to be able to
  328. use it in an expression `just as if' it was a builtin type like int or float.
  329. C++ allows you to overload operators, so you can tell the compiler what it
  330. means for two complex numbers to be added, subtracted, multiplied, etc.  This
  331. gives you: z0 = (z1 + z2) * z3 / z4; Furthermore you might want string1+string2
  332. to mean string concatenation, etc.  One of the goals of C++ is to make user
  333. defined types `look like' builtin types.  You can even have `smart pointers',
  334. which means a pointer `p' could actually be a user defined data type that
  335. `points' to a disk record (for example).  `Dereferencing' such a pointer (ex:
  336. i=*p;) means ``seek to the location on disk where p `points' and return its
  337. value''.  Also statements like p->field=27; can store things on disk, etc.  If
  338. later on you find you can fit the entire pointed-to data structure in memory,
  339. you just change the user-defined pseudo-pointer type and recompile.  All the
  340. code that used these `pseudo pointers' doesn't need to be changed at all.
  341.  
  342. INHERITANCE: We still have just scratched the surface.  In fact, we haven't
  343. even gotten to the `object-oriented' part yet!  Suppose you have a Stack data
  344. type with operations push, pop, etc.  Suppose you want an InvertableStack,
  345. which is `just like' Stack except it also has an `invert' operation.  In `C'
  346. style, you'd have to either (1) modify the existing Stack module (trouble if
  347. `Stack' is being used by others), or (2) copy Stack into another file and text
  348. edit that file (results in lots of code duplication, another chance to break
  349. something tricky in the Stack part of InvertableStack, and especially twice as
  350. much code to maintain).  C++ provides a much cleaner solution: inheritance.
  351. You say `InvertableStack inherits everything from Stack, and InvertableStack
  352. adds the invert operation'.  Done.  Stack itself remains `closed' (untouched,
  353. unmodified), and InvertableStack doesn't duplicate the code for push/pop/etc.
  354.  
  355. POLYMORPHISM: The real power of OOP isn't just inheritance, but is the ability
  356. to pass an InvertableStack around as if it actually were a Stack.  This is
  357. `safe' since (in C++ at least) the is-a relation follows public inheritance
  358. (ie: a InvertableStack is-a Stack that can also invert itself).  Polymorphism
  359. is easiest to understand from an example, so here's a `classic': a graphical
  360. draw package might deal with Circles, Squares, Rectangles, general Polygons,
  361. and Lines.  All of these are Shapes.  Most of the draw package's functions need
  362. a `Shape' parameter (as opposed to some particular kind of shape like Square).
  363. Ex: if a Shape is picked by a mouse, the Shape might get dragged across the
  364. screen and placed into a new location.  Polymorphism allows the code to work
  365. correctly even if the compiler only knows that the parameter is a `Shape'
  366. without knowing the exact kind of Shape it is.  Furthermore suppose the
  367. `pick_and_drag(Shape*) function just mentioned was compiled on Tuesday, and on
  368. Wednesday you decide to add the Hexagon shape.  Strange as it sounds,
  369. pick_and_drag() will still work with Hexagons, even though the Hexagon didn't
  370. even exist when pick_and_drag() was compiled!!  (it's not really `amazing' once
  371. you understand how the C++ compiler does it -- but it's still very convenient!)
  372.  
  373. ==============================================================================
  374.  
  375. Q3: Who uses C++?
  376. A: Lots and lots of companies and government sites.  Lots.
  377. Statistically, 20 to 30 people will consider themselves to be new C++
  378. programmers before you finish reading the responses to these FAQs.
  379.  
  380. ==============================================================================
  381.  
  382. Q4: Are there any C++ standardization efforts underway?
  383. A: Yes; ANSI (American) and ISO (International) groups are working closely with
  384. each other.
  385.  
  386. `X3J16' is the name of the ANSI-C++ committee.
  387.  
  388. `WG21' is the name of ISO's C++ standards group.
  389.  
  390. The committees are using the `ARM' as a base document:
  391.  `Annotated C++ Reference Manual', Ellis and Stroustrup, Addison/Wesley.
  392.  ISBN 0-201-51459-1
  393.  
  394. The major players in the ANSI/ISO C++ standards process includes just about
  395. everyone:
  396.  
  397. AT&T, IBM, DEC, HP, Sun, MS, Borland, Zortech, Apple, OSF, <add your favorite
  398. here>, ... and a lot of users and smaller companies.  About 70 people attend
  399. each ANSI C++ meeting.  People come from USA, UK, Japan, Germany, Sweden,
  400. Denmark, France, ... (all have `local' committees sending official
  401. representatives and conducting `local' meetings).
  402.  
  403. Optimistically the standard might be finished by 1995-6 time frame (this is
  404. fast for a proper standards process).
  405.  
  406. ==============================================================================
  407.  
  408. Q5: Where can I ftp a copy of the latest ANSI-C++ draft standard?
  409. A: You can't.  ANSI standards and/or drafts are NOT available in machine
  410. readable form.
  411.  
  412. You can get a paper copy by sending a request to:
  413.  Standards Secretariat
  414.  CBEMA
  415.  311 First St NW, Suite 500
  416.  Washington, DC  20001
  417. Ask for the latest version of `Working Paper for Draft Proposed American
  418. National Standard for Information Systems -- Programming Language C++'.
  419.  
  420. ==============================================================================
  421.  
  422. Q6: Is C++ backward compatible with ANSI-C?
  423. A: Almost. C++ is as close as possible to compatible with ANSI-C but no closer.
  424. In practice, the major difference is that C++ requires prototypes, and that
  425. `f()' declares a function that takes no parameters, while ANSI-C rules state
  426. that `f()' declares a function that takes any number of parameters of any type.
  427. There are some very subtle differences as well, like the sizeof a char literal
  428. being equal to the sizeof a char (in ANSI-C, sizeof('x') is the sizeof an int).
  429. Structure `tags' are in the same namespace as other names in C++, but C++ has
  430. some warts to take care of backward compatibility here.
  431.  
  432. ==============================================================================
  433.  
  434. Q7: How long does it take to learn C++?
  435. A: I and others teach standard industry `short courses' (for those not familiar
  436. with these, you pack a university semester course into one 40hr work-week), and
  437. have found them successful.  However mastery takes experience, and there's no
  438. substitute for time.  Laboratory time is essential for any OOP course, since it
  439. allows concepts to `gel'.
  440.  
  441. Generally people start out wondering why the company has devoted a full 5 days
  442. to something as trivial as another programming language.  Then about half way
  443. through, they realize they're not being taught just a new syntax, but an
  444. entirely different way of thinking and programming and designing and . . . .
  445. Then they begin to feel dumb, since they can't quite grasp what is being said.
  446. Then they get mad and wonder why the course isn't taught in two or three weeks
  447. instead.  Finally about Wednesday afternoon the lights go `clink', and their
  448. faces brighten, and they `get it'.  By Friday, they've had numerous laboratory
  449. `experiments' and they've seen both sides of reusable components (both how to
  450. code *from* reuse, and how to code *for* reuse).  It's different in every time
  451. I teach, but the `reuse' aspect is rewarding, since it has a large potential to
  452. improve software production's overall economics.
  453.  
  454. It takes 9 months to `master' C++/OOP.  Less if there is already a body of
  455. experts and code that programmers have regular access to, more if there isn't a
  456. `good' general purpose C++ class library available.
  457.  
  458. ==============================================================================
  459.  
  460.   ****  PART 03 -- Basics of the paradigm  ****
  461.  
  462. ==============================================================================
  463.  
  464. Q8: What is a class?
  465. A: A class defines a data type, much like a struct would be in C.  In a CompSci
  466. sense, a type consists of two things: a set of values *and* a set of operations
  467. which operate on those values.  Thus `int' all by itself isn't a true `type'
  468. until you add operations like `add two ints' or `int*int', etc.  In exactly the
  469. same way, a `class' provides a set of (usually `public') operations, and a set
  470. of (usually non-public) data bits representing the abstract values that
  471. instances of the type can have.  From a C language perspective, a `class' is a
  472. `struct' whose members default to `private'.
  473.  
  474. ==============================================================================
  475.  
  476. Q9: What is an object?
  477. A: An object is a region of storage with associated semantics.  After the
  478. declaration `int i;', we say that `i is an object of type int'.  In C++/OOP,
  479. `object' is usually used to mean `an instance of a class'.  Thus a class
  480. defines the behavior of possibly many objects (instances).
  481.  
  482. ==============================================================================
  483.  
  484. Q10: What is a reference?
  485. A: A reference is an alias (an alternate name) for an object.  It is frequently
  486. used for pass-by-reference; ex:
  487.  
  488.  void swap(int& i, int& j)
  489.  {
  490.    int tmp = i;
  491.    i = j;
  492.    j = tmp;
  493.  }
  494.  
  495.  main()
  496.  {
  497.    int x, y;
  498.    //...
  499.    swap(x,y);
  500.  }
  501.  
  502. Here `i' and `j' are aliases for main's `x' and `y' respectively.  The effect
  503. is as if you used the C style pass-by-pointer, but the `&' is moved from the
  504. caller into the callee.  Pascal enthusiasts will recognize this as a VAR param.
  505.  
  506. ==============================================================================
  507.  
  508. Q11: What happens if you assign to a reference?
  509. A: Assigning to a reference changes the referred-to value, thus a ref is an
  510. `Lvalue' (something that can appear on the `L'eft-hand-side of an assignment
  511. statement) for the referred-to value.  This insight can be pushed a bit farther
  512. by allowing references to be *returned*, thus allowing function calls on the
  513. left hand side of an assignment stmt.
  514.  
  515. ==============================================================================
  516.  
  517. Q12: How can you reseat a reference to make it refer to a different object?
  518. A: Unlike a pointer, once a reference is bound to an object, it can NOT be
  519. `reseated' to another object.  The reference itself isn't an object; you can't
  520. separate the reference from the referred-to-object.  Ex: `&ref' is the address
  521. of the referred-to-object, not of the reference itself.
  522.  
  523. ==============================================================================
  524.  
  525. Q13: When should I use references, and when should I use pointers?
  526. A: Old line C programmers sometimes don't like references since the reference
  527. semantics they provide isn't *explicit* in the caller's code.  After a bit of
  528. C++ experience, however, one quickly realizes this `information hiding' is an
  529. asset rather than a liability.  In particular, reuse-centered OOP tends to
  530. migrate the level of abstraction away from the language of the machine toward
  531. the language of the problem.
  532.  
  533. References are usually preferred over ptrs whenever you don't need `reseating'
  534. (see early question on `How can you reseat a reference').  This usually means
  535. that references are most useful in a class' public interface.  References then
  536. typically appear on the skin of an object, and pointers on the inside.
  537.  
  538. The exception to the above is where a function's parameter or return value
  539. needs a `sentinel' reference.  This is usually best done by returning/taking a
  540. pointer, and giving the NULL pointer this special significance (references
  541. should always alias *objects*, not a dereferenced NULL ptr).
  542.  
  543. ==============================================================================
  544.  
  545. Q14: What are inline fns? What are their advantages? How are they declared?
  546. A: An inline function is a function which gets textually inserted by the
  547. compiler, much like a macro.  Like macros, performance is improved by avoiding
  548. the overhead of the call itself, and (especially!) by the compiler being able
  549. to optimize *through* the call (`procedural integration').  Unlike macros,
  550. arguments to inline fns are always evaluated exactly once, so the `call' is
  551. semantically like a regular function call only faster.  Also unlike macros,
  552. argument types are checked and necessary conversions are performed correctly.
  553.  
  554. Beware that overuse of inline functions can cause code bloat, which can in
  555. turn have a negative performance impact in paging environments.
  556.  
  557. They are declared by using the `inline' keyword when the function is defined:
  558.  inline void f(int i, char c) { /*...*/ }   //an inline function
  559. or by including the function definition itself within a class:
  560.  class X {
  561.  public:
  562.    void f(int i, char c) { /*...*/ }   //inline function within a class
  563.  };
  564. or by defining the member function as `inline' outside the class:
  565.  class X {
  566.  public:
  567.    void f(int i, char c);
  568.  };
  569.  //...
  570.  inline void X::f(int i, char c) {/*...*/} //inline fn outside the class
  571.  
  572. Generally speaking, a function cannot be defined as `inline' after it has been
  573. called.  Inline functions should be defined in a header file, with `outlined'
  574. functions appearing in a `.C' file (or .cpp, etc; see question on file naming
  575. conventions).
  576.  
  577. ==============================================================================
  578.  
  579.   ****  PART 04 -- Constructors and destructors  ****
  580.  
  581. ==============================================================================
  582.  
  583. Q15: What is a constructor?  Why would I ever use one?
  584. A: Objects should establish and maintain their own internal coherence.  The
  585. `maintaining' part is done by ensuring self-consistency is restored after any
  586. operation completes (ex: by incrementing the link count after adding a new link
  587. to a linked list).  The part about `establishing coherence' is the job of a
  588. constructor.
  589.  
  590. Constructors are like `init functions'; they build a valid object.  The
  591. constructor turns a pile of incoherent arbitrary bits into a living object.
  592. Minimally it initializes any internally used fields that are needed, but it may
  593. also allocate resources (memory, files, semaphores, sockets, ...).
  594.  
  595. A constructor is like a `factory': it builds objects from dust.
  596.  
  597. `ctor' is a typical abbreviation for constructor.
  598.  
  599. ==============================================================================
  600.  
  601. Q16: How can I make a constructor call another constructor as a primitive?
  602. A: You can't.  Use an `init()' member function instead (often `private:').
  603.  
  604. ==============================================================================
  605.  
  606. Q17: What are destructors really for?  Why would I ever use them?
  607. A: Destructors are used to release any resources allocated by the object's
  608. constructor.  Ex: a Lock class might lock a semaphore, and the destructor will
  609. release that semaphore.  The usual `resource' being acquired in a constructor
  610. (and subsequently released in a destructor) is dynamically allocated memory.
  611.  
  612. `dtor' is a typical abbreviation for destructor
  613.  
  614. ==============================================================================
  615.  
  616.   ****  PART 05 -- Operator overloading  ****
  617.  
  618. ==============================================================================
  619.  
  620. Q18: What is operator overloading?
  621. A: Operator overloading allows the basic C/C++ operators to have user-defined
  622. meanings on user-defined types (classes).  They are syntactic sugar for
  623. equivalent function calls; ex:
  624.  
  625.  class X {
  626.    //...
  627.  public:
  628.    //...
  629.  };
  630.  
  631.  X add(X, X); //a top-level function that adds two X's
  632.  X mul(X, X); //a top-level function that multiplies two X's
  633.  
  634.  X f(X a, X b, X c)
  635.  {
  636.    return add(add(mul(a,b), mul(b,c)), mul(c,a));
  637.  }
  638.  
  639. Now merely replace `add' with `operator+' and `mul' with `operator*':
  640.  
  641.  X operator+(X, X); //a top-level function that adds two X's
  642.  X operator*(X, X); //a top-level function that multiplies two X's
  643.  
  644.  X f(X a, X b, X c)
  645.  {
  646.    return a*b + b*c + c*a;
  647.  }
  648.  
  649. ==============================================================================
  650.  
  651. Q19: What operators can/cannot be overloaded?
  652. A: Most can be overloaded. The only C operators that can't be are `.' and `?:'
  653. (and `sizeof', which is technically an operator).  C++ adds a few of its own
  654. operators, most of which can be overloaded except `::' and `.*'.
  655.  
  656. Here's an example of the subscript operator (it returns a reference).
  657. First withOUT operator overloading:
  658.  class Vec {
  659.    int data[100];
  660.  public:
  661.    int& elem(unsigned i) { if (i>99) error(); return data[i]; }
  662.  };
  663.  
  664.  main()
  665.  {
  666.    Vec v;
  667.    v.elem(10) = 42;
  668.    v.elem(12) += v.elem(13);
  669.  }
  670.  
  671. Now simply replace `elem' with `operator[]':
  672.  class Vec {
  673.    int data[100];
  674.  public:
  675.    int& operator[](unsigned i) { if (i>99) error(); return data[i]; }
  676.  };   //^^^^^^^^^^--formerly `elem'
  677.  
  678.  main()
  679.  {
  680.    Vec v;
  681.    v[10] = 42;
  682.    v[12] += v[13];
  683.  }
  684.  
  685. ==============================================================================
  686.  
  687. Q20: Can I create a `**' operator for `to-the-power-of' operations?
  688. A: No.
  689.  
  690. The names of, precedence of, associativity of, and arity of operators is fixed
  691. by the language.  There is no `**' operator in C++, so you cannot create one
  692. for a class type.
  693.  
  694. If you doubt the wisdom of this approach, consider the following code:
  695.  x = y ** z;
  696. Looks like your power operator?  Nope.  z may be a ptr, so this is actually:
  697.  x = y * (*z);
  698. Lexical analysis groups characters into tokens at the lowest level of the
  699. compiler's operations, so adding new operators would present an implementation
  700. nightmare (not to mention the increased maintenance cost to read the code!).
  701.  
  702. Besides, operator overloading is just syntactic sugar for function calls.  It
  703. does not add fundamental power to the language (although this particular
  704. syntactic sugar can be very sweet, it is not fundamentally necessary).  I
  705. suggest you overload `pow(base,exponent)', for which a double precision version
  706. is provided by the ANSI-C <math.h> library.
  707.  
  708. By the way: operator^ looks like a good candidate for to-the-power-of, but it
  709. has neither the proper precedence nor associativity.
  710.  
  711. ==============================================================================
  712.  
  713.   ****  PART 06 -- Friends  ****
  714.  
  715. ==============================================================================
  716.  
  717.  
  718. Q21: What is a `friend'?
  719. A: Friends can be either functions or other classes.  The class grants friends
  720. access privileges.  Normally a developer has political and technical control
  721. over both the class, its members, and its friends (that way you avoid political
  722. problems when you want to update a portion, since you don't have to get
  723. permission from the present owner of the other piece(s)).
  724.  
  725. ==============================================================================
  726.  
  727. Q22: Do `friends' violate encapsulation?
  728. A: Friends can be looked at three ways: (1) they are not class members and they
  729. therefore violate encapsulation of the class members by their mere existence,
  730. (2) a class' friends are absorbed into that class' encapsulation barrier, and
  731. (3) any time anyone wants to do anything tricky they textedit the header file
  732. and add a new friend so they can get right in there and fiddle 'dem bits.
  733.  
  734. No one argues that (3) is a Good Thing, and for good reasons. The arguments for
  735. (1) always boil down to the rather arbitrary and somewhat naive view that a
  736. class' member functions `should' be the *only* functions inside a class'
  737. encapsulation barrier.  I have not seen this view bear fruit by enhancing
  738. software quality.  On the other hand, I have seen (2) bear fruit by lowering
  739. the *overall* coupling in a software system.  Reason: friends can be used as
  740. `liaisons' to provide safe, screened access for the whole world, perhaps in a
  741. way that the class syntactically or semantically isn't able to do for itself.
  742.  
  743. Conclusion: friend functions are merely a syntactic variant of a class' public
  744. access functions.  When used in this manner, they don't violate encapsulation
  745. any more than a member function violates encapsulation.  Thus a class' friends
  746. and members *are* the encapsulation barrier, as defined by the class itself.
  747.  
  748. I've actually seen the `friends always violate encapsulation' view *destroy*
  749. encapsulation: programmers who have been taught that friends are inherently
  750. evil want to avoid them, but they have another class or fn that needs access to
  751. some internal detail in the class, so they provide a member fn which exposes
  752. the class' internal details to the PUBLIC!  Private decisions should stay
  753. private, and only those inside your encapsulation barrier (your members,
  754. friends, and [for `protected' things] your subclasses) should have access.
  755.  
  756. ==============================================================================
  757.  
  758. Q23: What are some advantages/disadvantages of using friends?
  759. A: The advantage of using friends is generally syntactic.  Ie: both a member fn
  760. and a friend are equally privileged (100% vested), but a friend function can be
  761. called like f(obj), where a member is called like obj.f().  When it's not for
  762. syntactic reasons (which is not a `bad' reason -- making an abstraction's
  763. syntax more readable lowers maintenance costs!), friends are used when two or
  764. more classes are designed to be more tightly coupled than you want for `joe
  765. public' (ex: you want to allow class `ListIter' to have more privilege with
  766. class `List' than you want to give to `main()').
  767.  
  768. Friends have three disadvantages.  The first disadvantage is that they add to
  769. the global namespace.  In contrast, the namespace of member functions is buried
  770. within the class, reducing the chance for namespace collisions for functions.
  771.  
  772. The second disadvantage is that they aren't inherited.  That is, the
  773. `friendship privilege' isn't inherited.  This is actually an advantage when it
  774. comes to encapsulation.  Ex: I may declare you as my friend, but that doesn't
  775. mean I trust your kids.
  776.  
  777. The third disadvantage is that they don't bind dynamically.  Ie: they don't
  778. respond to polymorphism.  There are no virtual friends; if you need one, have a
  779. friend call a hidden (usually `protected:') virtual member fn.  Friends that
  780. take a ptr/ref to a class can also take a ptr/ref to a publically derived class
  781. object, so they act as if they are inherited, but the friendship *rights* are
  782. not inherited (the friend of a base has no special access to a class derived
  783. from that base).
  784.  
  785. ==============================================================================
  786.  
  787. Q24: What does it mean that `friendship is neither inherited nor transitive'?
  788. A: This is speaking of the access privileges granted when a class declares a
  789. friend.
  790.  
  791. The access privilege of friendship is not inherited:
  792.  * I may trust you, but I don't necessarily trust your kids.
  793.  * My friends aren't necessarily friends of my kids.
  794.  * Class `Base' declares f() to be a friend, but f() has no special access
  795.    rights with class `Derived'.
  796.  
  797. The access privilege of friendship is not transitive:
  798.  * I may trust you, and you may trust Sam, but that doesn't necessarily mean
  799.    that I trust Sam.
  800.  * A friend of a friend is not necessarily a friend.
  801.  
  802. ==============================================================================
  803.  
  804. Q25: When would I use a member function as opposed to a friend function?
  805. A: Use a member when you can, and a friend when you have to.
  806.  
  807. Like in real life, my family members have certain privileges that my friends do
  808. not have (ex: my family members inherit from me, but my friends do not, etc).
  809. To grant privileged access to a function, you need either a friend or a member;
  810. there is no additional loss of encapsulation one way or the other.  Sometimes
  811. friends are syntactically better (ex: in class `X', friend fns allow the `X'
  812. param to be second, while members require it to be first).  Another good use of
  813. friend functions are the binary infix arithmetic operators.  Ex: `aComplex +
  814. aComplex' probably should be defined as a friend rather than a member, since
  815. you want to allow `aFloat + aComplex' as well (members don't allow promotion of
  816. the left hand arg, since that would change the class of the object that is the
  817. recipient of the message).
  818.  
  819. ==============================================================================
  820.  
  821. ==============================================================================
  822.  
  823.  ****  PART 07 -- Input/output via <iostream.h> and <stdio.h>  ****
  824.  
  825. ==============================================================================
  826.  
  827. Q26: How can I provide printing for a `class X'?
  828. A: Provide a friend operator<<:
  829.  
  830.     class X {
  831.     public:
  832.       friend ostream& operator<< (ostream& o, const X& x)
  833.         { return o << x.i; }
  834.       //...
  835.     private:
  836.       int i;    //just for illustration
  837.     };
  838.  
  839. We use a friend rather than a member since the `X' parameter is 2nd, not 1st.
  840. Input is similar, but the signature is:
  841.  istream& operator>> (istream& i, X& x);  //not `const X& x' !!
  842.  
  843. ==============================================================================
  844.  
  845. Q27: Why should I use <iostream.h> instead of the traditional <stdio.h>?
  846. A: See next question.
  847.  
  848. ==============================================================================
  849.  
  850. Q28: Printf/scanf weren't broken; why `fix' them with ugly shift operators?
  851. A: The overloaded shift operator syntax is strange at first sight, but it
  852. quickly grows on you.  However syntax is just syntax; the real issues are
  853. deeper.  Printf is arguably not broken, and scanf is perhaps livable despite
  854. being error prone, however both are limited with respect to what C++ I/O can
  855. do.  C++ I/O (left/right shift) is, relative to C (printf/scanf):
  856.  * type safe -- type of object being I/O'd is known statically by the compiler
  857.  rather than via dynamically tested '%' fields
  858.  * less error prone -- redundant info has greater chance to get things wrong
  859.  C++ I/O has no redundant '%' tokens to get right
  860.  * faster -- printf is basically an `interpreter' of a tiny language whose
  861.  constructs mainly include '%' fields.  the proper low-level routine is
  862.  chosen at runtime based on these fields.  C++ I/O picks these routines
  863.  statically based on actual types of the args
  864.  * extensible -- perhaps most important of all, the C++ I/O mechanism is
  865.  extensible to new user-defined data types (imagine the chaos if
  866.  everyone was simultaneously adding new incompatible '%' fields to
  867.  printf and scanf?!).  Remember: we want to make user-defined types
  868.  (classes) look and act like `built-in' types.
  869.  * subclassable -- ostream and istream (the C++ replacements for FILE*) are
  870.  real classes, and hence subclassable.  This means you can have other
  871.  user defined things that look and act like streams, yet that do
  872.  whatever strange and wonderful things you want.  You automatically
  873.  get to use the zillions of lines of I/O code written by users you
  874.  don't even know, and they don't need to know about your `extended
  875.  stream' class.  Ex: you can have a `stream' that writes to a memory
  876.  area (incore formatting provided by the standard class `strstream'),
  877.  or you could have it use the stdio buffers, or [you name it...].
  878.  
  879. ==============================================================================
  880.  
  881.   ****  PART 08 -- Freestore management  ****
  882.  
  883. ==============================================================================
  884.  
  885. Q29: Does `delete ptr' delete the ptr or the pointed-to-data?
  886. A: The pointed-to-data.
  887.  
  888. When you read `delete p', say to yourself `delete the thing pointed to by p'.
  889. One could argue that the keyword is misleading, but the same abuse of English
  890. occurs when `free'ing the memory pointed to by a ptr in C:
  891.  free(ptr); /* why not `free_the_stuff_pointed_to_by(p)' ?? */
  892.  
  893. ==============================================================================
  894.  
  895. Q30: Can I free() ptrs alloc'd with `new' or `delete' ptrs alloc'd w/ malloc()?
  896. A: No.  You should not mix C and C++ heap management.
  897.  
  898. ==============================================================================
  899.  
  900. Q31: Why should I use `new' instead of trustworthy old malloc()?
  901. A: malloc() doesn't call constructors, and free() doesn't call destructors.
  902. Besides, malloc() isn't type safe, since it returns a `void*' rather than a ptr
  903. of the right type (ANSI-C punches a hole in its typing system to make it
  904. possible to use malloc() without pointer casting the return value, but C++
  905. closes that hole).  Besides, `new' is an operator that can be overridden by a
  906. class, while `malloc' is not overridable on a per-class basis (ie: even if the
  907. class doesn't have a constructor, allocating via malloc might do inappropriate
  908. things if the freestore operations have been overridden).
  909.  
  910. ==============================================================================
  911.  
  912. Q32: Why doesn't C++ have a `realloc()' along with `new' and `delete'?
  913. A: Because realloc() does *bitwise* copies (when it has to copy), which will
  914. tear most C++ objects to shreds.  C++ objects know how to copy themselves.
  915. They use their own copy constructor or assignment operator (depending on
  916. whether we're copying into a previously unused space [copy-ctor] or a previous
  917. object [assignment op]).
  918.  
  919. Moral: never use realloc() on objects of a class.  Let the class copy its own
  920. objects.
  921.  
  922. ==============================================================================
  923.  
  924. Q33: How do I allocate / unallocate an array of things?
  925. A: Use new[] and delete[]:
  926.  
  927.  Thing* p = new Thing[100];
  928.  //...
  929.  delete [] p; //older compilers require you to use `delete [100] p'
  930.  
  931. Any time you allocate an array of things (ie: any time you use the `[...]' in
  932. the `new' expression) you *!*MUST*!* use the `[]' in the `delete' statement.
  933.  
  934. The fact that there is no syntactic difference between a ptr to a thing and a
  935. ptr to an array of things is an artifact we inherited from C.
  936.  
  937. ==============================================================================
  938.  
  939. Q34: What if I forget the `[]' when `delete'ing array allocated via `new X[n]'?
  940. A: Life as we know it suddenly comes to a catastrophic end.
  941.  
  942. It is the programmer's --not the compiler's-- responsibility to get the
  943. connection between new[] and delete[] correct.  If you get it wrong, neither a
  944. compile-time nor a run-time error message will be generated by the compiler.
  945.  
  946. Heap corruption is a likely result.
  947.  
  948. ==============================================================================
  949.  
  950.   ****  PART 09 -- Debugging and error handling  ****
  951.  
  952. ==============================================================================
  953.  
  954. Q35: How can I handle a constructor that fails?
  955. A: Constructors (ctors) do not return any values, so no returned error code
  956. is possible.  The best way to handle failure is therefore to `throw' an
  957. exception.
  958.  
  959. If your compiler doesn't yet support exceptions, several possibilities remain.
  960. The simplest is to put the object itself into a `half baked' state by setting
  961. an internal status bit.  Naturally there should be a query (`inspector') method
  962. to check this bit, allowing clients to discover whether they have a live
  963. object.  Other member functions should check this bit, and either do a no-op
  964. (or perhaps something more obnoxious such as `abort()') if the object isn't
  965. really alive.  Check out how the iostreams package handles attempts to open
  966. nonexistent/illegal files for an example of prior art.
  967.  
  968. ==============================================================================
  969.  
  970. Q36: How can I compile-out my debugging print statements?
  971. A: This will NOT work, since comments are parsed before the macro is expanded:
  972.  #ifdef DEBUG_ON
  973.    #define  DBG
  974.  #else
  975.    #define  DBG  //
  976.  #endif
  977.  DBG cout << foo;
  978.  
  979. This is the simplest technique:
  980.  #ifdef DEBUG_ON
  981.    #define  DBG(anything)  anything
  982.  #else
  983.    #define  DBG(anything)  /*nothing*/
  984.  #endif
  985.  
  986. Then you can say:
  987.  //...
  988.  DBG(cout << "the value of foo is " << foo << '\n');
  989.  //                                                ^-- `;' outside ()
  990.  
  991. Any commas in your `DBG()' statement must be enclosed in a `()':
  992.  DBG(i=3, j=4); //<---- C-preprocessor will generate error message
  993.  DBG(i=3; j=4); //<---- ok
  994.  
  995. There are also more complicated techniques that use variable argument lists,
  996. but these are primarily useful for `printf()' style (see question on the pros
  997. and cons of <iostream.h> as opposed to <stdio.h> for more).
  998.  
  999. ==============================================================================
  1000.  
  1001.   ****  PART 10 -- Const correctness  ****
  1002.  
  1003. ==============================================================================
  1004.  
  1005. Q37: What is `const correctness'?
  1006. A: A program is `const correct' if it never mutates a constant object.  This is
  1007. achieved by using the keyword `const'.  Ex: if you pass a String to a function
  1008. `f()', and you wish to prohibit `f()' from modifying the original String, you
  1009. can either pass by value: void  f(      String  s   )  { /*...*/ }
  1010. or by constant reference: void  f(const String& s   )  { /*...*/ }
  1011. or by constant pointer:  void  f(const String* sptr)  { /*...*/ }
  1012. but *not* by non-const ref: void  f(      String& s   )  { /*...*/ }
  1013. *nor* by non-const pointer: void  f(      String* sptr)  { /*...*/ }
  1014.  
  1015. Attempted changes to `s' within a fn that takes a `const String&' are flagged
  1016. as compile-time errors; neither run-time space nor speed is degraded.
  1017.  
  1018. ==============================================================================
  1019.  
  1020. Q38: Is `const correctness' a good goal?
  1021. A: Declaring the `constness' of a parameter is just another form of type
  1022. safety.  It is almost as if a constant String, for example, `lost' its various
  1023. mutative operations.  If you find type safety helps you get systems correct
  1024. (especially large systems), you'll find const correctness helps also.
  1025.  
  1026. Short answer: yes, const correctness is a good goal.
  1027.  
  1028. ==============================================================================
  1029.  
  1030. Q39: Is `const correctness' tedious?
  1031. A: Type safety requires you to annotate your code with type information.  In
  1032. theory, expressing this type information isn't necessary -- witness untyped
  1033. languages as an example of this.  However in practice, programmers often know
  1034. in their heads a lot of interesting information about their code, so type
  1035. safety (and, by extension, const correctness) merely provide structured ways to
  1036. get this information into their keyboards.
  1037.  
  1038. Short answer: yes, const correctness is tedious.
  1039.  
  1040. ==============================================================================
  1041.  
  1042. Q40: Should I try to get things const correct `sooner' or `later'?
  1043. A: Back-patching const correctness is *very* expensive.  Every `const' you add
  1044. `over here' requires you to add four more `over there'.  The snowball effect is
  1045. magnificent -- unless you have to pay for it.  Long about the middle of the
  1046. process, someone stumbles on a function that needs to be const but can't be
  1047. const, and then they know why their system wasn't functioning correctly all
  1048. along.  This is the benefit of const correctness, but it should be installed
  1049. from the beginning.
  1050.  
  1051. Short answer: CONST CORRECTNESS SHOULD NOT BE DONE RETROACTIVELY!!
  1052.  
  1053. ==============================================================================
  1054.  
  1055. Q41: What is a `const member function'?
  1056. A: A const member function is a promise to the caller not to change the object.
  1057. Put the word `const' after the member function's signature; ex:
  1058.  class X {
  1059.    //...
  1060.    void f() const;
  1061.  };
  1062.  
  1063. Some programmers feel this should be a signal to the compiler that the raw bits
  1064. of the object's `struct' aren't going to change, others feel it means the
  1065. *abstract* (client-visible) state of the object isn't going to change.  C++
  1066. compilers aren't allowed to assume the bitwise const, since a non-const alias
  1067. could exist which could modify the state of the object (gluing a `const' ptr to
  1068. an object doesn't promise the object won't change; it only promises that the
  1069. object won't change **via that pointer**).
  1070.  
  1071. I talked to Jonathan Shopiro at the C++AtWork conference, and he confirmed that
  1072. the above view has been ratified by the ANSI-C++ standards board.  This doesn't
  1073. make it a `perfect' view, but it will make it `the standard' view.
  1074.  
  1075. See the next few questions for more.
  1076.  
  1077. ==============================================================================
  1078.  
  1079. Q42: What is an `inspector'?  What is a `mutator'?
  1080. A: An inspector inspects and a mutator mutates.  These different categories of
  1081. member fns are distinguished by whether the member fn is `const' or not.
  1082.  
  1083. ==============================================================================
  1084.  
  1085. Q43: What is `casting away const in an inspector' and why is it legal?
  1086. A: In current C++, const member fns are allowed to `cast away the const-ness of
  1087. the "this" ptr'.  Programmers use (some say `misuse') this to tickle internally
  1088. used counters, cache values, or some other non-client-visible change.  Since
  1089. C++ allows you to use const member fns to indicate the abstract/meaning-wise
  1090. state of the object doesn't change (as opposed to the concrete/bit-wise state),
  1091. the `meaning' of the object shouldn't change during a const member fn.
  1092.  
  1093. Those who believe `const' member fns shouldn't be allowed to change the bits of
  1094. the struct itself call the `abstract const' view `Humpty Dumpty const' (Humpty
  1095. Dumpty said that words mean what he wants them to mean).  The response is that
  1096. a class' public interface *should* mean exactly what the class designer wants
  1097. it to mean, in Humpty Dumpty's words, `nothing more and nothing less'.  If the
  1098. class designer says that accessing the length of a List doesn't change the
  1099. List, then one can access the length of a `const' List (even though the `len()'
  1100. member fn may internally cache the length for future accesses).
  1101.  
  1102. Some proposals are before the ANSI/ISO C++ standards bodies to provide syntax
  1103. that allows individual data members to be designated as `can be modified in a
  1104. const member fn' using a prefix such as `~const'.  This would blend the best of
  1105. the `give the compiler a chance to cache data across a const member fn', but
  1106. only if aliasing can be solved (see next question).
  1107.  
  1108. ==============================================================================
  1109.  
  1110. Q44: But doesn't `cast away const' mean lost optimization opportunities?
  1111. A: If the object is constructed in the scope of the const member fn invocation,
  1112. and if all the non-const member function invocations between the object's
  1113. construction and the const member fn invocation are statically bound, and if
  1114. every one of these invocations is also `inline'd, and if the ctor itself is
  1115. `inline', and if any member fns the ctor calls are inline, then the answer is
  1116. `Yes, the soon-to-be-standard interpretation of the language would prohibit a
  1117. very smart compiler from detecting the above scenario, and the register cache
  1118. would be unnecessarily flushed'.  The reader should judge whether the above
  1119. scenario is common enough to warrant a language change which would break
  1120. existing code.
  1121.  
  1122. ==============================================================================
  1123.  
  1124.   ****  PART 11 -- Inheritance  ****
  1125.  
  1126. ==============================================================================
  1127.  
  1128. Q45: What is inheritance?
  1129. A: Inheritance is what separates abstract data type (ADT) programming from OOP.
  1130. It is not a `dark corner' of C++ by any means.  In fact, everything discussed
  1131. so far could be simulated in your garden variety ADT programming language (ex:
  1132. Ada, Modula-2, C [with a little work], etc).  Inheritance and the consequent
  1133. (subclass) polymorphism are the two big additions which separate a language
  1134. like Ada from an object-oriented programming language.
  1135.  
  1136. ==============================================================================
  1137.  
  1138. Q46: Ok, ok, but what is inheritance?
  1139. A: Human beings abstract things on two dimensions: part-of and kind-of.  We say
  1140. that a Ford Taurus is-a-kind-of-a Car, and that a Ford Taurus has parts such as
  1141. Engine, Tire, etc.  The part-of hierarchy has been a first class part of
  1142. software since the ADT style became relevant, but programmers have had to whip
  1143. up their own customized techniques for simulating kind-of (usually in an ad hoc
  1144. manner).  Inheritance changes that; it adds `the other' major dimension of
  1145. decomposition.
  1146.  
  1147. An example of `kind-of decomposition', consider the genus/species biology
  1148. charts.  Knowing the internal parts of various fauna and flora is important for
  1149. certain applications, but knowing the groupings (kinds, categories) is equally
  1150. important.
  1151.  
  1152. ==============================================================================
  1153.  
  1154. Q47: How do you express inheritance in C++?
  1155. A: By the `: public' syntax:
  1156.  
  1157.  class Car : public Vehicle {
  1158.          //^^^^^^^^---- `: public' is pronounced `is-a-kind-of-a'
  1159.    //...
  1160.  };
  1161.  
  1162. We state the above relationship in several ways:
  1163.  * Car is `a kind of a' Vehicle
  1164.  * Car is `derived from' Vehicle
  1165.  * Car is `a specialized' Vehicle
  1166.  * Car is the `subclass' of Vehicle
  1167.  * Vehicle is the `base class' of Car
  1168.  * Vehicle is the `superclass' of Car (this not as common in the C++ community)
  1169.  
  1170. ==============================================================================
  1171.  
  1172. Q48: What is `incremental programming'?
  1173. A: In addition to being an abstraction mechanism that makes is-a-kind-of
  1174. relationships explicit, inheritance can also be used as a means of `incremental
  1175. programming'.  A derived class inherits all the representation (bits) of its
  1176. base class, plus all the base class' mechanism (code).  Another device (virtual
  1177. functions, described below) allows derived classes to selectively override some
  1178. or all of the base class' mechanism (replace and/or enhance the various
  1179. algorithms).
  1180.  
  1181. This simple ability is surprisingly powerful: it effectively adds a `third
  1182. dimension' to programming.  After becoming fluent in C++, most programmers find
  1183. languages like C and Ada to be `flat' (a cute little book, `Flatland', aptly
  1184. describes those living in a two dimensional plane, and their disbelief about a
  1185. strange third dimension that is somehow neither North, South, East nor West,
  1186. but is `Up').
  1187.  
  1188. As a trivial example, suppose you have a Linked List that is too slow, and you
  1189. wish to cache its length.  You could `open up' the List `class' (or `module'),
  1190. and modify it directly (which would certainly be appropriate for such a simple
  1191. situation), but suppose the List's physical size is critical, and some
  1192. important client cannot afford to add the extra machine word to every List.
  1193. Another option would be to textually copy the List module and modify the copy,
  1194. but this increases the amount of code that must be maintained, and also
  1195. presumes you have access to the internal source code of the List module.  The
  1196. OO solution is to realize that a List that caches its length is-a-kind-of-a
  1197. List, so we inherit:
  1198.  
  1199.  class FastList : public List {
  1200.  public:
  1201.    //override operations so the cache stays `hot'
  1202.  protected:
  1203.    int length; //cache the length here
  1204.  };
  1205.  
  1206. ==============================================================================
  1207.  
  1208. Q49: Should I pointer-cast from a derived class to its base class?
  1209. A: The short answer: yes -- you don't even need the `cast'.
  1210.  
  1211. Long answer: a derived class is a specialized version of the base class
  1212. (`Derived is-a-kind-of-a Base').  The upward conversion is perfectly safe, and
  1213. happens all the time (a ptr to a Derived is in fact pointing to a [specialized
  1214. version of a] Base):
  1215.     void f(Base* base_ptr);
  1216.     void g(Derived* derived_ptr) { f(derived_ptr); }  //perfectly safe; no cast
  1217.  
  1218. (note that the answer to this question assumes we're talking about `public'
  1219. derivation; see below on `private/protected' inheritance for `the other kind').
  1220.  
  1221. ==============================================================================
  1222.  
  1223. Q50: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
  1224. A: A C++ compiler will allow a Derived* to masquerade as a Base*, since a
  1225. Derived object is a kind of a Base object.  However passing a Derived** as a
  1226. Base** (or otherwise trying to convert a Derived** to a Base**) is (correctly)
  1227. flagged as an error.
  1228.  
  1229. An array of Deriveds is-NOT-a-kind-of-an array of Bases.  I like to use the
  1230. following example in my C++ training sessions:
  1231.   `A Bag of Apples is *NOT* a Bag of Fruit'
  1232.  
  1233. Suppose a `Bag<Apple>' could be passed to a function taking a Bag<Fruit> such
  1234. as `f(Bag<Fruit>& b)'.  But `f()' can insert *any* kind of Fruit into the Bag.
  1235. Imagine the surprise on the caller's face when he gets the Bag back only to
  1236. find it has a Banana in it!
  1237.  
  1238. Here's another example I use:
  1239.  A ParkingLot of Car is-NOT-a-kind-of-a ParkingLot of Vehicle
  1240. (otherwise you could pass a ParkingLot<Car>* as a ParkingLot<Vehicle>*, and the
  1241. called fn could park an EighteenWheeler in a ParkingLot designed for Cars!)
  1242.  
  1243. These improper things are violations of `contravariance' (that's the scientific
  1244. glue that holds OOP together).  C++ enforces contravariance, so you should
  1245. trust your compiler at moments like these.  Contravariance is more solid than
  1246. our fickle intuition.
  1247.  
  1248. ==============================================================================
  1249.  
  1250. Q51: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are bad?
  1251. A: Yes, `arrays are evil' (jest kidd'n :-).
  1252.  
  1253. There's a very subtle problem with using raw built-in arrays.  Consider this:
  1254.  
  1255.  void f(Base* array_of_Base)
  1256.  {
  1257.    array_of_Base[3].memberfn();
  1258.  }
  1259.  
  1260.  main()
  1261.  {
  1262.    Derived array_of_Derived[10];
  1263.    f(array_of_Derived);
  1264.  }
  1265.  
  1266. This is perfectly type-safe, since a D* is-a B*, but it is horrendously evil,
  1267. since Derived might be larger than Base, so the array index in f() not only
  1268. isn't type safe, it's not even going to be pointing at a real object!  In
  1269. general it'll be pointing somewhere into the innards of some poor D.
  1270.  
  1271. The fundamental problem here is that C++ cannot distinguish a ptr-to-a-thing
  1272. from a ptr-to-an-array-of-things (witness the required `[]' in `delete[]' when
  1273. deleting an array as another example of how these different kinds of ptrs are
  1274. actually different).  Naturally C++ `inherited' this feature from C.
  1275.  
  1276. This underscores the advantage of using an array-like *class* instead of using
  1277. a raw array (the above problem would have been properly trapped as an error if
  1278. we had used a `Vec<T>' rather than a `T[]'; ex: you cannot pass a Vec<Derived>
  1279. to `f(Vec<Base>& v)').
  1280.  
  1281. ==============================================================================
  1282. SUBSECTION: Inheritance -- virtual functions
  1283. ==============================================================================
  1284.  
  1285. Q52: What is a `virtual member function'?
  1286. A: A virtual member function is a member fn preceded by the keyword `virtual'.
  1287.  
  1288. It has the effect of allowing derived classes to replace the implementation of
  1289. the fn.  Furthermore the replacement is always called whenever the object in
  1290. question is actually of the derived class.  The impact is that algorithms in
  1291. the base class can be replaced in the derived class without affecting the
  1292. operation of the base class.  The replacement can be either full or partial,
  1293. since the derived class operation can invoke the base class version if desired.
  1294.  
  1295. This is discussed further below.
  1296.  
  1297. ==============================================================================
  1298.  
  1299. Q53: What is dynamic dispatch?  Static dispatch?
  1300. A: In the following discussion, `ptr' means either a pointer or a reference.
  1301.  
  1302. When you have a ptr to an object, there are two distinct types in question: the
  1303. static type of the ptr, and the dynamic type of the pointed-to object (the
  1304. object may actually be of a class that is derived from the class of the ptr).
  1305.  
  1306. The `legality' of the call is checked based on the static type of the ptr,
  1307. which gives us static type safety (if the type of the ptr can handle the member
  1308. fn, certainly the pointed-to object can handle it as well, since the pointed-to
  1309. object is of a class that is derived from the ptr's class).
  1310.  
  1311. Suppose ptr's type is `List' and the pointed-to object's type is `FastList'.
  1312. Suppose the fn `len()' is provided in `List' and overridden in `FastList'.  The
  1313. question is: which function should actually be invoked: the function attached
  1314. to the pointer's type (`List::len()') or the function attached to the object
  1315. itself (`FastList::len()')?
  1316.  
  1317. If `len()' is a virtual function, as it would be in the above case, the fn
  1318. attached to the object is invoked.  This is called `dynamic binding', since the
  1319. actual code being called is determined dynamically (at run time).
  1320.  
  1321. On the other hand, if `len()' were non-virtual, the dispatch would be resolved
  1322. statically to the fn attached to the ptr's class.
  1323.  
  1324. ==============================================================================
  1325.  
  1326. Q54: Can I override a non-virtual fn?
  1327. A: Yes but you shouldn't.  The only time you should do this is to get around
  1328. the `hiding rule' (see below, and ARM sect.13.1), and the overridden definition
  1329. should be textually identical to the base class' version.
  1330.  
  1331. The above advice will keep you out of trouble, but it is a bit too strong.
  1332. Experienced C++ programmers will sometimes override a non-virtual fn for
  1333. efficiency, and will provide an alternate implementation which makes better use
  1334. of the derived class' resources.  However the client-visible effects must be
  1335. *identical*, since non-virtual fns are dispatched based on the static type of
  1336. the ptr/ref rather than the dynamic type of the pointed-to/referenced object.
  1337.  
  1338. ==============================================================================
  1339.  
  1340. Q55: Why do I get the warning "Derived::foo(int) hides Base::foo(double)"?
  1341. A: A member function in a derived class will *hide* all member functions of the
  1342. same name in the base class, *not* overload them, even if Base::foo(double) is
  1343. virtual (see ARM 13.1).  This is done because it was felt that programmers
  1344. would, for example, call a_derived.foo(1) and expect Derived::foo(double) to be
  1345. called.  If you define any member function with the name `foo' in a derived
  1346. class, you must redefine in class Derived all other Base::foo()'s that you wish
  1347. to allow access from a Derived object (which generally means all of them; you
  1348. should [generally] *not* try to hide inherited public member functions since it
  1349. breaks the `conformance' of the derived class with respect to the base class).
  1350.  
  1351.    class Base {
  1352.    public:
  1353.      void foo(int);
  1354.    };
  1355.  
  1356.    class Derived : public Base {
  1357.    public:
  1358.      void foo(double);
  1359.      void foo(int i) { Base::foo(i); } // <-- override it with itself
  1360.    };
  1361.  
  1362. ==============================================================================
  1363. SUBSECTION: Inheritance -- conformance
  1364. ==============================================================================
  1365.  
  1366. Q56: Can I `revoke' or `hide' public member fns inherited from my base class?
  1367. A: Never never never do this.  Never.  NEVER!
  1368.  
  1369. This is an all-too-common design error.  It usually stems from muddy thinking
  1370. (but sometimes it stems from a very difficult design that doesn't seem to yield
  1371. anything elegant).
  1372.  
  1373. ==============================================================================
  1374.  
  1375. Q57: Is a `Circle' a kind-of an `Ellipse'?
  1376. A: Depends on what you claim an Ellipse can do.  Ex: suppose Ellipse has a
  1377. `scale(x,y)' method, which is meaningless for Circle.
  1378.  
  1379. There are no easy options at this point, but the worst of all possible worlds
  1380. is to keep muddling along and hope that no one stubs their toes over the bad
  1381. design (if we're serious about reuse, we should fix our mistakes rather than
  1382. leave them to a future generation).  If an Ellipse can do something a Circle
  1383. can't, a Circle can't be a kind of Ellipse.  Should there be any other
  1384. relationship between Circle and Ellipse?  Here are two reasonable options:
  1385.  * make Circle and Ellipse completely unrelated classes.
  1386.  * derive Circle and Ellipse from a base class representing `Ellipses that
  1387.    can't *necessarily* perform an unequal-scale operation'.
  1388.  
  1389. In the first case, Ellipse could be derived from class `AsymmetricShape' (with
  1390. scale(x,y) being introduced in AsymmetricShape), and Circle should be derived
  1391. from `SymmetricShape', which has a scale(factor) member fn.
  1392.  
  1393. In the second case, we could create class `Oval' that has only an equal scale
  1394. operation, then derive both `Ellipse' and `Circle' from Oval, where Ellipse
  1395. --but not Circle-- adds the unequal scale operation (see the `hiding rule' for
  1396. a caveat if the same method name `scale' is used for both unequal and equal
  1397. scale operations).
  1398.  
  1399. In any event, we could create an operation to create an Ellipse whose size et
  1400. al are the same as a given Circle, but this would be a constructive operation
  1401. (ie: it would create a brand new object, like converting an int to a float, but
  1402. unlike passing a reference to a Circle as if it were a ref to an Ellipse).
  1403.  
  1404. Example: class Ellipse : public Oval {
  1405.   public:       ^^^^^^^^^^^^^---- or whatever
  1406.     Ellipse(const Circle& circle);
  1407.     //...
  1408.   };
  1409.  
  1410. Or:  class Circle /*...*/ {
  1411.   public:
  1412.     operator Ellipse() const;
  1413.     //...
  1414.   };
  1415.  
  1416. ==============================================================================
  1417.  
  1418. Q58: Are there other options to the `Circle is/isnot kind-of Ellipse' dilemma?
  1419. A: There appear to be 2 other options (but read below for why these are poor):
  1420.  * redefine Circle::scale(x,y) to throw an exception or call `abort()'.
  1421.  * redefine Circle::scale(x,y) to be a no-op, or to scale both dimensions by
  1422.    the average of the parameters (or some other arbitrary value).
  1423.  
  1424. Throwing an exception will `surprise' clients.  You claimed that a Circle was
  1425. actually a kind of an Ellipse, so they pass a Circle off to `f(Ellipse& e)'.
  1426. The author of this function read the contract for Ellipse very carefully, and
  1427. scale(x,y) is definitely allowed.  Yet when f() innocently calls e.scale(5,3),
  1428. it kills him!  Conclusion: you lied; what you gave them was distinctly *not* an
  1429. Ellipse.
  1430.  
  1431. In the second case, you'll find it to be very difficult to write a meaningful
  1432. semantic specification (a `contract') for Ellipse::scale(x,y).  You'd like to
  1433. be able to say it scales the x-axis by `x' and the y-axis by `y', but the best
  1434. you can say is `it may do what you expect, or it may do nothing, or it may
  1435. scale both x and y even if you asked it to only scale the x (ex: `scale(2,1)').
  1436. Since you've diluted the contract into dribble, the client can't rely on any
  1437. meaningful behavior, so the whole hierarchy begins to be worthless (it's hard
  1438. to convince someone to use an object if you have to shrug your shoulders when
  1439. asked what the object does for them).
  1440.  
  1441. ==============================================================================
  1442. SUBSECTION: Inheritance -- access rules
  1443. ==============================================================================
  1444.  
  1445. Q59: Why can't I access `private' things in a base class from a derived class?
  1446. A: Derived classes do not get access to private members of a base class.  This
  1447. effectively `seals off' the derived class from any changes made to the private
  1448. members of the base class.
  1449.  
  1450. ==============================================================================
  1451.  
  1452. Q60: What's the difference between `public:', `private:', and `protected:'?
  1453. A: `Private' is discussed in the previous section, and `public' means `anyone
  1454. can access it'.  The third option, `protected', makes a member (either data
  1455. member or member fn) accessible to subclasses.
  1456.  
  1457. Thus members defined in the `private:' section of class X are accessible only
  1458. to the member functions and friends of class X; members defined in the
  1459. `public:' section are accessible by everyone; `protected:' members are
  1460. accessible by members fns and friends of class X, as well as member fns of
  1461. subclasses of X.
  1462.  
  1463. ==============================================================================
  1464.  
  1465. Q61: How can I protect subclasses from breaking when I change internal parts?
  1466. A: You can make your software more resilient to internal changes by realizing
  1467. a class has two distinct interfaces for two distinct sets of clients:
  1468.  * its `public:' interface serves unrelated classes
  1469.  * its `protected:' interface serves derived classes
  1470.  
  1471. A class that is intended to have a long and happy life can hide its physical
  1472. bits in its `private:' part, then put `protected:' inline access functions to
  1473. these data.  The private bits can change, but if the protected access fns are
  1474. stable, subclasses (ie: derived classes) won't break (though they'll need to
  1475. be recompiled after a change to the base class).
  1476.  
  1477. ==============================================================================
  1478. SUBSECTION: Inheritance -- constructors and destructors
  1479. ==============================================================================
  1480.  
  1481. Q62: Why does base ctor get *base*'s virtual fn instead of the derived version?
  1482.  
  1483. Ie: when constructing an obj of class `Derived', Base::Base() invokes `virt()'.
  1484. `Derived::virt()' exists (an override of `Base::virt()'), yet `Base::virt()'
  1485. gets control rather than the `Derived' version; why?
  1486.  
  1487. A: A constructor turns raw bits into a living object.  Until the ctor has
  1488. finished, you don't have a complete `object'.  In particular, while the base
  1489. class' ctor is working, the object isn't yet a Derived class object, so the
  1490. call of the base class' virtual fn defn is correct.
  1491.  
  1492. Similarly dtors turn a living object into raw bits (they `blow it to bits'), so
  1493. the object is no longer a Derived during Base's dtor.  Therefore the same thing
  1494. happens: when Base::~Base() calls `virt()', Base::virt() gets control, not the
  1495. Derived::virt() override.  (Think of what would happen if the Derived fn
  1496. touched a subobject from the Derived class, and you'll quickly see the wisdom
  1497. of the approach).
  1498.  
  1499. ==============================================================================
  1500.  
  1501. Q63: Does a derived class dtor need to explicitly call the base destructor?
  1502. A: No, you never need to explicitly call a dtor (where `never' means `rarely').
  1503. ie: you only have to have an explicit dtor call in rather esoteric situations
  1504. such as destroying an object created by the `placement new operator'.  In the
  1505. usual case, a derived class' dtor (whether you explicitly define one or not)
  1506. automatically invokes the dtors for subobjects and base class(es).  Subobjects
  1507. are destroyed immediately after the derived class' destructor body (`{...}'),
  1508. and base classes are destroyed immediately after subobjects.  Subobjects are
  1509. destroyed from bottom to top in the lexical order they appear within a class,
  1510. and base classes from right to left in the order of the base-class-list.
  1511.  
  1512. ==============================================================================
  1513. SUBSECTION: Inheritance -- private and protected inheritance
  1514. ==============================================================================
  1515.  
  1516. Q64: How do you express `private inheritance'?
  1517. A: When you use `: private' instead of `: public'.  Ex:
  1518.  
  1519.  class Foo : private Bar {
  1520.    //...
  1521.  };
  1522.  
  1523. ==============================================================================
  1524.  
  1525. Q65: How are `private derivation' and `containment' similar? dissimilar?
  1526. A: Private derivation can be thought of as a syntactic variant of containment
  1527. (has-a).  Ex: it is NOT true that a privately derived is-a-kind-of-a Base:
  1528.  
  1529. With private derivation:
  1530.  class Car : private Engine {/*...*/}; //a Car is NOT a-kind-of Engine
  1531. Similarly:
  1532.  class Car { Engine e; /*...*/ }; //normal containment
  1533.  
  1534. There are several similarities between these two forms of containment:
  1535.  * in both cases there is exactly one Engine subobject contained in a Car
  1536.  * in neither case can clients (outsiders) convert a Car* to an Engine*
  1537.  
  1538. There are also several distinctions:
  1539.  * the second form is needed if you want to contain several subobjects
  1540.  * the first form can introduce unnecessary multiple inheritance
  1541.  * the first form allows members of Car to convert a Car* to an Engine*
  1542.  * the first form allows access to the `protected' members of the base class
  1543.  * the first form allows Car to override Engine's virtual functions.
  1544. Private inheritance is almost always used for the last item: to gain access
  1545. into the `protected:' members of the base class.
  1546.  
  1547. ==============================================================================
  1548.  
  1549. Q66: Should I pointer-cast from a `privately' derived class to its base class?
  1550. A: The short answer: no, but yes too (better read the long answer!)
  1551.  
  1552. From `inside' the privately derived class (ie: in the body of members or
  1553. friends of the privately derived class), the relationship to the base class is
  1554. known, and the upward conversion from PrivatelyDer* to Base* (or PrivatelyDer&
  1555. to Base&) is safe and doesn't need a cast.
  1556.  
  1557. From `outside' the privately derived class, the relationship to `Base' is a
  1558. `private' decision of `PrivatelyDer', so the conversion requires a cast.
  1559. Clients should not exercise this cast, since private derivation is a private
  1560. implementation decision of the privately derived class, and the coercion will
  1561. fail after the privately derived class privately chooses to change this private
  1562. implementation decision.
  1563.  
  1564. Bottom line: only a class and its friends have the right to convert a ptr to a
  1565. derived class into a ptr to its private base class.  They don't need a cast,
  1566. since the relationship with the base class is accessible to them.  No one else
  1567. can convert such ptrs without pointer-casts, so no one else should.
  1568.  
  1569. ==============================================================================
  1570.  
  1571. Q67: Should I pointer-cast from a `protected' derived class to its base class?
  1572. A: Protected inheritance is similar to private inheritance; the answer is `no'.
  1573.  class Car : protected Engine {/*...*/};   //protected inheritance
  1574.  
  1575. In `private' inheritance, only the class itself (and its friends) can know
  1576. about the relation to the base class (the relationship to the base class is a
  1577. `private' decision).  In protected inheritance, the relationship with the base
  1578. class is a `protected' decision, so *subclasses* of the `protectedly' derived
  1579. class can also know about and exploit this relationship.
  1580.  
  1581. This is a `for better *and* for worse' situation: future changes to `protected'
  1582. decisions have further consequences than changing a private decision (in this
  1583. case, the class, its friends, *and* subclasses, sub- sub- classes, etc, all
  1584. need to be examined for dependencies upon the relationship to the base class).
  1585. However it is also for better, in that subclasses have the ability to exploit
  1586. the relationship.
  1587.  
  1588. The existence of protected inheritance in C++ is debated in some circles.
  1589.  
  1590. ==============================================================================
  1591.  
  1592. Q68: What are the access rules with `private' and `protected' inheritance?
  1593. A: Take these classes as examples:
  1594.  class B { /*...*/ };
  1595.  class D_priv : private   B { /*...*/ };
  1596.  class D_prot : protected B { /*...*/ };
  1597.  class D_publ : public    B { /*...*/ };
  1598.  class Client { B b; /*...*/ };
  1599.  
  1600. Public and protected parts of B are `private' in D_priv, and are `protected' in
  1601. D_prot.  In D_publ, public parts of B are public (D_prot is-a-kind-of-a B), and
  1602. protected parts of B remain protected in D_publ.  Naturally *none* of the
  1603. subclasses can access anything that is private in B.  Class `Client' can't
  1604. even access the protected parts of B (ie: it's `sealed off').
  1605.  
  1606. It is often the case that you want to make some but not all inherited member
  1607. functions public in privately/protectedly derived classes.  Ex: to make member
  1608. fn B::f(int,char,float) public in D_prot, you would say:
  1609.  class D_prot : protected B {
  1610.    //...
  1611.  public:
  1612.    B::f;    //note: not  B::f(int,char,float)
  1613.  };
  1614.  
  1615. There are limitations to this technique (can't distinguish overloaded names,
  1616. and you can't make a feature that was `protected' in the base `public' in the
  1617. derived).  Where necessary, you can get around these by a call-through fn:
  1618.  class D_prot : protected B {
  1619.  public:
  1620.    short f(int i, char c, float f) { return B::f(i,c,f); }
  1621.  };
  1622.  
  1623. ==============================================================================
  1624.  
  1625. Q69: Do most C++ programmers use containment or private inheritance?
  1626. A: Short answer: generalizations are always wrong (that's a generalization :-).
  1627.  
  1628. The long answer is another generalization: most C++ programmers use regular
  1629. containment (also called `composition' or `aggregation') more often than
  1630. private inheritance.  The usual reason is that they don't *want* to have access
  1631. to the internals of too many other classes.
  1632.  
  1633. Private inheritance is not evil; it's just more expensive to maintain, since it
  1634. increases the number of classes that have access to `internal' parts of other
  1635. classes (coupling).  The `protected' parts of a class are more likely to change
  1636. than the `public' parts.
  1637.  
  1638. ==============================================================================
  1639.  
  1640. ==============================================================================
  1641.  
  1642.   ****  PART 12 -- Abstraction  ****
  1643.  
  1644. ==============================================================================
  1645.  
  1646. Q70: What's the big deal of separating interface from implementation?
  1647. A: Separating interface from implementation is a key to reusable software.
  1648. Interfaces are a company's most valuable resources.  Designing an interface
  1649. takes longer than whipping together a concrete class which fulfills that
  1650. interface.  Furthermore interfaces require the resources of more expensive
  1651. people (for better and worse, most companies separate `designers' from
  1652. `coders').  Since they're so valuable, they should be protected from being
  1653. tarnished by data structures and other artifacts of the implementation (any
  1654. data structures you put in a class can never be `revoked' by a derived class,
  1655. which is why you want to `separate' the interface from the implementation).
  1656.  
  1657. ==============================================================================
  1658.  
  1659. Q71: How do I separate interface from implementation in C++ (like Modula-2)?
  1660. A: Short answer: use an ABC (see next question for what an ABC is).
  1661.  
  1662. ==============================================================================
  1663.  
  1664. Q72: What is an ABC (`abstract base class')?
  1665. A: An ABC corresponds to an abstract concept.  If you asked a Mechanic if he
  1666. repaired Vehicles, he'd probably wonder what *kind* of Vehicle you had in mind.
  1667. Chances are he doesn't repair space shuttles, ocean liners, bicycles, and
  1668. volkswaggon beetles too.  The problem is that the term `Vehicle' is an abstract
  1669. concept; you can't build one until you know what kind of vehicle to build.  In
  1670. C++, you'd make Vehicle be an ABC, with Bicycle, SpaceShuttle, etc, being
  1671. subclasses (an OceanLiner is-a-kind-of-a Vehicle).
  1672.  
  1673. In real-world OOP, ABCs show up all over the place.  Technically, an ABC is a
  1674. class that has one or more pure virtual member functions (see next question).
  1675. You cannot make an object (instance) of an ABC.
  1676.  
  1677. ==============================================================================
  1678.  
  1679. Q73: What is a `pure virtual' member function?
  1680. A: Some member functions exist in concept, but can't have any actual defn.  Ex:
  1681. Suppose I asked you to draw a Shape at location (x,y) that has size 7.2.  You'd
  1682. ask me `what kind of shape should I draw', since circles, squares, hexagons,
  1683. etc, are drawn differently.  In C++, we indicate the existence of the `draw()'
  1684. method, but we recognize it can only be defined in subclasses:
  1685.  
  1686.  class Shape {
  1687.  public:
  1688.    virtual void draw() const = 0;
  1689.    //...                     ^^^--- `=0' means it is `pure virtual'
  1690.  };
  1691.  
  1692. This pure virtual makes `Shape' an ABC.  The `const' says that invoking the
  1693. `draw()' method won't change the Shape object (ie: it won't move around on the
  1694. screen, change sizes, etc).  If you want, you can think of it as if the code
  1695. were at the NULL pointer.
  1696.  
  1697. Pure virtuals allow you to express the idea that any actual object created from
  1698. a [concrete] class derived from the ABC *will* have the indicated member fn,
  1699. but we simply don't have enough information to actually *define* it yet.  They
  1700. allow separation of interface from implementation, which ultimately allows
  1701. functionally equivalent subclasses to be produced that can `compete' in a free
  1702. market sense (a technical version of `market driven economics').
  1703.  
  1704. ==============================================================================
  1705.  
  1706. Q74: How can I provide printing for an entire hierarchy rooted at `class X'?
  1707. A: Provide a friend operator<< that calls a protected virtual function:
  1708.  
  1709.     class X {
  1710.     public:
  1711.       friend ostream& operator<< (ostream& o,const X& x)
  1712.         { x.print(o); return o; }
  1713.       //...
  1714.     protected:
  1715.       virtual void print(ostream& o) const;  //or `=0;' if `X' is abstract
  1716.     };
  1717.  
  1718. Now all subclasses of X merely provide their own `print(ostream&)const' member
  1719. function, and they all share the common `<<' operator.  Friends don't bind
  1720. dynamically, but this technique makes them *act* as if they were.
  1721.  
  1722. ==============================================================================
  1723.  
  1724. Q75: What is a `virtual destructor'?
  1725. A: In general, a virtual fn means to start at the class of the object itself,
  1726. not the type of the pointer/ref (`do the right thing based on the actual class
  1727. of' is a good way to remember it).  Virtual destructors (dtors) are no
  1728. different: start the destruction process `down' at the object's actual class,
  1729. rather than `up' at the ptr's class (ie: `destroy yourself using the *correct*
  1730. destruction routine').
  1731.  
  1732. Virtual destructors are so valuable that some people want compilers to holler
  1733. at you if you forget them.  In general there's only one reason *not* to make a
  1734. class' dtor virtual: if that class has no virtual fns, the introduction of the
  1735. first virtual fn imposes typically 4 bytes overhead in the size of each object
  1736. (there's a bit of magic for how C++ `does the right thing', and it boils down
  1737. to an extra ptr per object called the `virtual table pointer' or `vptr').
  1738.  
  1739. ==============================================================================
  1740.  
  1741. Q76: What is a `virtual constructor'?
  1742. A: Technically speaking, there is no such thing.  You can get the effect you
  1743. desire by a virtual `create_copy()' member fn (for copy constructing), or a
  1744. `create_similar()' member fn (also virtual) which constructs/creates a new
  1745. object of the same class but is `fresh' (like the `default' [zero parameter]
  1746. ctor would do).
  1747.  
  1748. The reason ctors can't be virtual is simple: a ctor turns raw bits into a
  1749. living object.  Until there's a living respondent to a message, you can't
  1750. expect a message to be handled `the right way'.  You can think of ctors as
  1751. `class' [static] functions, or as `factories' which churn out objects.
  1752. Thinking of ctors as `methods' attached to an object is misleading.
  1753.  
  1754. Here is an example of how you could use `create_copy()' and `create_similar()'
  1755. methods:
  1756.  
  1757.  class Set {   //normally this would be a template
  1758.  public:
  1759.    virtual void insert(int); //Set of `int'
  1760.    virtual int  remove();
  1761.    //...
  1762.    virtual Set* create_copy() const = 0; //pure virtual; Set is an ABC
  1763.    virtual Set* create_similar() const = 0;
  1764.    virtual ~Set() { }  //see on `virtual destructors' for more
  1765.  };
  1766.  
  1767.  class SetHT : public Set {
  1768.  public:
  1769.    //...
  1770.    Set* create_copy()    const { return new SetHT(*this); }
  1771.    Set* create_similar() const { return new SetHT(); }
  1772.  protected:
  1773.    //a hash table in here
  1774.  };
  1775.  
  1776. A SetHT is-a Set, so the return value is correct.  The invocation of
  1777. `SetHT(*this)' is that of copy construction (`*this' has type `const SetHT&').
  1778. Although `create_copy()' returns a new SetHT, the caller of create_copy()
  1779. merely knows he has a Set, not a SetHT (which is desirable in the case of
  1780. wanting a `virtual ctor').  `create_similar()' is similar, but it constructs an
  1781. `empty' SetHT.
  1782.  
  1783. Clients can use this as if they were `virtual constructors':
  1784.  
  1785.  void client_code(Set& s)
  1786.  {
  1787.    Set* s2 = s.create_copy();
  1788.    Set* s3 = s.create_similar();
  1789.    //...
  1790.    delete s2; //relies on destructor being virtual!!
  1791.    delete s3; // ditto
  1792.  }
  1793.  
  1794. This fn will work correctly regardless of how the Set is implemented (hash
  1795. table based, AVL tree based, etc).
  1796.  
  1797. See above on `separation of interface from implementation' for more.
  1798.  
  1799. ==============================================================================
  1800.  
  1801.   ****  PART 13 -- Style guidelines  ****
  1802.  
  1803. ==============================================================================
  1804.  
  1805. Q77: What are some good C++ coding standards?
  1806. A: Thank you for reading this answer rather than just trying to set your own
  1807. coding standards.  But please don't ask this question on Usenet.  Nearly every
  1808. software engineer has, at some point, felt that coding standards are or can be
  1809. used as a `power play'.  Furthermore some attempts to set C++ coding standards
  1810. have been made by those unfamiliar with the language and/or paradigm, so the
  1811. standards end up being based on what *was* the state-of-the-art when the
  1812. setters where writing code.  Such impositions generate an attitude of mistrust
  1813. for coding standards.  Obviously anyone who asks this question on Usenet wants
  1814. to be trained so they *don't* run off on their own ignorance, but nonetheless
  1815. the answers tend to generate more heat than light.
  1816.  
  1817. ==============================================================================
  1818.  
  1819. Q78: Are coding standards necessary?  sufficient?
  1820. A: Coding standards do not make non OO programmers into OO programmers.  Only
  1821. training and experience do that.  If they have merit, it is that coding
  1822. standards discourage the petty fragmentation that occurs when organizations
  1823. coordinate the activities of diverse groups of programmers.
  1824.  
  1825. But you really want more than a coding standard.  The structure provided by
  1826. coding standards gives neophytes one less degree of freedom to worry about,
  1827. however pragmatics go well beyond pretty-printing standards.  We actually need
  1828. a consistent *philosophy* of implementation.  Ex: strong or weak typing?
  1829. references or ptrs in our interface?  stream I/O or stdio?  should C++ code
  1830. call our C?  vise versa?  should we use ABCs?  polymorphism?  inheritance?
  1831. classes? encapsulation?  how should we handle exceptions?  etc.
  1832.  
  1833. Therefore what is needed is a `pseudo standard' for detailed *design*.  How can
  1834. we get this?  I recommend a two-pronged approach: training and libraries.
  1835. Training provides `intense instruction', and a high quality C++ class library
  1836. provides `long term instruction'.  There is a thriving commercial market for
  1837. both kinds of `training'.  Advice by organizations who have been through the
  1838. mill is consistent: Buy, Don't Build.  Buy libraries, buy training, buy tools.
  1839. Companies who have attempted to become a self-taught tool-shop as well as an
  1840. application/system shop have found success difficult.
  1841.  
  1842. Few argue that coding standards are `ideal', or even `good', however many feel
  1843. that they're necessary in the kind of organizations/situations described above.
  1844.  
  1845. The following questions provide some basic guidance in conventions and styles.
  1846.  
  1847. ==============================================================================
  1848.  
  1849. Q79: Should our organization determine coding standards from our C experience?
  1850. A: No matter how vast your C experience, no matter how advanced your C
  1851. expertise, being a good C programmer does not make you a good C++ programmer.
  1852. C programmers must learn to use the `++' part of `C++', or the results will be
  1853. lackluster.  People who want the `promise' of OOP, but who fail to put the `OO'
  1854. into OOP, are fooling themselves, and the balance sheet will show their folly.
  1855.  
  1856. C++ coding standards should be tempered by C++ experts.  Asking comp.lang.c++
  1857. is a start (but don't use the term `coding standard' in the question; instead
  1858. simply say, `what are the pros and cons of this technique?').  Seek out experts
  1859. who can help guide you away from pitfalls.  Get training.  Buy libraries and
  1860. see if `good' libraries pass your coding standards.  Do *not* set standards by
  1861. yourself unless you have considerable experience in C++.  Having no standard is
  1862. better than having a bad standard, since improper `official' positions `harden'
  1863. bad brain traces.  There is a thriving market for both C++ training and
  1864. libraries from which to pool expertise.
  1865.  
  1866. One more thing: whenever something is in demand, the potential for charlatans
  1867. increases.  Look before you leap.  Also ask for student-reviews from past
  1868. companies, since not even expertise makes someone a good communicator.
  1869. Finally, select a practitioner who can teach, not a full time teacher who has a
  1870. passing knowledge of the language/paradigm.
  1871.  
  1872. ==============================================================================
  1873.  
  1874. Q80: Should I declare locals in the middle of a fn or at the top?
  1875. A: Different people have different opinions about coding standards.  However
  1876. one thing we all should agree on is this: no style guide should impose undue
  1877. performance penalties.  The real reason C++ allows objects to be created
  1878. anywhere in the block is not style, but performance.
  1879.  
  1880. An object is initialized (constructed) the moment it is declared.  If you don't
  1881. have enough information to initialize an object until half way down the fn, you
  1882. can either initialize it to an `empty' value at the top then `assign' it later,
  1883. or initialize it correctly half way down the fn.  It doesn't take much
  1884. imagination to see that it's cheaper to get it right the first time than it is
  1885. to build it once, tear it down, then rebuild it again.  Simple examples show a
  1886. factor of 350% speed hit for simple classes like String.  Your mileage may
  1887. vary; surely the overall system degradation will be less that 300+%, but there
  1888. *will* be degradation.  *Unnecessary* degradation.
  1889.  
  1890. A common retort to the above is: `we'll provide "set" methods for every datum
  1891. in our objects, so the cost of construction will be spread out'.  This is worse
  1892. than the performance overhead, since now you're introducing a maintenance
  1893. nightmare.  Providing `set' methods for every datum is tantamount to public
  1894. data.  You've exposed your implementation technique to the world.  The only
  1895. thing you've hidden is the physical *names* of your subobjects, but the fact
  1896. that you're using a List and a String and a float (for example) is open for all
  1897. to see.  Maintenance generally consumes far more resources than run-time CPU.
  1898.  
  1899. Conclusion: in general, locals should be declared near their first use.  Sorry
  1900. that this isn't `familiar' to your C experts, but `new' doesn't necessarily
  1901. mean `bad'.
  1902.  
  1903. ==============================================================================
  1904.  
  1905. Q81: What source-file-name convention is best? `foo.C'? `foo.cc'? `foo.cpp'?
  1906. A: Most Un*x compilers accept `.C' for C++ source files, g++ preferring `.cc',
  1907. and cfront also accepting `.c'.  Most DOS and OS/2 compilers require `.cpp'
  1908. since DOS filesystems aren't case sensitive.  Some also advocate `.cxx'.  The
  1909. impact of this decision is not great, since a trivial shell script can rename
  1910. all .cc files into .C files.  The only files that would have to be modified are
  1911. the Makefiles, which is a very small piece of your maintenance costs.  Note
  1912. however that some versions of cfront accept a limited set of suffixes (ie: some
  1913. can't handle `.cc'; in these cases it is easier to tell `make' about CC's
  1914. convention than vise versa).
  1915.  
  1916. You can use `.C' on DOS or OS/2 if the compiler provides a command-line option
  1917. to tell it to always compile with C++ rules (ex: `ztc -cpp foo.C' for Zortech,
  1918. `bcc -P foo.C' for Borland, etc).
  1919.  
  1920. ==============================================================================
  1921.  
  1922. Q82: What header-file-name convention is best? `foo.H'? `foo.hh'? `foo.hpp'?
  1923. A: The naming of your source files is cheap since it doesn't affect your source
  1924. code.  Your substantial investment is your source code.  Therefore the names of
  1925. your header files must be chosen with much greater care.  The preprocessor will
  1926. accept whatever name you give it in the #include line, but whatever you choose,
  1927. you will want to plan on sticking with it for a long time, since it is more
  1928. expensive to change (though certainly not as difficult as, say, porting to a
  1929. new language).
  1930.  
  1931. Almost all vendors ship their C++ header files using a `.h' extension, which
  1932. means you can reliably do things like:
  1933.   #include <iostream.h>
  1934.  
  1935. Some sites use `.H' for their own internally developed header files, but most
  1936. simply use `.h'.
  1937.  
  1938. ==============================================================================
  1939.  
  1940. Q83: Are there any lint-like guidelines for C++?
  1941. A: Yes, there are some practices which are generally considered dangerous.
  1942. However none of these are universally `bad', since situations arise when
  1943. even the worst of these is needed:
  1944.  * a class `X's assignment operator should return `*this' as an `X&'
  1945.    (allows chaining of assignments)
  1946.  * a class with any virtual fns ought to have a virtual destructor
  1947.  * a class with any of {dtor, assignment-op, copy-ctor} generally needs all 3
  1948.  * a class `X's copy-ctor and assignment-op should have `const' in the param:
  1949.    `X::X(const X&)'  and  `X& X::operator=(const X&)'  respectively
  1950.  * always use initialization lists for class sub-objects rather than assignment
  1951.    the performance difference for user-defined classes can be substantial (3x!)
  1952.  * many assignment operators should start by testing if `we' are `them'; ex:
  1953.  X& X::operator=(const X& x)
  1954.  {
  1955.    if (this == &x) return *this;
  1956.    //...normal assignment duties...
  1957.    return *this;
  1958.  }
  1959.    sometimes there is no need to check, but these situations generally
  1960.    correspond to when there's no need for an explicit user-specified assignment
  1961.    op (as opposed to a compiler-synthesized assignment-op).
  1962.  * in classes that define both `+=', `+' and `=', `a+=b' and `a=a+b' should
  1963.    generally do the same thing; ditto for the other identities of builtin types
  1964.    (ex: a+=1 and ++a; p[i] and *(p+i); etc).  This can be enforced by writing
  1965.    the binary ops using the `op=' forms; ex:
  1966.  X operator+(const X& a, const X& b)
  1967.  {
  1968.    X ans = a;
  1969.    ans += b;
  1970.    return ans;
  1971.  }
  1972.    This way the `constructive' binary ops don't even need to be friends.  But
  1973.    it is sometimes possible to more efficiently implement common ops (ex: if
  1974.    class `X' is actually `String', and `+=' has to reallocate/copy string
  1975.    memory, it may be better to know the eventual length from the beginning).
  1976.  
  1977. ==============================================================================
  1978.  
  1979.   ****  PART 14 -- C++/Smalltalk differences and keys to learning C++  ****
  1980.  
  1981. ==============================================================================
  1982.  
  1983. Q84: Why does C++'s FAQ have a section on Smalltalk? Is this Smalltalk-bashing?
  1984. A: The two `major' OOPLs in the world are C++ and Smalltalk.  Due to its
  1985. popularity as the OOPL with the second largest user pool, many new C++
  1986. programmers come from a Smalltalk background.  This section answers the
  1987. questions:
  1988.  * what's different about the two languages
  1989.  * what must a Smalltalk-turned-C++ programmer know to master C++
  1990.  
  1991. This section does *!*NOT*!* attempt to answer the questions:
  1992.  * which language is `better'?
  1993.  * why is Smalltalk `bad'?
  1994.  
  1995. Nor is it an open invitation for some Smalltalk terrorist to slash my tires
  1996. while I sleep (on those rare occasions when I have time to rest these days :-).
  1997.  
  1998. ==============================================================================
  1999.  
  2000. Q85: What's the difference between C++ and Smalltalk?
  2001. A: There are many differences such as compiled vs perceived-as-interpreted,
  2002. pure vs hybrid, faster vs perceived-as-slower, etc.  Some of these aren't true
  2003. (ex: a large portion of a typical Smalltalk program can be compiled by current
  2004. implementations, and some Smalltalk implementations perform reasonably well).
  2005. But none of these affect the programmer as much as the following three issues:
  2006.  
  2007.  * static typing vs dynamic typing (`strong' and `weak' are synonyms)
  2008.  * how you use inheritance
  2009.  * value vs reference semantics
  2010.  
  2011. The first two differences are illuminated in the remainder of this section; the
  2012. third point is the subject of the section that follows.
  2013.  
  2014. If you're a Smalltalk programmer who wants to learn C++, you'd be very wise to
  2015. study the next three questions carefully.  Historically there have been many
  2016. attempts to `make' C++ look/act like Smalltalk, even though the languages are
  2017. very Very different.  This hasn't always led to failures, but the differences
  2018. are significant enough that it has led to a lot of needless frustration and
  2019. expense.  The quotable quote of the year goes to Bjarne Stroustrup at the `C++
  2020. 1995' panel discussion, 1990 C++-At-Work conference, discussing library design:
  2021.   `Smalltalk is the best Smalltalk around'.
  2022.  
  2023. ==============================================================================
  2024.  
  2025. Q86: What is `static typing', and how is it similar/dissimilar to Smalltalk?
  2026. A: Static (most say `strong') typing says the compiler checks the type-safety
  2027. of every operation *statically* (at compile-time), rather than to generate code
  2028. which will check things at run-time.  For example, the signature matching of fn
  2029. arguments is checked, and an improper match is flagged as an error by the
  2030. *compiler*, not at run-time.
  2031.  
  2032. In OO code, the most common `typing mismatch' is sending a message to an object
  2033. that the recipient isn't prepare to handle.  Ex: if class `X' has member fn f()
  2034. but not g(), and `x' is an instance of class X, then x.f() is legal and x.g()
  2035. is illegal.  C++ (statically/strongly typed) catches the error at compile time,
  2036. and Smalltalk (dynamically/weakly typed) catches `type' errors at run-time.
  2037. (Technically speaking, C++ is like Pascal [*pseudo* statically typed], since
  2038. ptr casts and unions can be used to violate the typing system; you probably
  2039. shouldn't use these constructs very much).
  2040.  
  2041. ==============================================================================
  2042.  
  2043. Q87: Which is a better fit for C++: `static typing' or `dynamic typing'?
  2044. A: The arguments over the relative goodness of static vs dynamic typing will
  2045. continue forever.  However one thing is clear: you should use a tool like it
  2046. was intended and designed to be used.  If you want to use C++ most effectively,
  2047. use it as a statically typed language.  C++ is flexible enough that you can
  2048. (via ptr casts, unions, and #defines) make it `look' like Smalltalk.
  2049.  
  2050. There are places where ptr casts and unions are necessary and even wholesome,
  2051. but they should be used carefully and sparingly.  A ptr cast tells the compiler
  2052. to believe you.  It effectively suspends the normal type checking facilities.
  2053. An incorrect ptr cast might corrupt your heap, scribble into memory owned by
  2054. other objects, call nonexistent methods, and cause general failures.  It's not
  2055. a pretty sight.  If you avoid these and related constructs, you can make your
  2056. C++ code both safer and faster -- anything that can be checked at compile time
  2057. is something that doesn't have to be done at run-time, one `pro' of strong
  2058. typing.
  2059.  
  2060. Even if you're in love with weak typing, please consider using C++ as a
  2061. strongly typed OOPL, or else please consider using another language that better
  2062. supports your desire to defer typing decisions to run-time.  Since C++ performs
  2063. 100% type checking decisions at compile time, there is *no* built-in mechanism
  2064. to do *any* type checking at run-time; if you use C++ as a weakly typed OOPL,
  2065. you put your life in your own hands.
  2066.  
  2067. ==============================================================================
  2068.  
  2069. Q88: How can you tell if you have a dynamically typed C++ class library?
  2070. A: One hint that a C++ class library is weakly typed is when everything is
  2071. derived from a single root class, usually `Object'.  Even more telling is the
  2072. implementation of the container classes (List, Stack, Set, etc): if these
  2073. containers are non-templates, and if their elements are inserted/extracted as
  2074. ptrs to `Object', the container will promote weak typing.  You can put an Apple
  2075. into such a container, but when you get it out, the compiler only knows that it
  2076. is derived from Object, so you have to do a pointer cast (a `down cast') to
  2077. cast it `down' to an Apple (you also might hope a lot that you got it right,
  2078. cause your blood is on your own head).
  2079.  
  2080. You can make the down cast `safe' by putting a virtual fn into Object such as
  2081. `are_you_an_Apple()' or perhaps `give_me_the_name_of_your_class()', but this
  2082. dynamic testing is just that: dynamic.  This coding style is the essence of
  2083. weak typing in C++.  You call a function that says `convert this Object into an
  2084. Apple or kill yourself if its not an Apple', and you've got weak typing: you
  2085. don't know if the call will succeed until run-time.
  2086.  
  2087. When used with templates, the C++ compiler can statically validate 99% of an
  2088. application's typing information (the figure `99%' is apocryphal; some claim
  2089. they always get 100%, others find the need to do persistence which cannot be
  2090. statically type checked).  The point is: C++ gets genericity from templates,
  2091. not from inheritance.
  2092.  
  2093. ==============================================================================
  2094.  
  2095. Q89: Will `standard C++' include any dynamic typing primitives?
  2096. A: Yep.
  2097.  
  2098. Note that the effect of a down-cast and a virtual fn call are similar: in the
  2099. member fn that results from the virtual fn call, the `this' ptr is a downcasted
  2100. version of what it used to be (it went from ptr-to-Base to ptr-to-Derived).
  2101. The difference is that the virtual fn call *always* works: it never makes the
  2102. wrong `down-cast' and it automatically extends itself whenever a new subclass
  2103. is created -- as if an extra `case' or `if/else' magically appearing in the
  2104. weak typing technique.  The other difference is that the client gives control
  2105. to the object rather than reasoning *about* the object.
  2106.  
  2107. ==============================================================================
  2108.  
  2109. Q90: How do you use inheritance in C++, and is that different from Smalltalk?
  2110. A: There are two reasons one might want to use inheritance: to share code, or
  2111. to express your interface compliance.  Ie: given a class `B' (`B' stands for
  2112. `base class', which is called `superclass' in Smalltalkese), a class `D' which
  2113. is derived from B is expressed this way:
  2114.  
  2115.  class B { /*...*/ };
  2116.  class D : public B { /*...*/ };
  2117.  
  2118. This says two distinct things: (1) the bits(data structure) + code(algorithms)
  2119. are inherited from B, and (2) `D's public interface is `conformal' to `B's
  2120. (anything you can do to a B, you can also do to a D, plus perhaps some other
  2121. things that only D's can do; ie: a D is-a-kind-of-a B).
  2122.  
  2123. In C++, one can use inheritance to mean:
  2124.  --> #2(is-a) alone (ex:you intend to override most/all inherited code)
  2125.  --> both #2(is-a) and #1(code-sharing)
  2126. but one should never Never use the above form of inheritance to mean
  2127.  --> #1(code-sharing) alone (ex: D really *isn't* a B, but...)
  2128.  
  2129. This is a major difference with Smalltalk, where there is only one form of
  2130. inheritance (C++ provides `private' inheritance to mean `share the code but
  2131. don't conform to the interface').  The Smalltalk language proper (as opposed to
  2132. coding practice) allows you to have the *effect* of `hiding' an inherited
  2133. method by providing an override that calls the `does not understand' method.
  2134. Furthermore Smalltalk allows a conceptual `is-a' relationship to exist *apart*
  2135. from the subclassing hierarchy (subtypes don't have to be subclasses; ex: you
  2136. can make something that `is-a Stack' yet doesn't inherit from `Stack').
  2137.  
  2138. In contrast, C++ is more restrictive about inheritance: there's no way to make
  2139. a `conceptual is-a' relationship without using inheritance (the C++ work-around
  2140. is to separate interface from implementation via ABCs).  The C++ compiler
  2141. exploits the added semantic information associated with public inheritance to
  2142. provide static typing.
  2143.  
  2144. ==============================================================================
  2145.  
  2146. Q91: What are the practical consequences of diffs in Smalltalk/C++ inheritance?
  2147. A: Since Smalltalk lets you make a subtype without making a subclass, one can
  2148. be very carefree in putting data (bits, representation, data structure) into a
  2149. class (ex: you might put a linked list into a Stack class).  After all, if
  2150. someone wants something that an array-based-Stack, they don't have to inherit
  2151. from Stack; they can go off and make effectively a stand-alone class (they
  2152. might even *inherit* from an Array class, even though they're not-a-kind-of-
  2153. Array!).
  2154.  
  2155. In C++, you can't be nearly as carefree.  Since only mechanism (method code),
  2156. but not representation (data bits) can be overridden in subclasses, you're
  2157. usually better off *not* putting the data structure in a class.  This leads to
  2158. the concept of Abstract Base Classes (ABCs), which are discussed in a separate
  2159. question.  You can change the algorithm but NOT the data structure.  Bits are
  2160. forever.
  2161.  
  2162. I like to think of the difference between an ATV and a Maseratti.  An ATV [all
  2163. terrain vehicle] is more fun, since you can `play around' by driving through
  2164. fields, streams, sidewalks and the like.  A Maseratti, on the other hand, gets
  2165. you there faster, but it forces you to stay on the road.  My advice to C++
  2166. programmers is simple: stay on the road.  Even if you're one of those people
  2167. who like the `expressive freedom' to drive through the bushes, don't do it in
  2168. C++; it's not a good `fit'.
  2169.  
  2170. Note that C++ compilers uphold the is-a semantic constraint only with `public'
  2171. inheritance.  Neither containment (has-a), nor private or protected inheritance
  2172. implies conformance.
  2173.  
  2174. ==============================================================================
  2175.  
  2176. Q92: Do you need to learn a `pure' OOPL before you learn C++?
  2177. A: The short answer is, No.
  2178.  
  2179. The medium answer length answer is: learning some `pure' OOPLs may *hurt*
  2180. rather than help.
  2181.  
  2182. The long answer is: read the previous questions on the difference between C++
  2183. and Smalltalk (the usual `pure' OOPL being discussed; `pure' means everything
  2184. is an object of some class; `hybrid' [like C++] means things like int, char,
  2185. and float are not instances of a class, hence aren't subclassable).
  2186.  
  2187. The `purity' of the OOPL doesn't make the transition to C++ any more or less
  2188. difficult; it is the weak typing and improper inheritance that is so hard to
  2189. get.  I've taught numerous people C++ with a Smalltalk background, and they
  2190. usually have just as hard a time as those who've never seen inheritance before.
  2191. In fact, my personal observation is that those with extensive experience with a
  2192. weakly typed OOPL (usually but not always Smalltalk) have a *harder* time,
  2193. since it's harder to *unlearn* habits than it is to learn the statically typed
  2194. way from the beginning.
  2195.  
  2196. ==============================================================================
  2197.  
  2198. Q93: What is the NIHCL?  Where can I get it?
  2199. A: NIHCL stands for `national-institute-of-health's-class-library'.
  2200. it can be acquired via anonymous ftp from [128.231.128.251]
  2201. in the file pub/nihcl-3.0.tar.Z
  2202.  
  2203. NIHCL (some people pronounce it `N-I-H-C-L', others pronounce it like `nickel')
  2204. is a C++ translation of the Smalltalk class library.  There are some ways where
  2205. NIHCL's use of weak typing helps (ex: persistent objects).  There are also
  2206. places where the weak typing it introduces create tension with the underlying
  2207. statically typed language.
  2208.  
  2209. A draft version of the 250pp reference manual is included with version 3.10
  2210. (gnu emacs TeX-info format).  It is not available via uucp, or via regular mail
  2211. on tape, disk, paper, etc (at least not from Keith Gorlen).
  2212.  
  2213. See previous questions on Smalltalk for more.
  2214.  
  2215. ==============================================================================
  2216.  
  2217.   ****  PART 15 -- Reference and value semantics  ****
  2218.  
  2219. ==============================================================================
  2220.  
  2221. Q94: What is value and/or reference semantics, and which is best in C++?
  2222. A: With reference semantics, assignment is a pointer-copy (ie: a *reference*).
  2223. Value (or `copy') semantics mean assignment copies the value, not just the
  2224. pointer.  C++ gives you the choice: use the assignment operator to copy the
  2225. value (copy/value semantics), or use a ptr-copy to copy a pointer (reference
  2226. semantics).  C++ allows you to override the assignment operator to do anything
  2227. your heart desires, however the default (and most common) choice is to copy the
  2228. *value*.  Smalltalk and Eiffel and CLOS and most other OOPLs force reference
  2229. semantics; you must use an alternate syntax to copy the value (clone,
  2230. shallowCopy, deepCopy, etc), but even then, these languages ensure that any
  2231. name of an object is actually a *pointer* to that object (Eiffel's `expanded'
  2232. classes allow a supplier-side work-around).
  2233.  
  2234. There are many pros to reference semantics, including flexibility and dynamic
  2235. binding (you get dynamic binding in C++ only when you pass by ptr or pass by
  2236. ref, not when you pass by value).
  2237.  
  2238. There are also many pros to value semantics, including speed.  `Speed' seems
  2239. like an odd benefit to for a feature that requires an object (vs a ptr) to be
  2240. copied, but the fact of the matter is that one usually accesses an object more
  2241. than one copies the object, so the cost of the occasional copies is (usually)
  2242. more than offset by the benefit of having an actual object rather than a ptr to
  2243. an object.
  2244.  
  2245. There are three cases when you have an actual object as opposed to a pointer to
  2246. an object: local vars, global/static vars, and fully contained subobjects in a
  2247. class.  The most common & most important of these is the last (`containment').
  2248.  
  2249. More info about copy-vs-reference semantics is given in the next questions.
  2250. Please read them all to get a balanced perspective.  The first few have
  2251. intentionally been slanted toward value semantics, so if you only read the
  2252. first few of the following questions, you'll get a warped perspective.
  2253.  
  2254. Assignment has other issues (ex: shallow vs deep copy) which are not covered
  2255. here.
  2256.  
  2257. ==============================================================================
  2258.  
  2259. Q95: What is `virtual data', and how-can / why-would I use it in C++?
  2260. A: Virtual data isn't strictly a `part' of C++, however it can be simulated.
  2261. It's not entirely pretty, but it works.  First we'll cover what it is and how
  2262. to simulate it, then conclude with why it isn't `part' of C++.
  2263.  
  2264. Consider classes Vec (like an array of int) and SVec (a stretchable Vec; ie:
  2265. SVec overrides operator[] to automatically stretch the number of elements
  2266. whenever a large index is encountered).  SVec inherits from Vec.  Naturally
  2267. Vec's subscript operator is virtual.
  2268.  
  2269. Now consider a VStack class (Vec-based-Stack).  Naturally this Stack has a
  2270. capacity limited by the fixed number of elements in the underlying Vec data
  2271. structure.  Then someone comes along and wants an SVStack class (SVec based
  2272. Stack).  For some reason, they don't want to merely modify VStack (say, because
  2273. there are many users already using it).
  2274.  
  2275. The obvious choice then would be to inherit SVStack from VStack, however
  2276. then there'd be *two* Vecs in an SVStack object (one explicitly in VStack,
  2277. the other as the base class subobject in the SVec which is explicitly in
  2278. the SVStack).  That's a lot of extra baggage.  There are at least 2 solns:
  2279.  * break the is-a link between SVStack and VStack, text-copy the code from
  2280.    VStack and manually change `Vec' to `SVec'.
  2281.  * activate some sort of virtual data, so subclasses can change the
  2282.    class of subobjects.
  2283.  
  2284. To effect virtual data, we need to change the Vec subobject from a physically
  2285. contained subobject into a ptr pointing to a dynamically allocated subobject:
  2286.  
  2287. _____original_____  |_____to_support_virtual_data_____
  2288. class VStack {   | class VStack {
  2289. public:    | public:
  2290.   VStack(int cap=10)  |   VStack(int cap=10)
  2291.     : v(cap), sp(0) { }  |     : v(*new Vec(cap)), sp(0) { } //FREESTORE
  2292.   void push(int x) {v[sp++]=x;} |   void push(int x) {v[sp++]=x;}   //no change
  2293.   int  pop()  {return v[--sp];} |   int  pop()  {return v[--sp];}   //no change
  2294.  ~VStack() { }   //unnecessary |  ~VStack()    {delete &v;}        //NECESSARY
  2295. protected:   | protected:
  2296.   Vec v;  //where data stored |   Vec& v; //where data is stored
  2297.   int sp; //stack pointer |   int sp; //stack pointer
  2298. };    | };
  2299.  
  2300. Now the subclass has a shot at overriding the defn of the object referred to as
  2301. `v'.  Ex: basically SVStack merely needs to bind a new SVec to `v', rather than
  2302. letting VStack bind the Vec.  However classes can only initialize their *own*
  2303. subobjects in an init-list.  Even if I had used a ptr rather than a ref, VStack
  2304. must be prevented from allocating its own `Vec'.  The way we do this is to add
  2305. another ctor to VStack that takes a Vec& and does *not* allocate a Vec:
  2306.  
  2307.  class VStack {
  2308.  protected:
  2309.    VStack(Vec& vv) : v(vv), sp(0) { } //`protected' constructor!
  2310.  //...     //(prevents public access)
  2311.  };
  2312.  
  2313. That's all there is to it!  Now the subclass (SVStack) can be defined as:
  2314.  
  2315.  class SVStack : public VStack {
  2316.  public:
  2317.    SVStack(int init_cap=10) : VStack(*new SVec(init_cap)) { }
  2318.  };
  2319.  
  2320. Pros: * implementation of SVStack is a one-liner
  2321.  * SVStack shares code with VStack
  2322.  
  2323. Cons: * extra layer of indirection to access the Vec
  2324.  * extra freestore allocations (both new and delete)
  2325.  * extra dynamic binding (reason given in next question)
  2326.  
  2327. We succeeded at making *our* job easier as implementor of SVStack, but all
  2328. clients pay for it.  It wouldn't be so bad if clients of SVStack paid for it,
  2329. after all, they chose to use SVStack (you pay for it if you use it).  However
  2330. the `optimization' made the users of the plain VStack pay as well!
  2331.  
  2332. See the question after the next to find out how much the client's `pay'.  Also:
  2333. *PLEASE* read the few questions that follow the next one too (YOU WILL NOT GET
  2334. A BALANCED PERSPECTIVE WITHOUT THE OTHERS).
  2335.  
  2336. ==============================================================================
  2337.  
  2338. Q96: What's the difference between virtual data and dynamic data?
  2339. A: The easiest way to see the distinction is by an analogy with `virtual fns':
  2340. A virtual member fn means the declaration (signature) must stay the same in
  2341. subclasses, but the defn (body) can be overridden.  The overriddenness of an
  2342. inherited member fn is a static property of the subclass; it doesn't change
  2343. dynamically throughout the life of any particular object, nor is it possible
  2344. for distinct objects of the subclass to have distinct defns of the member fn.
  2345.  
  2346. Now go back and re-read the previous paragraph, but make these substitutions:
  2347.  `member fn' --> `subobject'
  2348.  `signature' --> `type'
  2349.  `body'      --> `exact class'
  2350. After this, you'll have a working defn of virtual data.
  2351.  
  2352. `Per-object member fns' (a member fn `f()' which is potentially different in
  2353. any given instance of an object) could be handled by burying a function ptr in
  2354. the object, then setting the (const) fn ptr during construction.
  2355.  
  2356. `Dynamic member fns' (member fns which change dynamically over time) could also
  2357. be handled by function ptrs, but this time the fn ptr would not be const.
  2358.  
  2359. In the same way, there are three distinct concepts for data members:
  2360.  * virtual data: the defn (`class') of the subobject is overridable in
  2361.    subclasses provided its declaration (`type') remains the same, and this
  2362.    overriddenness is a static property of the [sub]class.
  2363.  * per-object-data: any given object of a class can instantiate a different
  2364.    conformal (same type) subobject upon initialization (usually a `wrapper'
  2365.    object), and the exact class of the subobject is a static property of the
  2366.    object that wraps it.
  2367.  * dynamic-data: the subobject's exact class can change dynamically over time.
  2368.  
  2369. The reason they all look so much the same is that none of this is `supported'
  2370. in C++.  It's all merely `allowed', and in this case, the mechanism for faking
  2371. each of these is the same: a ptr to a (probably abstract) base class.  In a
  2372. language that made these `first class' abstraction mechanisms, the difference
  2373. would be more striking, since they'd each have a different syntactic variant.
  2374.  
  2375. ==============================================================================
  2376.  
  2377. Q97: Should class subobjects be ptrs to freestore allocated objs, or contained?
  2378. A: Usually your subobjects should actually be `contained' in the aggregate
  2379. class (but not always; `wrapper' objects are a good example of where you want a
  2380. a ptr/ref; also the N-to-1-uses-a relationship needs something like a ptr/ref).
  2381.  
  2382. There are three reasons why fully contained subobjects have better performance
  2383. than ptrs to freestore allocated subobjects:
  2384.  * extra layer to indirection every time you need to access subobject
  2385.  * extra freestore allocations (`new' in ctor, `delete' in dtor)
  2386.  * extra dynamic binding (reason given later in this question)
  2387.  
  2388. ==============================================================================
  2389.  
  2390. Q98: What are relative costs of the 3 performance hits of allocated subobjects?
  2391. A: The three performance hits are enumerated in the previous question:
  2392.  * By itself, an extra layer of indirection is small potatoes.
  2393.  * Freestore allocations can be a big problem (standard malloc's performance
  2394.    degrades with more small freestore allocations; OO s/w can easily become
  2395.    `freestore bound' unless you're careful).
  2396.  * Extra dynamic binding comes from having a ptr rather than an object.
  2397.    Whenever the C++ compiler can know an object's *exact* class, virtual fn
  2398.    calls can be *statically* bound, which allows inlining.  Inlining allows
  2399.    zillions (would you believe half a dozen :-) optimization opportunities
  2400.    such as procedural integration, register lifetime issues, etc.  The C++
  2401.    compiler can know an object's exact class in three circumstances: local
  2402.    variables, global/static variables, and fully-contained subobjects.
  2403.  
  2404. Thus fully-contained subobjects allow significant optimizations that wouldn't
  2405. be possible under the `subobjects-by-ptr' approach (this is the main reason
  2406. that languages which enforce reference-semantics have `inherent' performance
  2407. problems).
  2408.  
  2409. ==============================================================================
  2410.  
  2411. Q99: What is an `inline virtual member fn'?  Are they ever actually `inlined'?
  2412. A: A inline virtual member fn is a member fn that is inline and virtual :-).
  2413. The second question is much harder to answer.  The short answer is `Yes, but'.
  2414.  
  2415. A virtual call (msg dispatch) via a ptr or ref is always resolved dynamically
  2416. (at run-time).  In these situations, the call is never inlined, since the
  2417. actual code may be from a derived class that was created after the caller was
  2418. compiled.
  2419.  
  2420. The difference between a regular fn call and a virtual fn call is rather small.
  2421. In C++, the cost of dispatching is rarely a problem.  But the lack of inlining
  2422. in any language can be very Very significant.  Ex: simple experiments will show
  2423. the difference to get as bad as an order of magnitude (for zillions of calls to
  2424. insignificant member fns, loss of inlining virtual fns can result in 25X speed
  2425. degradation! [Doug Lea, `Customization in C++', proc Usenix C++ 1990]).
  2426.  
  2427. This is why endless debates over the actual number of clock cycles required to
  2428. do a virtual call in language/compiler X on machine Y are largely meaningless.
  2429. Ie: many language implementation vendors make a big stink about how good their
  2430. msg dispatch strategy is, but if these implementations don't *inline* method
  2431. calls, the overall system performance would be poor, since it is inlining
  2432. --*not* dispatching-- that has the greatest performance impact.
  2433.  
  2434. NOTE: PLEASE READ THE NEXT TWO QUESTIONS TO SEE THE OTHER SIDE OF THIS COIN!
  2435.  
  2436. ==============================================================================
  2437.  
  2438. Q100: Sounds like I should never use reference semantics, right?
  2439. A: Wrong.
  2440.  
  2441. Reference semantics is A Good Thing.  We can't live without pointers.  We just
  2442. don't want our s/w to be One Gigantic Pointer.  In C++, you can pick and choose
  2443. where you want reference semantics (ptrs/refs) and where you'd like value
  2444. semantics (where objects physically contain other objects etc).  In a large
  2445. system, there should be a balance.  However if you implement absolutely
  2446. *everything* as a pointer, you'll get enormous speed hits.
  2447.  
  2448. Objects near the problem skin are larger than higher level objects.  The
  2449. *identity* of these `problem space' abstractions is usually more important than
  2450. their `value'.  These combine to indicate reference semantics should be used
  2451. for problem-space objects (Booch says `Entity Abstractions'; see on `Books').
  2452.  
  2453. The question arises: is reference semantics likely to cause a performance
  2454. problem in these `entity abstractions'?  The key insight in answering this
  2455. question is that the relative interaction frequency is much lower for problem
  2456. skin abstractions than for low level server objects.
  2457.  
  2458. Thus we have an *ideal* situation in C++: we can choose reference semantics for
  2459. objects that need unique identity or that are too large to copy, and we can
  2460. choose value semantics for the others.  The result is very likely to be that
  2461. the highest frequency objects will end up with value semantics.  Thus we
  2462. install flexibility only where it doesn't hurt us, and performance where we
  2463. need it most!
  2464.  
  2465. These are some of the many issues the come into play with real OO design.
  2466. OO/C++ mastery takes time and high quality training.
  2467. That's the investment-price you pay for a powerful tool.
  2468.  
  2469.  <<<<DON'T STOP NOW!  READ THE NEXT QUESTION TOO!!>>>>
  2470.  
  2471. ==============================================================================
  2472.  
  2473. Q101: Does the poor performance of ref semantics mean I should pass-by-value?
  2474. A: No.  In fact, `NO!' :-)
  2475.  
  2476. The previous questions were talking about *subobjects*, not parameters.  Pass-
  2477. by-value is usually a bad idea when mixed with inheritance (larger subclass
  2478. objects get `sliced' when passed by value as a base class object).  Generally,
  2479. objects that are part of an inheritance hierarchy should be passed by ref or by
  2480. ptr, but not by value, since only then do you get the (desired) dynamic
  2481. binding.
  2482.  
  2483. Unless compelling reasons are given to the contrary, subobjects should be by
  2484. value and parameters should be by reference.  The discussion in the previous
  2485. few questions indicates some of the `compelling reasons' for when subobjects
  2486. should be by reference.
  2487.  
  2488. ==============================================================================
  2489.  
  2490. ==============================================================================
  2491.  
  2492.   ****  PART 16 -- Linkage-to/relationship-with C  ****
  2493.  
  2494. ==============================================================================
  2495.  
  2496. Q102: How can I call a C function `f()' from C++ code?
  2497. A: Tell the C++ compiler that it is a C function:  extern "C" void f();
  2498. Be sure to include the full function prototype.  A block of many C functions
  2499. can be grouped via braces, as in:
  2500.  
  2501.  extern "C" {
  2502.    void* malloc(size_t);
  2503.    char* strcpy(char* dest, const char* src);
  2504.    int   printf(const char* fmt, ...);
  2505.  }
  2506.  
  2507. ==============================================================================
  2508.  
  2509. Q103: How can I create a C++ function `f()' that is callable by my C code?
  2510. A: Use the same `extern "C" f()' construct as detailed in the previous
  2511. question, only then proceed to actually define the function in your C++ module.
  2512. The compiler will ensure that the external information sent to the linker uses
  2513. C calling conventions and name mangling (ex: preceded by a single underscore).
  2514. Obviously you can't make several overloaded fns simultaneously callable by a C
  2515. program, since name overloading isn't supported by C.
  2516.  
  2517. Caveats and implementation dependencies:
  2518. * your `main()' should be compiled with your C++ compiler.
  2519. * your C++ compiler should direct the linking process.
  2520.  
  2521. ==============================================================================
  2522.  
  2523. Q104: Why's the linker giving errors for C/C++ fns being called from C++/C fns?
  2524. A: See the previous two questions on how to use `extern "C"'.
  2525.  
  2526. ==============================================================================
  2527.  
  2528. Q105: How can I pass an object of a C++ class to/from a C function?
  2529. A: Here's an example of one that will work (be sure to read the tail of this
  2530. answer which details when such a scheme will *not* work):
  2531.  
  2532.  /****** C/C++ header file: X.h ******/
  2533.  #ifdef __cplusplus    /*`__cplusplus' is #defined iff compiler is C++*/
  2534.    extern "C" {
  2535.  #endif
  2536.  
  2537.  #ifdef __STDC__
  2538.    extern int c_fn(struct X*);  /* ANSI-C prototypes */
  2539.    extern struct X* cplusplus_callback_fn(struct X*);
  2540.  #else
  2541.    extern int c_fn();   /* K&R style */
  2542.    extern struct X* cplusplus_callback_fn();
  2543.  #endif
  2544.  
  2545.  #ifdef __cplusplus
  2546.    }
  2547.  #endif
  2548.  
  2549.  #ifdef __cplusplus
  2550.    class X {
  2551.      int a;
  2552.    public:
  2553.      X();
  2554.      void frob(int);
  2555.    };
  2556.  #endif
  2557.  
  2558. Then, in file `X.C':
  2559.  
  2560.  #include "X.h"
  2561.  X::X() : a(0) { }
  2562.  void X::frob(int aa) { a = aa; }
  2563.  
  2564.  X* cplusplus_callback_fn(X* x)
  2565.  {
  2566.    x->frob(123);
  2567.    return x;
  2568.  }
  2569.  
  2570. In C++ file `main.C':
  2571.  
  2572.  #include "X.h"
  2573.  
  2574.  int main()
  2575.  {
  2576.    X x;
  2577.    c_fn(&x);
  2578.    return 0;
  2579.  }
  2580.  
  2581. Finally, in a C file `c-fn.c':
  2582.  
  2583.  #include "X.h"
  2584.  
  2585.  int c_fn(struct X* x)
  2586.  {
  2587.    if (cplusplus_callback_fn(x))
  2588.      do_one_thing();
  2589.    else
  2590.      do_something_else();
  2591.    return something();
  2592.  }
  2593.  
  2594. Passing ptrs to C++ objects to/from C fns will FAIL if you pass and get back
  2595. something that isn't *exactly* the same pointer, such as passing a base class
  2596. ptr and receiving a derived class ptr (this fails when multiple inheritance is
  2597. involved, since C fails to do pointer-conversion properly).
  2598.  
  2599. ==============================================================================
  2600.  
  2601. Q106: Can my C function access data in an object of a C++ class?
  2602. A: Sometimes.
  2603.  
  2604. (First read the previous question on passing C++ objects to/from C functions.)
  2605. You can safely access a C++ object's data from a C function if the C++ class:
  2606.  * has no virtual functions (including inherited virtual fns)
  2607.  * has all its data in the same access-level section (private/protected/public)
  2608.  * has no fully-contained subobjects with virtual fns
  2609.  
  2610. If the C++ class has any base classes at all (or if any fully contained
  2611. subobjects have base classes), accessing the data will *technically* be
  2612. non-portable, since class layout under inheritance isn't imposed by the
  2613. language.  However in practice, all C++ compilers do it the same way: the base
  2614. class object appears first (in left-to-right order in the event of multiple
  2615. inheritance), and subobjects follow.
  2616.  
  2617. Furthermore you can often (but less than always) assume a `void*' appears in
  2618. the object at the location of the first virtual function.  This is trickier,
  2619. since the first virtual function is often in a different access specifier
  2620. section than the data members.  Even the use of a single pointer is not
  2621. required by the language (but this is the way `everyone' does it).
  2622.  
  2623. If the class has any virtual base classes, it is more complicated and less
  2624. portable.  One common implementation technique is for objects to contain an
  2625. object of the virtual base class (V) last (regardless of where `V' shows up as
  2626. a virtual base class in the inheritance DAG), with the rest of the object's
  2627. parts appearing in the normal order.  Every class that has V as a virtual base
  2628. class actually has a *pointer* to the V part of the final object.
  2629.  
  2630. ==============================================================================
  2631.  
  2632. Q107: Why do I feel like I'm `further from the machine' in C++ as opposed to C?
  2633. A: Because you are.  Being an OOPL, C++ allows you to directly model the
  2634. problem domain itself (obviously OOD is more complex than this, but a good
  2635. start at `finding the objects' is to model the nouns in the problem domain).
  2636. By modeling the problem domain, the system interacts in the language of the
  2637. problem domain rather than in the language of the solution domain.
  2638.  
  2639. One of C's great strengths is the fact that it has `no hidden mechanism'.  What
  2640. you see is what you get.  You can read a C program and `see' every clock cycle.
  2641. This is not the case in C++; overloaded operators are a case in point.  Old
  2642. line C programmers (such as many of us once were) are often ambivalent about
  2643. this feature, but soon we realize that it provides a level of abstraction and
  2644. economy of expression which lowers maintenance costs without destroying runtime
  2645. performance.
  2646.  
  2647. Naturally you can write assembly code in any language; using C++ doesn't
  2648. guarantee any particular level of quality, reusability, abstraction, or any
  2649. other measure of `goodness'.  C++ doesn't try to make it impossible for bad
  2650. programmers to write bad programs; it enables good programmers to write good
  2651. programs.
  2652.  
  2653. ==============================================================================
  2654.  
  2655.   ****  PART 17 -- Pointers to member functions  ****
  2656.  
  2657. ==============================================================================
  2658.  
  2659. Q108: What is the type of `ptr-to-member-fn'?  Is it diffn't from `ptr-to-fn'?
  2660. A: A member fn of class X has type:  Returntype (X::*)(Argtypes)
  2661.    while a plain function has type:  Returntype (*)   (Argtypes)
  2662.  
  2663. ==============================================================================
  2664.  
  2665. Q109: How can I ensure `X's objects are only created with new, not on the
  2666. stack?
  2667. A: Make constructors protected and define `friend' or `static' fns that return
  2668. a ptr to objects created via `new' (the ctors must be protected rather than
  2669. private, otherwise you couldn't derive from the class).  Ex:
  2670.  
  2671.  class X { //only want to allow dynamicly allocated X's
  2672.  public:
  2673.    static X* create()           { return new X();  }
  2674.    static X* create(int i)      { return new X(i); }
  2675.    static X* create(const X& x) { return new X(x); }
  2676.  protected:
  2677.             X();
  2678.             X(int i);
  2679.             X(const X& x);
  2680.    virtual ~X();
  2681.  };
  2682.  
  2683.  X* Xptr = X::create(5);
  2684.  
  2685. ==============================================================================
  2686.  
  2687. Q110: How do I pass a ptr to member fn to a signal handler,X event
  2688. callback,etc?
  2689. A: Because a member function is meaningless without an object to invoke it on,
  2690. you can't do this directly (if `X' were rewritten in C++, it would probably
  2691. pass references to *objects* around, not just pointers to fns; naturally the
  2692. objects would embody the required function and probably a whole lot more).
  2693.  
  2694. As a patch for existing software, use a free function as a wrapper which takes
  2695. an object obtained through some other technique (held in a global, perhaps) and
  2696. calls the desired member function.  There is one exception: static member
  2697. functions do not require an actual object to be invoked, and ptrs-to-static-
  2698. member-fns are type compatible with regular ptrs-to-fns (see ARM p.25, 158).
  2699.  
  2700. Ex: suppose you want to call X::memfn() on interrupt:
  2701.  
  2702.     class X {
  2703.     public:
  2704.              void memfn();
  2705.       static void staticmemfn(); //a static member fn can handle it
  2706.       //...
  2707.     };
  2708.  
  2709.     //wrapper fn remembers the object on which to invoke memfn in a static var:
  2710.     static X* object_which_will_handle_signal;
  2711.     void X_memfn_wrapper() { object_which_will_handle_signal.memfn(); }
  2712.  
  2713.     main()
  2714.     {
  2715.       /* signal(SIGINT, X::memfn); */   //Can NOT do this
  2716.       signal(SIGINT, X_memfn_wrapper);  //Ok
  2717.       signal(SIGINT, X::staticmemfn);   //Also Ok
  2718.     }
  2719.  
  2720. ==============================================================================
  2721.  
  2722. Q111: Why am I having trouble taking the address of a C++ function?
  2723. Short ans: Please read previous question first; this is a corollary.
  2724.  
  2725. Long ans: In C++, member fns have an implicit parameter which points to the
  2726. object (the `this' ptr inside the member fn).  Normal C fns can be thought of
  2727. as having a different calling convention from member fns, so the types of their
  2728. ptrs (ptr-to-member-fn vs ptr-to-fn) are different and incompatible.  C++
  2729. introduces a new type of ptr, called a ptr-to-member, which can only be invoked
  2730. by providing an object (see ARM 5.5).  Do NOT attempt to `cast' a ptr-to-mem-fn
  2731. into a ptr-to-fn; the result is undefined and probably disastrous; a ptr-to-
  2732. member-fn is NOT required to contain the machine addr of the appropriate fn
  2733. (see ARM, 8.1.2c, p.158).  As was said in the last example, if you want a
  2734. regular C fn ptr, use either a top-level (non-class) fn, or a `static' (class)
  2735. member fn.
  2736.  
  2737. ==============================================================================
  2738.  
  2739. Q112: How do I declare an array of pointers to member functions?
  2740. A: Use the following declaration:
  2741.  
  2742.  class Frob {
  2743.  public:
  2744.    Rettype f(T1 x, T2 y);
  2745.    Rettype g(T1 x, T2 y);
  2746.    Rettype h(T1 x, T2 y);
  2747.    Rettype i(T1 x, T2 y);
  2748.    //...
  2749.  };
  2750.  
  2751.  Rettype (Frob::*fn_ptr[3])(T1,T2) = { &Frob::f, &Frob::g, &Frob::h };
  2752.  
  2753. You can make the array declaration somewhat clearer with a typedef:
  2754.  typedef  Rettype (Frob::*Frob_member_ptr)(T1,T2);
  2755.  //...
  2756.  Frob_member_ptr fn_ptr[3] = { &Frob::f, &Frob::g, &Frob::h };
  2757.  
  2758. To call one of the functions on an object `frob', use:
  2759.  Frob frob;
  2760.  //...
  2761.  (frob.*fn_ptr[i])(x, y);
  2762.  
  2763. You can make the call somewhat clearer using a #define:
  2764.  #define  apply_member_fn(object,fn)   ((object).*(fn))
  2765.  //...
  2766.  apply_member_fn(frob,fn_ptr[i])(x, y)
  2767.  
  2768. ==============================================================================
  2769.  
  2770.   ****  PART 18 -- Container classes and templates  ****
  2771.  
  2772. ==============================================================================
  2773.  
  2774. Q113: How can I insert/access/change elements from a linked list/hashtable/etc?
  2775. A: I'll use a `inserting into a linked list' as a prototypical example.  The
  2776. obvious approach is to allow insertion at the head and tail of the list, but
  2777. that would produce a library that is too weak (a weak library is almost worse
  2778. than no library).  Whenever encapsulation frustrates rather than helps a user,
  2779. it may be that the class' public interface needs enhancing.  If class List only
  2780. supports adding at the front and tail, it *definitely* needs more strength.
  2781.  
  2782. This answer will be a lot to swallow for novice C++'ers, so I'll give a couple
  2783. of options.  As usual, the first is easiest, while the second option is better.
  2784. I also give a thumbnail sketch of a third option, which has certain advantages
  2785. and disadvantages over the second option.
  2786.  
  2787. [1] Empower the List with a `viewport' or `cursor' that references an arbitrary
  2788. list element.  Implies adding member fns to List such as advance(), backup(),
  2789. atend(), atbegin(), rewind(), fastforward(), and current().  `current()'
  2790. returns the element of the List that is currently `under the cursor'.  Finally
  2791. you'll need to add a few more member fns to *mutate* the list, such as
  2792. changeto(X), insert(X), remove(), etc.
  2793.  
  2794. [2] Provide a separate class called ListIter.  ListIter has member fns named
  2795. similar to the above (though probably with operator overloading, but that's
  2796. just syntactic sugar for member fns).  The List itself would have none of the
  2797. above mentioned member fns, and the ListIter would be a `friend' of List
  2798. (ListIter would have to have access to the innards of List; this allows the
  2799. world to have safe access abilities to List without violating encapsulation).
  2800.  
  2801. The reason option [2] is better becomes apparent when you use classes that only
  2802. support [1].  In particular, if you pass a List off to a subcall, you'd better
  2803. hope the subcall didn't warp the `cursor' around, or your code may fail.  Also,
  2804. if you try to get all pairs of elements, it's very hard if you only have one
  2805. cursor.  The distinct-class iterator concept removes these restrictions.  My
  2806. own class library uses these extensively, as will most any other commercial
  2807. grade class library.
  2808.  
  2809. Note that the options are not mutually exclusive; it is possible to provide
  2810. both [2] *and* [1], giving rise to the notion of a `primary' list position,
  2811. with instances of ListIter being somewhat secondary.
  2812.  
  2813. [3] The third possibility considers the entire iteration as an atomic event.  A
  2814. class is created which embodies this event.  The nice thing about this third
  2815. alternative is that the public access methods (which may be virtual fns) can be
  2816. avoided during the inner loop, thus enhancing performance.  The down side is
  2817. that you get extra object code in the application, since templates gain speed
  2818. by duplicating code.  This third technique is due to Andrew Koenig in a paper
  2819. published recently in JOOP [`Templates as interfaces', JOOP, 4, 5 (Sept 91)].
  2820. You can also see a taste of it in Bjarne Stroustrup's book, The C++ Programming
  2821. Language Second Edition (look for `Comparator' in the index).
  2822.  
  2823. ==============================================================================
  2824.  
  2825. Q114: What's the idea behind `templates'?
  2826. A: A template is a cookie-cutter that specifies how to cut cookies that all
  2827. look pretty much the same (although the cookies can be made of various kinds of
  2828. dough, they'll all have the same basic shape).  In the same way, a class
  2829. template is a cookie cutter to description of how to build classes that all
  2830. look basically the same, and a function template describes how to build similar
  2831. looking functions.
  2832.  
  2833. The questions about templates are in the `Containers' section since templates
  2834. are often used to build type safe containers (although this only scratches the
  2835. surface for how they can be used).  We will see how to use templates to build
  2836. container classes below.
  2837.  
  2838. ==============================================================================
  2839.  
  2840. Q115: What's the syntax / semantics for a `function template'?
  2841. A: Consider this function that swaps its two integer arguments:
  2842.  
  2843.  void swap(int& x, int& y)
  2844.  {
  2845.    int tmp = x;
  2846.    x = y;
  2847.    y = tmp;
  2848.  }
  2849.  
  2850. If we also had to swap floats, longs, Strings, Sets, and FileSystems, we'd get
  2851. pretty tired of coding lines that look almost identical except for the type.
  2852. Mindless repetition is an ideal job for a computer, hence a function template:
  2853.  
  2854.  template<class T>
  2855.  void swap(T& x, T& y)
  2856.  {
  2857.    T tmp = x;
  2858.    x = y;
  2859.    y = tmp;
  2860.  }
  2861.  
  2862. Every time we used `swap()' with a given pair of types, the compiler will go to
  2863. the above definition and will create yet another `template function' as an
  2864. instantiation of the above.  Ex:
  2865.  
  2866.  main()
  2867.  {
  2868.    int    i,j;  /*...*/  swap(i,j);  //instantiates a swap for `int'
  2869.    float  a,b;  /*...*/  swap(a,b);  //instantiates a swap for `float'
  2870.    char   c,d;  /*...*/  swap(c,d);  //instantiates a swap for `char'
  2871.    String s,t;  /*...*/  swap(s,t);  //instantiates a swap for `String'
  2872.  }
  2873.  
  2874. (note: a `template function' is the instantiation of a `function template').
  2875.  
  2876. ==============================================================================
  2877.  
  2878. Q116: What's the syntax / semantics for a `class template'?
  2879. A: Consider this container class of that acts like an array of integers:
  2880.  
  2881.  //this would go into a header file such as `Vec.h':
  2882.  class Vec {
  2883.  public:
  2884.    int         len()             const { return xlen;     }
  2885.    const int&  operator[](int i) const { xdata[check(i)]; }
  2886.          int&  operator[](int i)       { xdata[check(i)]; }
  2887.                Vec(int L=10) : xlen(L), xdata(new int[L]) { /*verify*/ }
  2888.               ~Vec()                   { delete [] xdata; }
  2889.  private:
  2890.    int  xlen;
  2891.    int* xdata;
  2892.    int  check(int i);  //return i if i>=0 && i<xlen else throw exception
  2893.  };
  2894.  
  2895.  //this would be part of a `.C' file such as `Vec.C':
  2896.  int Vec::check(int i)
  2897.  {
  2898.    if (i < 0 || i >= xlen) throw BoundsViol("Vec", i, xlen);
  2899.    return i;
  2900.  }
  2901.  
  2902. Just as with `swap()' above, repeating the above over and over for Vec of
  2903. float, char, String, Vec, Vec-of-Vec-of-Vec, etc, will become tedious.  Hence
  2904. we create a single class template:
  2905.  
  2906.  //this would go into a header file such as `Vec.h':
  2907.  template<class T>
  2908.  class Vec {
  2909.  public:
  2910.    int       len()             const { return xlen;     }
  2911.    const T&  operator[](int i) const { xdata[check(i)]; }
  2912.          T&  operator[](int i)       { xdata[check(i)]; }
  2913.              Vec(int L=10) : xlen(L), xdata(new T[L]) { /*verify*/ }
  2914.             ~Vec()                   { delete [] xdata; }
  2915.  private:
  2916.    int  xlen;
  2917.    T*   xdata;
  2918.    int  check(int i);  //return i if i>=0 && i<xlen else throw exception
  2919.  };
  2920.  
  2921.  //this would be part of a `.C' file such as `Vec.C':
  2922.  template<class T>
  2923.  int Vec<T>::check(int i)
  2924.  {
  2925.    if (i < 0 || i >= xlen) throw BoundsViol("Vec", i, xlen);
  2926.    return i;
  2927.  }
  2928.  
  2929. Unlike template functions, template classes (instantiations of class templates)
  2930. need to be explicit about the parameters over which they are instantiating:
  2931.  
  2932.  main()
  2933.  {
  2934.    Vec<int>        vi;
  2935.    Vec<float>      vf;
  2936.    Vec<char*>      vc;
  2937.    Vec<String>     vs;
  2938.    Vec< Vec<int> > vv;
  2939.  }          // ^^^-- note the space; do NOT use Vec<Vec<int>> since the
  2940.             //       `maximal munch' rule would grab a single `>>' token
  2941.  
  2942. ==============================================================================
  2943.  
  2944. Q117: What is a `parameterized type'?
  2945. A: A parameterized type is a type that is parameterized over another value or
  2946. type.  Ex: List<int> is a type that is parameterized over another type, `int'.
  2947. Therefore the C++ rendition of parameterized types is provided by class
  2948. templates.
  2949.  
  2950. ==============================================================================
  2951.  
  2952. Q118: What is `genericity'?
  2953. A: Not to be confused with `generality' (which just means avoiding solutions
  2954. which are overly specific), `genericity' means parameterized types.  In C++,
  2955. this is provided by class templates.
  2956.  
  2957. ==============================================================================
  2958.  
  2959. Q119: How can I fake templates if I don't have a compiler that supports them?
  2960. A: The best answer is: buy a compiler that supports templates.  When this is
  2961. not feasible, the next best answer is to buy or build a template preprocessor
  2962. (ex: reads C++-with-templates, outputs C++-with-expanded-template-classes; such
  2963. a system needn't be perfect; it cost my company about three man-weeks to
  2964. develop such a preprocessor).  If neither of these is feasible, you can use the
  2965. macro preprocessor to fake templates.  But beware: it's tedious; templates are
  2966. a better solution wrt development and maintenance costs.
  2967.  
  2968. Here's how you'd declare my `Vec' example from above.  First we define `Vec(T)'
  2969. to concatenate the name `Vec' with that of the type T (ex: Vec(String) becomes
  2970. `VecString').  This would go into a header file such as Vec.h:
  2971.  
  2972.  #include <generic.h> //to get the `name2()' macro
  2973.  #define  Vec(T)  name2(Vec,T)
  2974.  
  2975. Next we declare the class Vec(T) using the name `Vecdeclare(T)' (in general you
  2976. would postfix the name of the class with `declare', such as `Listdeclare' etc):
  2977.  
  2978.  #define Vecdeclare(T)      \
  2979.  class Vec(T) {       \
  2980.    int  xlen;       \
  2981.    T*   xdata;       \
  2982.    int  check(int i);  /*return i if in bounds else throw*/ \
  2983.  public:        \
  2984.    int       len()             const { return xlen;     } \
  2985.    const T&  operator[](int i) const { xdata[check(i)]; } \
  2986.          T&  operator[](int i)       { xdata[check(i)]; } \
  2987.              Vec(T)(int L=10): xlen(L), xdata(new T[L]) {/*...*/}\
  2988.             ~Vec(T)()                   { delete [] xdata; } \
  2989.  };
  2990.  
  2991. Note how each occurrence of `Vec' has the `(T)' postfixed.  Finally we set up
  2992. another macro that `implements' the non-inline member function(s) of Vec:
  2993.  
  2994.  //strangely enough this can also go into Vec.h
  2995.  #define Vecimplement(T)      \
  2996.  int Vec(T)::check(int i)     \
  2997.  {        \
  2998.    if (i < 0 || i >= xlen) throw BoundsViol("Vec", i, xlen); \
  2999.    return i;       \
  3000.  }
  3001.  
  3002. When you wish to use a Vec-of-String and Vec-of-int, you would say:
  3003.  
  3004.  #include "Vec.h"     //pulls in <generic.h> too; see below...
  3005.  declare(Vec,String)  //`declare()' is a macro defined in <generic.h>
  3006.  declare(Vec,int)
  3007.  Vec(String) vs;      //Vec(String) becomes the single token `VecString'
  3008.  Vec(int)    vi;
  3009.  
  3010. In exactly one source file in the system, you must provide implementations for
  3011. the non-inlined member functions:
  3012.  
  3013.  #include "Vec.h"
  3014.  declare  (Vec,String)   declare  (Vec,int)   declare  (Vec,float)
  3015.  implement(Vec,String)   implement(Vec,int)   implement(Vec,float)
  3016.  
  3017. Note that types whose names are other than a single identifier do not work
  3018. properly.  Ex: Vec(char*) creates a class whose name is `Vecchar*'.  The patch
  3019. is to create a typedef for the appropriate type:
  3020.  
  3021.  #include "Vec.h"
  3022.  typedef char* charP;
  3023.  declare(Vec,charP)
  3024.  
  3025. It is important that every declaration of what amounts to `Vec<char*>' must all
  3026. use exactly the same typedef, otherwise you will end up with several equivalent
  3027. classes, and you'll have unnecessary code duplication.  This is the sort of
  3028. tedium which a template mechanism can handle for you.
  3029.  
  3030. ==============================================================================
  3031.  
  3032.   ****  PART 19 -- Nuances of particular implementations  ****
  3033.  
  3034. ==============================================================================
  3035.  
  3036. Q120: Why don't variable arg lists work for C++ on a Sun SPARCstation?
  3037. A: That is a bug in cfront 2.1.  There is a magic variable, __builtin_va_alist.
  3038. It has to be added to the end of the argument list of a varadic function, and
  3039. it has to be referenced in va_start.  This requires source modification to (a)
  3040. print `,__builtin_va_alist' on the end of the argument list, (b) pretend that
  3041. this arg was declared, and thus pass references to it, and (c) not mangle its
  3042. name in the process.
  3043.  
  3044. Here's a tiny bit more detail:
  3045. 1) when print2.c prints a varadic procedure, it should add __builtin_va_alist
  3046.    to the end. It need not declare it. Type of int to the Sun C compiler (the
  3047.    default) is fine.
  3048. 2) #define   va_start(ap,parmN)   ap = (char *)&__builtin_va_alist
  3049. 3) when find.c see this reference to __builtin_va_alist, it should construct a
  3050.    special cfront name node. When name::print sees that node it should print
  3051.    its name literally, without adding any mangling.
  3052. 4) the same trick is needed, with the name va_alist, for Ultrix/MIPS and HPUX.
  3053. 5) the net result, in generated C code, looks like:
  3054.  void var_proc (a, b, c, __builtin_va_alist)
  3055.    int a;
  3056.    float b;
  3057.    char * c;
  3058.  {
  3059.      char * val;
  3060.      val = &__builtin_va_alist;
  3061.      ...
  3062.  }
  3063.  
  3064. ==============================================================================
  3065.  
  3066. Q121: GNU C++ (g++) produces big executables for tiny programs; Why?
  3067. A: libg++ (the library used by g++) was probably compiled with debug info (-g).
  3068. On some machines, recompiling libg++ without debugging can save lots of disk
  3069. space (~1 Meg; the down-side: you'll be unable to trace into libg++ calls).
  3070. Merely `strip'ping the executable doesn't reclaim as much as recompiling
  3071. without -g followed by subsequent `strip'ping the resultant `a.out's.
  3072.  
  3073. Use `size a.out' to see how big the program code and data segments really are
  3074. rather than `ls -s a.out' which includes the symbol table.
  3075.  
  3076. ==============================================================================
  3077.  
  3078. Q122: Is there a yacc-able C++ grammar?
  3079. A: Jim Roskind is the author of a yacc grammar for C++. It's roughly compatible
  3080. with the portion of the language implemented by USL cfront 2.0.  Jim's grammar
  3081. deviates from cfront (and the ARM) in a couple of what I understand to be minor
  3082. ways.  Ultimately any deviation from a standard is unthinkable, but the number
  3083. of real programs that are interpreted differently is relatively small, so the
  3084. `consequence' of the deviation is not great.
  3085.  
  3086. I have used Jim's grammar when a grad student wrote a C++ templatizer mechanism
  3087. (reads ANSI-C++, spits out pre-templates C++), but my expertise does not
  3088. include precise knowledge of where the grammar deviates from `official'.  I
  3089. have found it to parse most things correctly, but I am aware that there are
  3090. differences.  (is that noncommittal enough? :-)
  3091.  
  3092. The grammar can be accessed by anonymous ftp from the following sites:
  3093. * ics.uci.edu (128.195.1.1) in the ftp/gnu directory (even though
  3094.   neither of the archives are GNU related) as:
  3095.         c++grammar2.0.tar.Z and byacc1.8.tar.Z
  3096. * mach1.npac.syr.edu (128.230.7.14) in the ftp/pub/C++ directory as:
  3097.         c++grammar2.0.tar.Z and byacc1.8.tar.z
  3098.  
  3099. Jim Roskind can be reached at jar@hq.ileaf.com or  ...!uunet!leafusa!jar
  3100.  
  3101. ==============================================================================
  3102.  
  3103. Q123: What is C++ 1.2?  2.0?  2.1?  3.0?
  3104. A: These are not versions of the language, but rather versions of the USL
  3105. translator, cfront.  However many people discuss these as levels of the
  3106. language as well, since each of the above versions represents additions to the
  3107. portion of the C++ language which is implemented by the compiler. When ANSI/ISO
  3108. C++ is finalized, conformance with the ANSI/ISO spec will become more important
  3109. than conformance with cfront version X.Y, but presently, cfront is acting as a
  3110. de facto standard to help coordinate the industry (although it leaves certain
  3111. features of the language unimplemented as well).
  3112.  
  3113. *VERY* roughly speaking, these are the major features:
  3114.  * 2.0 includes multiple/virtual inheritance and pure virtual functions.
  3115.  * 2.1 includes semi-nested classes and `delete [] ptr_to_array'.
  3116.  * 3.0 includes fully-nested classes, templates and `i++' vs `++i'.
  3117.  *?4.0? will include exceptions.
  3118.  
  3119. ==============================================================================
  3120.  
  3121. Q124: How does the lang accepted by cfront 3.0 differ from that accepted by
  3122. 2.1?
  3123. A: USL cfront release 3.0 provides implementations of a number of features that
  3124. were previously flagged as `sorry not implemented':
  3125.  
  3126.   templates, fully nested types, prefix and postfix increment and decrement
  3127.   operators, initialization of single dimension arrays of class objects with
  3128.   ctors taking all default arguments, use of operators &&, ||, and ?: with
  3129.   expressions requiring temporaries of class objects containing destructors,
  3130.   and implicit named return values.
  3131.  
  3132. The major feature not accepted by cfront 3.0 is exceptions.
  3133.  
  3134. ==============================================================================
  3135.  
  3136. Q125: Why are exceptions going to be implemented after templates? Why not both?
  3137. A: Most C++ compiler vendors are providing templates in their present release,
  3138. but very few are providing exceptions (I know of only one).  The reason for
  3139. going slowly is that both templates and exception handling are difficult to
  3140. implement *well*. A poor template implementation will give slow compile and
  3141. link times and a poor exception handling implementation will give slow run
  3142. times.  Good implementations will not have those problems.
  3143.  
  3144. C++ compiler vendors are human beings too, and they can only get so much done
  3145. at once.  However they know that the C++ community is craving for the `whole'
  3146. language, so they'll be pushing hard to fill that need.
  3147.  
  3148. ==============================================================================
  3149.  
  3150. Q126: What was C++ 1.xx, and how is it different from the current C++ language?
  3151. A: C++ 1.2 (the version number corresponds to the release number of USL's
  3152. cfront) corresponds to Bjarne Stroustrup's first edition (`The C++ Programming
  3153. Language', ISBN 0-201-12078-X).  In contrast, the present version (3.0)
  3154. corresponds roughly to the `ARM', except for exceptions.  Here is a summary of
  3155. the differences between the first edition of Bjarne's book and the ARM:
  3156.  - A class can have more than one direct base class (multiple inheritance).
  3157.  - Class members can be `protected'.
  3158.  - Pointers to class members can be declared and used.
  3159.  - Operators `new' and `delete' can be overloaded and declared for a class.
  3160.      This allows the "assignment to `this'" technique for class specific
  3161.      specific storage management to be removed to the anachronism section
  3162.  - Objects can be explicitly destroyed.
  3163.  - Assignment and Copy-Initialization default to member-wise assignment and
  3164.      copy-initialization.
  3165.  - The `overload' keyword was made redundant and removed to the anachronism
  3166.      section.
  3167.  - General expressions are allowed as initializers for static objects.
  3168.  - Data objects can be `volatile' (new keyword).
  3169.  - Initializers are allowed for `static' class members.
  3170.  - Member functions can be `static'.
  3171.  - Member functions can be `const' or `volatile'.
  3172.  - Linkage to non-C++ program fragments can be explicitly declared.
  3173.  - Operators `->', `->*' and `,' can be overloaded.
  3174.  - Classes can be abstract.
  3175.  - Prefix and postfix application of `++' and `--' on a user-defined type
  3176.      can be distinguished.
  3177.  - Templates.
  3178.  - Exception handling.
  3179.  
  3180. ==============================================================================
  3181.  
  3182.   ****  PART 20 -- Miscellaneous technical and environmental issues  ****
  3183.  
  3184. ==============================================================================
  3185. SUBSECTION: Miscellaneous technical issues:
  3186. ==============================================================================
  3187.  
  3188. Q127: Why are classes with static data members getting linker errors?
  3189. A: Static member variables must be given an explicit definition in exactly one
  3190. module.  Ex:
  3191.  
  3192.  class X {
  3193.    //...
  3194.    static int i;  //*declare* static member X::i
  3195.    //...
  3196.  };
  3197.  
  3198. The linker will holler at you (`X::i is not defined') unless (exactly) one of
  3199. your source files has something like the following:
  3200.  
  3201.  int X::i = some_expression_evaluating_to_an_int;     //*define* X::i
  3202. or:
  3203.  int X::i;                     //define --but don't initialize-- X::i
  3204.  
  3205. The usual place to define static member variables of class `X' is file `X.C'
  3206. (or X.cpp, X.cc, X.c++, X.c or X.cxx; see question on file naming conventions).
  3207.  
  3208. ==============================================================================
  3209.  
  3210. Q128: What's the difference between the keywords struct and class?
  3211. A: The members and base classes of a struct are public by default, while in
  3212. class, they default to private.  Base classes of a struct are public by default
  3213. while they are private by default with `class' (however you should make your
  3214. base classes *explicitly* public, private, or protected).  `Struct' and `class'
  3215. are otherwise functionally equivalent.
  3216.  
  3217. ==============================================================================
  3218.  
  3219. Q129: Why can't I overload a function by its return type?
  3220.  
  3221. Ex: the compiler says the following two are an error:
  3222.  char  f(int i);
  3223.  float f(int i);
  3224.  
  3225. A: Return types are not considered when determining unique signatures for
  3226. overloading functions; only the number and type of parameters are considered.
  3227. Reason: which function should be called if the return value is ignored?  Ex:
  3228.  
  3229.  main()
  3230.  {
  3231.    f(3);  //which should be invoked??
  3232.  }
  3233.  
  3234. ==============================================================================
  3235.  
  3236. Q130: What is `persistence'?  What is a `persistent object'?
  3237. A: Loosely speaking, a persistent object is one that lives on after the
  3238. program which created it has stopped.  Persistent objects can even outlive
  3239. various versions of the creating program, can outlive the disk system, the
  3240. operating system, or even the hardware on which the OS was running when
  3241. they were created.
  3242.  
  3243. The challenge with persistent objects is to effectively store their method
  3244. code out on secondary storage along with their data bits (and the data bits
  3245. and method code of all subobjects, and of all their subobjects, etc).  This
  3246. is non-trivial when you have to do it yourself.  In C++, you have to do it
  3247. yourself.  C++/OO databases can help hide the mechanism for all this.
  3248.  
  3249. ==============================================================================
  3250. SUBSECTION: Miscellaneous environmental issues:
  3251. ==============================================================================
  3252.  
  3253. Q131: Is there a TeX or LaTeX macro that fixes the spacing on `C++'?
  3254. A: Yes, here are two:
  3255.  
  3256. \def\CC{C\raise.22ex\hbox{{\footnotesize +}}\raise.22ex\hbox{\footnotesize +}}
  3257.  
  3258. \def\CC{{C\hspace{-.05em}\raisebox{.4ex}{\tiny\bf ++}}}
  3259.  
  3260. ==============================================================================
  3261.  
  3262. Q132: Where can I access C++2LaTeX, a LaTeX pretty printer for C++ source?
  3263. A: Here are a few ftp locations:
  3264.  
  3265. Host aix370.rrz.uni-koeln.de   (134.95.80.1) Last updated 15:41 26 Apr 1991
  3266.     Location: /tex
  3267.       FILE      rw-rw-r--     59855  May  5  1990   C++2LaTeX-1.1.tar.Z
  3268. Host utsun.s.u-tokyo.ac.jp   (133.11.11.11) Last updated 05:06 20 Apr 1991
  3269.     Location: /TeX/macros
  3270.       FILE      rw-r--r--     59855  Mar  4 08:16   C++2LaTeX-1.1.tar.Z
  3271. Host nuri.inria.fr   (128.93.1.26) Last updated 05:23  9 Apr 1991
  3272.     Location: /TeX/tools
  3273.       FILE      rw-rw-r--     59855  Oct 23 16:05   C++2LaTeX-1.1.tar.Z
  3274. Host iamsun.unibe.ch   (130.92.64.10) Last updated 05:06  4 Apr 1991
  3275.     Location: /TeX
  3276.       FILE      rw-r--r--     59855  Apr 25  1990   C++2LaTeX-1.1.tar.Z
  3277. Host iamsun.unibe.ch   (130.92.64.10) Last updated 05:06  4 Apr 1991
  3278.     Location: /TeX
  3279.       FILE      rw-r--r--     51737  Apr 30  1990
  3280.       C++2LaTeX-1.1-PL1.tar.Z
  3281. Host tupac-amaru.informatik.rwth-aachen.de   (192.35.229.9) Last updated 05:07
  3282. 18 Apr 1991
  3283.     Location: /pub/textproc/TeX
  3284.       FILE      rw-r--r--     72957  Oct 25 13:51  C++2LaTeX-1.1-PL4.tar.Z
  3285. Host wuarchive.wustl.edu   (128.252.135.4) Last updated 23:25 30 Apr 1991
  3286.     Location: /packages/tex/tex/192.35.229.9/textproc/TeX
  3287.       FILE      rw-rw-r--     49104  Apr 10  1990   C++2LaTeX-PL2.tar.Z
  3288.       FILE      rw-rw-r--     25835  Apr 10  1990   C++2LaTeX.tar.Z
  3289. Host tupac-amaru.informatik.rwth-aachen.de   (192.35.229.9) Last updated 05:07
  3290. 18 Apr 1991
  3291.     Location: /pub/textproc/TeX
  3292.       FILE rw-r--r-- 74015  Mar 22 16:23 C++2LaTeX-1.1-PL5.tar.Z
  3293.     Location: /pub
  3294.       FILE rw-r--r-- 74015  Mar 22 16:23 C++2LaTeX-1.1-PL5.tar.Z
  3295. Host sol.cs.ruu.nl   (131.211.80.5) Last updated 05:10 15 Apr 1991
  3296.     Location: /TEX/TOOLS
  3297.       FILE      rw-r--r--     74015  Apr  4 21:02x   C++2LaTeX-1.1-PL5.tar.Z
  3298. Host tupac-amaru.informatik.rwth-aachen.de (192.35.229.9) Last updated 05:07 18
  3299. Apr 1991
  3300.     Location: /pub/textproc/TeX
  3301.       FILE      rw-r--r--      4792  Sep 11  1990 C++2LaTeX-1.1-patch#1
  3302.       FILE      rw-r--r--      2385  Sep 11  1990 C++2LaTeX-1.1-patch#2
  3303.       FILE      rw-r--r--      5069  Sep 11  1990 C++2LaTeX-1.1-patch#3
  3304.       FILE      rw-r--r--      1587  Oct 25 13:58 C++2LaTeX-1.1-patch#4
  3305.       FILE      rw-r--r--      8869  Mar 22 16:23 C++2LaTeX-1.1-patch#5
  3306.       FILE      rw-r--r--      1869  Mar 22 16:23 C++2LaTeX.README
  3307. Host rusmv1.rus.uni-stuttgart.de   (129.69.1.12) Last updated 05:13 13 Apr 1991
  3308.     Location: /soft/tex/utilities
  3309.       FILE      rw-rw-r--    163840  Jul 16  1990   C++2LaTeX-1.1.tar
  3310.  
  3311. ==============================================================================
  3312.  
  3313. Q133: Where can I access `tgrind', a pretty printer for C++/C/etc source?
  3314. A: `tgrind' reads the file to be printed and a command line switch to see what
  3315. the source language is.  It then reads a language definition database file and
  3316. learns the syntax of the language (list of keywords, literal string delimiters,
  3317. comment delimiters, etc).
  3318.  
  3319. `tgrind' usually comes with the public distribution of TeX and LaTeX.  Look in
  3320. the directory:
  3321.  ...tex82/contrib/van/tgrind
  3322.  
  3323. A more up-to-date version of tgrind by Jerry Leichter can be found on:
  3324.  venus.ycc.yale.edu in [.TGRIND]
  3325.  
  3326. ==============================================================================
  3327.  
  3328. Q134: Is there a C++-mode for GNU emacs?  If so, where can I get it?
  3329. A: Yes, there is a C++-mode for GNU emacs.  You can get it via:
  3330.  
  3331. c++-mode-2 (1.0)  87-12-08
  3332.      Bruce Eckel,Thomas Keffer, <eckel@beluga.ocean.washington.edu,uw-beaver
  3333. beluga!eckel,keffer@sperm.ocean.washington.edu>
  3334.  
  3335. archive.cis.ohio-state.edu:/pub/gnu/emacs/elisp-archive/as-is/c++-mode-2.el.Z
  3336.  
  3337.      Another C++ major mode.
  3338. c++-mode   89-11-07
  3339.      Dave Detlefs, et al, <dld@cs.cmu.edu>
  3340.  
  3341. archive.cis.ohio-state.edu:/pub/gnu/emacs/elisp-archive/modes/c++-mode.el.Z
  3342.  
  3343.      C++ major mode.
  3344. c++    90-02-01
  3345.      David Detlefs, Stewart Clamen, <dld@f.gp.cs.cmu.edu,clamen@cs.cmu.edu>
  3346.      archive.cis.ohio-state.edu:/pub/gnu/emacs/elisp-archive/modes/c++.el.Z
  3347.      C++ code editing commands for Emacs
  3348.  
  3349. c-support (46)   89-11-04
  3350.      Lynn Slater, <lrs@indetech.com>
  3351.  
  3352. archive.cis.ohio-state.edu:/pub/gnu/emacs/elisp-archive/misc/c-support.el.Z
  3353.      Partial support for team C/C++ development.
  3354.  
  3355. ==============================================================================
  3356.  
  3357. Q135: What is `InterViews'?
  3358. A: A non-proprietary toolkit for graphic user interface programming in C++,
  3359. developed by Mark Linton and others when he was at Stanford.  Unlike C++
  3360. wrappers for C libraries such as Motif, InterViews is a true object library.
  3361. Commercially maintained versions are available from Quest, while freely
  3362. redistributable versions (running on top of X) from interviews.stanford.edu (an
  3363. ftp site).  Copies of this are (were?) distributed with the regular X
  3364. distribution.  Other sources of information include comp.windows.interviews,
  3365. which has its own FAQ.
  3366.  
  3367. ==============================================================================
  3368.  
  3369. Q136: Where can I get OS-specific questions answered (ex:BC++,DOS,Windows,etc)?
  3370. A: see comp.os.msdos.programmer, BC++ and Zortech mailing lists, BC++ and
  3371.    Zortech bug lists, comp.windows.ms.programmer, comp.unix.programmer, etc.
  3372.  
  3373. You can subscribe to the BC++ mailing list by sending email to:
  3374. | To: listserv@ucf1vm.cc.ucf.edu   <---or LISTSERV@UCF1VM.BITNET
  3375. | Subject: SUB TCPLUS-L
  3376. | Reply-to: you@your.email.addr    <---ie: put your return address here
  3377.  
  3378. The BC++ bug report is available via anonymous ftp from sun.soe.clarkson.edu
  3379. [128.153.12.3] from the file ~ftp/pub/Turbo-C++/bug-report
  3380. (also, I post it on comp.lang.c++ on the first each month).
  3381.  
  3382. Relevant email addresses:
  3383.  ztc-list@zortech.com          General requests and discussion
  3384.  ztc-list-request@zortech.com  Requests to be added to ztc-list
  3385.  ztc-bugs@zortech.com          For _short_ bug reports
  3386.  
  3387. ==============================================================================
  3388.  
  3389. Q137: Why does my DOS C++ program says `Sorry: floating point code not linked'?
  3390. A: The compiler attempts to save space in the executable by not including the
  3391. float-to-string format conversion routines unless they are necessary, and
  3392. sometimes does not recognize some code that does require it. Taking the address
  3393. of a float in an argument list of a function call seems to trigger it, but
  3394. taking the address of a float element of a struct may fool the compiler.  A
  3395. "%f" in a printf/scanf format string doesn't trigger it because format strings
  3396. aren't examined at compile-time.
  3397.  
  3398. You can fix it by (1) using <iostream.h> instead of <stdio.h>, or (2) by
  3399. including the following function definition somewhere in your compilation (but
  3400. don't call it!):
  3401.  static void dummyfloat(float *x) { float y; dummyfloat(&y); }
  3402.  
  3403. See question on stream I/O for more reasons to use <iostream.h> vs <stdio.h>.
  3404.  
  3405. ==============================================================================
  3406.  
  3407. --
  3408. Marshall Cline
  3409. --
  3410. Marshall P. Cline, Ph.D. / Paradigm Shift, Inc / One Park St/Norwood, NY 13668
  3411. cline@parashift.com / 315-353-6100 / FAX: 315-353-6110
  3412.  
  3413.  
  3414.  
  3415.  
  3416.  
  3417.  
  3418.  
  3419.  
  3420.  
  3421.  
  3422.  
  3423.  
  3424.  
  3425.  
  3426.  
  3427.  
  3428.  
  3429.  
  3430.  
  3431.  
  3432.  
  3433.  
  3434.  
  3435.  
  3436.  
  3437.  
  3438.  
  3439.  
  3440.  
  3441.  
  3442.  
  3443.  
  3444.  
  3445.  
  3446.  
  3447.  
  3448.  
  3449.  
  3450.  
  3451.  
  3452.  
  3453.  
  3454.  
  3455.  
  3456.  
  3457.  
  3458.  
  3459.  
  3460.  
  3461.  
  3462.  
  3463.  
  3464.  
  3465.  
  3466.  
  3467.  
  3468.  
  3469.  
  3470.  
  3471.  
  3472.  
  3473.  
  3474.  
  3475.  
  3476.  
  3477.  
  3478.  
  3479.  
  3480.  
  3481.