
From csus.edu!csusac!charnel.ecst.csuchico.edu!psgrain!usenet.eel.ufl.edu!news.mathworks.com!news.kei.com!ub!library.erc.clarkson.edu!sun.soe.clarkson.edu!cline Sun Oct 15 13:08:06 1995
From: cline@sun.soe.clarkson.edu (Marshall Cline)
Newsgroups: comp.lang.c++
Subject: C++ FAQ: posting #1/4
Followup-To: comp.lang.c++
Date: 2 Oct 1995 21:31:49 GMT
Organization: Paradigm Shift, Inc (OO consulting/training)
Lines: 1210
Sender: cline@sun.soe.clarkson.edu
Distribution: world
Expires: +1 month
Message-ID: <44plo5$int@library.erc.clarkson.edu>
Reply-To: cline@parashift.com (Marshall Cline)
NNTP-Posting-Host: sun.soe.clarkson.edu
Summary: Please read this before posting to comp.lang.c++
Status: O

comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
Copyright (C) 1991-95 Marshall P. Cline, Ph.D.
Posting 1 of 4.

UPDATED 10/95:
 * No significant updates were made this month.
 * Still no word on when anonymous ftp will be back up on sun.soe.clarkson.edu.

UPDATED 9/95:
 * Added FAQ 41 on using a variable for the first dimension of a
   multi-dimensional array
 * Added FAQ 123 on the code from "Numerical Recipes"
 * Added section 20 ("Libraries").  It's still pretty sparse, but it's a start
 * Fixed a bug in FAQ 30 (there was no variable "i")
 * Added FAQ 124 on dynamic linking to avoid bloated executables
 * Added FAQ 32 on trying to "reopen" cin and cout in binary mode
 * Added the access info to get the ANSI/ISO Committee Draft via ftp (FAQ 7)

UPDATED 7/95:
 * Minor stuff (but not change in FTP access, below).

UPDATED 6/95:
 * Corrected the mailing address where the ANSI-C++ Draft can be ordered
 * Added a FAQ on floating point [Thanks to Phil Staite]
 * Added a FAQ on multidimensional arrays [Thanks to Doug Shapter]
 * Added a FAQ on interrupt service routines and ptrs to member functions
 * Reorganized the FAQ on allocating all objects of a certain class via 'new'

UPDATED 5/95:
 * Minor cosmetic changes

UPDATED 4/95:
 * Added a question on a common BC++ Windows issue
 * Fixed the ftp address for NIHCL
 * Added an explanation that "ARM" is short for "Annotated Reference Manual"

UPDATED 3/95:
 * Added a question on "delete this"
 * Added two questions on iostreams and eof
 * Fixed the entry on "c-mode" and "cc-mode" in Gnu emacs

UPDATED 1/95:
 * A Chinese version of this document has been produced; details below.

UPDATED 12/94:
 * Added a FAQ on STL (currently #115).
 * Added a FAQ on name mangling (currently #119).
 * Fixed typo in FAQ that compared composition with private inheritance.
 * Corrected some spelling errors.

UPDATED 11/94:
 * Added differentiator between "FAQ book" and "FAQ posting"
 * Other cosmetic changes

UPDATED 10/94:
 * Fixed a few typos

UPDATED 9/94:
 * Minor cosmetic changes

UPDATED 8/94:
 * Made it up-to-date with respect to "typeid" and "dynamic_cast".
 * Made it up-to-date with respect to "mutable" and "const_cast".
 * Rewrote most of the answers to provide general cleanup.
 * The quotation marks are now "..." rather than `...' or ``...''
 * Sample code lines start with a tab; no other lines starts with a tab.
 * Everything was edited; minor modifications everywhere.

==============================================================================
SECTION 1: Introduction and table of contents
==============================================================================

	DOCUMENT:	Frequently-Asked-Questions for comp.lang.c++
	REVISION:	Oct 2, 1995

	POSTING!=BOOK:	This C++ FAQ posting is NOT the same as the "FAQ book".
			The "FAQ book" ("C++ FAQs", Addison-Wesley, 1995) is
			5x larger than this posting.  See below for more.

	AUTHOR:		Marshall P. Cline, Ph.D.
			Paradigm Shift, Inc.
			One Park St. / Norwood, NY  13668
			voice: 315-353-6100
			fax:   315-353-6110
			email: cline@parashift.com

	COPYRIGHT:	Copyright (C), 1991-94 Marshall P. Cline, Ph.D.
			Permission to copy all or part of this work is granted,
			provided that the copies are not made or distributed
			for resale (except a nominal copy fee may be charged),
			and provided that the AUTHOR, COPYRIGHT, & NO WARRANTY
			sections are retained verbatim and are displayed
			conspicuously.  If anyone needs other permissions that
			aren't covered by the above, please contact the author.

	NO WARRANTY:	THIS WORK IS PROVIDED ON AN "AS IS" BASIS.  THE AUTHOR
			PROVIDES NO WARRANTY WHATSOEVER, EITHER EXPRESS OR
			IMPLIED, REGARDING THE WORK, INCLUDING WARRANTIES WITH
			RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY
			PARTICULAR PURPOSE.

	AVAILABILITY:	The old FTP site is no longer available.
			I am searching for an alternate FTP site.
			Watch this space for an FTP site next month.
			Please DON'T send suggestions for ftp sites
				(my mailbox to overfloweth :-).

	SEE ALSO:	comp.lang.c FAQ appears every month in that newsgroup,
			and is maintained by Steve Summit (scs@eskimo.com).

	CHINESE TRANSLATION: A Chinese translation, encoded in "Big5" code
			(a 16-bit Chinese code used mostly in Taiwan)
			is now available for anonymous ftp at:
	     ftp://ftp.cis.nctu.edu.tw/Documents/News/comp.lang.c++/c-cppfaq.*

==============================================================================
SUBSECTION 1A: "FAQ book" versus "FAQ posting"
==============================================================================

Now that Addison-Wesley has published "C++ FAQs" by Cline and Lomow (1995,
ISBN 0-201-58958-3), many people have asked about the relationship between the
book and this posting.  Some who haven't seen the book have wondered whether
the posting was equivalent to the book.  This section answers these questions.

The "FAQ book" (at bookstores starting Oct. 94) is loosely based on the same
concepts as this posting.  However the FAQ book is approx five (5) times
bigger than this posting, including thousands of cross references, external
references, and index terms, as well as many programming examples.

==============================================================================
SUBSECTION 1B: Table of Contents
==============================================================================

========== POSTING #1 ==========

SECTION 1: Introduction and table of contents
SUBSECTION 1A: "FAQ book" versus "FAQ posting"
SUBSECTION 1B: Table of Contents
SUBSECTION 1C: Nomenclature and Common Abbreviations

SECTION 2: How should I post something? (READ BEFORE POSTING)
Q1: Which newsgroup should I post my questions?
Q2: How do I post a question about code that doesn't work correctly?

SECTION 3: Environmental/managerial issues
Q3: What is OOP?  What is C++?
Q4: What are some advantages of C++?
Q5: Who uses C++?
Q6: Are there any C++ standardization efforts underway?
Q7: Where can I get a copy of the latest ANSI-C++ draft standard?
Q8: Is C++ backward compatible with ANSI-C?
Q9: How long does it take to learn C++?

SECTION 4: Basics of the paradigm
Q10: What is a class?
Q11: What is an object?
Q12: What is a reference?
Q13: What happens if you assign to a reference?
Q14: How can you reseat a reference to make it refer to a different object?
Q15: When should I use references, and when should I use pointers?
Q16: What's the deal with inline functions?

SECTION 5: Constructors and destructors
Q17: What's the deal with constructors?
Q18: How can I make a constructor call another constructor as a primitive?
Q19: What's the deal with destructors?

SECTION 6: Operator overloading
Q20: What's the deal with operator overloading?
Q21: What operators can/cannot be overloaded?
Q22: Can I create a "**" operator for "to-the-power-of" operations?

SECTION 7: Friends
Q23: What is a "friend"?
Q24: Do "friends" violate encapsulation?
Q25: What are some advantages/disadvantages of using friend functions?
Q26: What does it mean that "friendship is neither inherited nor transitive"?
Q27: Should my class declare a member function or a friend function?

SECTION 8: Input/output via <iostream.h> and <stdio.h>
Q28: How can I provide printing for a "class Fred"?
Q29: Why should I use <iostream.h> instead of the traditional <stdio.h>?
Q30: Why does my input seem to process past the end of file?
Q31: Why is my program ignoring my input request after the first iteration?
Q32: How can I "reopen" cin and cout in binary mode under DOS and/or OS/2?

========== POSTING #2 ==========

SECTION 9: Freestore management
Q33: Does "delete p" delete the pointer "p", or the pointed-to-data, "*p"?
Q34: Can I "free()" pointers allocated with "new"?  Can I "delete" pointers
   alloc'd with "malloc()"?
Q35: Why should I use "new" instead of trustworthy old malloc()?
Q36: Why doesn't C++ have a "realloc()" along with "new" and "delete"?
Q37: How do I allocate / unallocate an array of things?
Q38: What if I forget the "[]" when "delete"ing array allocated via "new
   Fred[n]"?
Q39: Is it legal (and moral) for a member function to say "delete this"?
Q40: How do I allocate multidimensional arrays using new?
Q41: Does C++ have arrays whose length can be specified at run-time?
Q42: How can I ensure objects of my class are always created via "new" rather
   than as locals or global/static objects?

SECTION 10: Debugging and error handling
Q43: How can I handle a constructor that fails?
Q44: How should I handle resources if my constructors may throw exceptions?

SECTION 11: Const correctness
Q45: What is "const correctness"?
Q46: Should I try to get things const correct "sooner" or "later"?
Q47: What is a "const member function"?
Q48: What do I do if I want to update an "invisible" data member inside a
   "const" member function?
Q49: Does "const_cast" mean lost optimization opportunities?

SECTION 12: Inheritance
Q50: Is inheritance important to C++?
Q51: When would I use inheritance?
Q52: How do you express inheritance in C++?
Q53: Is it ok to convert a pointer from a derived class to its base class?
Q54: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
Q55: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are
   bad?
SUBSECTION 12A: Inheritance -- Virtual functions
Q56: What is a "virtual member function"?
Q57: How can C++ achieve dynamic binding yet also static typing?
Q58: Should a derived class replace ("override") a non-virtual fn from a base
   class?
Q59: What's the meaning of, "Warning: Derived::f(int) hides Base::f(float)"?
SUBSECTION 12B: Inheritance -- Conformance
Q60: Should I hide public member fns inherited from my base class?
Q61: Is a "Circle" a kind-of an "Ellipse"?
Q62: Are there other options to the "Circle is/isnot kind-of Ellipse"
   dilemma?
SUBSECTION 12C: Inheritance -- Access rules
Q63: Why can't my derived class access "private" things from my base class?
Q64: What's the difference between "public:", "private:", and "protected:"?
Q65: How can I protect subclasses from breaking when I change internal parts?
SUBSECTION 12D: Inheritance -- Constructors and destructors
Q66: When my base class's constructor calls a virtual function, why doesn't my
   derived class's override of that virtual function get invoked?
Q67: Does a derived class destructor need to explicitly call the base
   destructor?
SUBSECTION 12E: Inheritance -- Private and protected inheritance
Q68: How do you express "private inheritance"?
Q69: How are "private inheritance" and "composition" similar?
Q70: Which should I prefer: composition or private inheritance?
Q71: Should I pointer-cast from a "privately" derived class to its base
   class?
Q72: How is protected inheritance related to private inheritance?
Q73: What are the access rules with "private" and "protected" inheritance?

SECTION 13: Abstraction
Q74: What's the big deal of separating interface from implementation?
Q75: How do I separate interface from implementation in C++ (like Modula-2)?
Q76: What is an ABC ("abstract base class")?
Q77: What is a "pure virtual" member function?
Q78: How can I provide printing for an entire hierarchy of classes?
Q79: When should my destructor be virtual?
Q80: What is a "virtual constructor"?

========== POSTING #3 ==========

SECTION 14: Style guidelines
Q81: What are some good C++ coding standards?
Q82: Are coding standards necessary?  Are they sufficient?
Q83: Should our organization determine coding standards from our C
   experience?
Q84: Should I declare locals in the middle of a fn or at the top?
Q85: What source-file-name convention is best? "foo.C"? "foo.cc"? "foo.cpp"?
Q86: What header-file-name convention is best? "foo.H"? "foo.hh"? "foo.hpp"?
Q87: Are there any lint-like guidelines for C++?

SECTION 15: Keys for Smalltalk programmers to learn C++
Q88: Why does C++'s FAQ have a section on Smalltalk? Is this
   Smalltalk-bashing?
Q89: What's the difference between C++ and Smalltalk?
Q90: What is "static typing", and how is it similar/dissimilar to Smalltalk?
Q91: Which is a better fit for C++: "static typing" or "dynamic typing"?
Q92: How can you tell if you have a dynamically typed C++ class library?
Q93: How do you use inheritance in C++, and is that different from Smalltalk?
Q94: What are the practical consequences of diffs in Smalltalk/C++
   inheritance?
Q95: Do you need to learn a "pure" OOPL before you learn C++?
Q96: What is the NIHCL?  Where can I get it?

SECTION 16: Reference and value semantics
Q97: What is value and/or reference semantics, and which is best in C++?
Q98: What is "virtual data," and how-can / why-would I use it in C++?
Q99: What's the difference between virtual data and dynamic data?
Q100: Should I normally use pointers to freestore allocated objects for my
   data members, or should I use "composition"?
Q101: What are relative costs of the 3 performance hits associated with
   allocating member objects from the freestore?
Q102: Are "inline virtual" member fns ever actually "inlined"?
Q103: Sounds like I should never use reference semantics, right?
Q104: Does the poor performance of ref semantics mean I should pass-by-value?

========== POSTING #4 ==========

SECTION 17: Linkage-to/relationship-with C
Q105: How can I call a C function "f(int,char,float)" from C++ code?
Q106: How can I create a C++ function "f(int,char,float)" that is callable by
   my C code?
Q107: Why's the linker giving errors for C/C++ fns being called from C++/C
   fns?
Q108: How can I pass an object of a C++ class to/from a C function?
Q109: Can my C function access data in an object of a C++ class?
Q110: Why do I feel like I'm "further from the machine" in C++ as opposed to
   C?

SECTION 18: Pointers to member functions
Q111: Is the type of "ptr-to-member-fn" different from "ptr-to-fn"?
Q112: How do I pass a ptr to member fn to a signal handler, X event callback,
   etc?
Q113: Why do I keep getting compile errors (type mismatch) when I try to use a
   member function as an interrupt service routine? 
Q114: Why am I having trouble taking the address of a C++ function?
Q115: How do I declare an array of pointers to member functions?

SECTION 19: Container classes and templates
Q116: How can I insert/access/change elements from a linked
   list/hashtable/etc?
Q117: What's the idea behind "templates"?
Q118: What's the syntax / semantics for a "function template"?
Q119: What's the syntax / semantics for a "class template"?
Q120: What is a "parameterized type"?
Q121: What is "genericity"?

SECTION 20: Libraries
Q122: Where can I get a copy of "STL"?
Q123: Where can I ftp the code that accompanies "Numerical Recipes"?
Q124: Why is my executable so large?

SECTION 21: Nuances of particular implementations
Q125: GNU C++ (g++) produces big executables for tiny programs; Why?
Q126: Is there a yacc-able C++ grammar?
Q127: What is C++ 1.2?  2.0?  2.1?  3.0?
Q128: If name mangling was standardized, could I link code compiled with
   compilers from different compiler vendors?

SECTION 22: Miscellaneous technical and environmental issues
SUBSECTION 22A: Miscellaneous technical issues:
Q129: Why are classes with static data members getting linker errors?
Q130: What's the difference between the keywords struct and class?
Q131: Why can't I overload a function by its return type?
Q132: What is "persistence"?  What is a "persistent object"?
Q133: Why is floating point so inaccurate?  Why doesn't this print 0.43?
SUBSECTION 22B: Miscellaneous environmental issues:
Q134: Is there a TeX or LaTeX macro that fixes the spacing on "C++"?
Q135: Where can I access C++2LaTeX, a LaTeX pretty printer for C++ source?
Q136: Where can I access "tgrind," a pretty printer for C++/C/etc source?
Q137: Is there a C++-mode for GNU emacs?  If so, where can I get it?
Q138: Where can I get OS-specific FAQs answered (e.g.,BC++,DOS,Windows,etc)?
Q139: Why does my DOS C++ program says "Sorry: floating point code not
   linked"?
Q140: Why does my BC++ Windows app crash when I'm not running the BC45 IDE?
==============================================================================
SUBSECTION 1C: Nomenclature and Common Abbreviations
==============================================================================

Here are a few of the abbreviations/etc used in this article:

    term	meaning
    ====	===========
    fn		function
    fns		functions
    param	parameter
    ptr		pointer, a C/C++ construct declared by:  int * p;
    ref		reference, a C++ construct declared by:  int & r;
    OO		object-oriented
    OOP		object-oriented programming
    OOPL	object-oriented programming language
    method	an alternate term for "member function"

==============================================================================
SECTION 2: How should I post something? (READ BEFORE POSTING)
==============================================================================

Q1: Which newsgroup should I post my questions?

Comp.lang.c++ is the best place to discuss the C++ language itself (e.g.,
C++ code design, syntax, style).  Other newsgroups exist for discussion of
topics which are specific to a particular system (e.g., MS Windows or UNIX)
or topics which are not directly related to the C++ language (e.g., how to
use your compiler).  Here's a list of some very active newsgroups and
excerpts from their Frequently Asked Questions lists.  These excerpts
should give you an idea of the type of topics frequently discussed there.

  comp.os.ms-windows.programmer.tools
     This group is intended for discussions about the selection and use of
     tools for Windows software development.
  comp.os.ms-windows.programmer.misc
     This group is for all other discussions about Windows software
     development.
  [There's one FAQ list for all the comp.os.ms-windows.programmer.* groups]
     FAQ 5.7.1.  Accessing C++ classes in a DLL
     FAQ 6.1.1.  A dialog as an MDI child window [with OWL]
     FAQ 6.2.1.  Disabled menu choices become enabled [with MFC]
     FAQ 8.1.5.  Using STRICT with windows.h
     FAQ 10.  A programmer's bibliography

  comp.os.msdos.programmer
     Much of the traffic is about language products (chiefly from Borland
     and Microsoft).
     FAQ 301. How can I read a character without [waiting for] the Enter key?
     FAQ 412. How can I read, create, change, or delete the volume label?
     FAQ 504. How do I configure a COM port and use it to transmit data?
     FAQ 602. How can a C program send control codes to my printer?
     FAQ 606. How can I find the Microsoft mouse position and button status?
     FAQ 707. How can I write a TSR (terminate-stay-resident) utility?
     FAQ B0. How can I contact [Borland, Microsoft]?
     [note: this FAQ is not available at rtfm.mit.edu; it is at Simtel
            (e.g., oak.oakland.edu) in /pub/msdos/info/faqp*.zip and Garbo
            (garbo.uwasa.fi) in /pc/doc-net/faqp*.zip]
  comp.os.msdos.programmer.turbovision [Borland's character-mode framework]

  comp.unix.programmer
     FAQ 4.5)  How do I use popen() to open a process for reading AND writing?
     FAQ 4.6)  How do I sleep() in a C program for less than one second?

  comp.unix.solaris (covers SunOS 4.x and Solaris)
     FAQ 4)  Signal Primer
     FAQ 5)  Waiting for Children to Exit

  gnu.g++.help
     FAQ: Where can I find a demangler?
     FAQ: Getting gcc/g++ binaries for Solaris 2.x
     FAQ: What documentation exists for g++ 2.x?
  gnu.g++.bug [bug reports for g++ -- see the g++ docs]

  comp.lang.c
     FAQ 1.10: I'm confused.  NULL is guaranteed to be 0, but the null
               pointer is not?
     FAQ 2.3:  So what is meant by the "equivalence of pointers and
               arrays" in C?
     FAQ 4.2:  [Why doesn't "printf("%d\n," i++ * i++);" work?]
     FAQ 7.1:  How can I write a function that takes a variable number
               of arguments? [stdarg.h or varargs.h]
     FAQ 10.4: How do I declare an array of pointers to functions returning
               pointers to functions returning pointers to characters?

Also check out the newsgroups comp.graphics, comp.sources.wanted,
comp.programming, and comp.object (its FAQ is an excellent introduction and
overview of OOP terms and concepts).  Remember that comp.std.c++ is for
discussion DIRECTLY related to the evolving ANSI/ISO C++ Standard (see more
below). 

There's rarely a need to crosspost a question to one of the above
newsgroups and comp.lang.c++ (readers in the system-specific newsgroups
aren't programming in machine language, ya know).  It's bad netiquette to
crosspost widely because your problem is "really important."  If you don't
get an answer in the "right" newsgroup and feel you must post here, at
least consider redirecting followups back to the appropriate newsgroup.

Before posting a question to any newsgroup you should read it's FAQ list.
An answer to your question is likely to be there, saving you the time of
posting and saving thousands of other people around the world the time of
reading your question.  People answering a FAQ are likely to be annoyed for
having to answer it for the umpteenth time, or they're likely to be giving
you a wrong or incomplete answer since they haven't read the FAQ either.

Frequently Asked Questions lists are available 24-hours a day via anonymous
ftp (rtfm.mit.edu in /pub/usenet/comp.what.ever) or e-mail server (send a
message with the line "help" to mail-server@rtfm.mit.edu).  See the article
"Introduction to the *.answers newsgroups" in the newsgroup news.answers or
news.announce.newusers (which contains many other must-read articles) for
more information.

==============================================================================

Q2: How do I post a question about code that doesn't work correctly?

Here's some guidelines you should follow that will help people reading
comp.lang.c++ help you with an answer to your programming problem.

1. Please read the previous FAQ to make sure that your question is about the
   C++ language and not a question about programming on your system (e.g.,
   graphics, printers, devices, etc.) or using your compilation
   environment (e.g., "the IDE crashes when I...," "how do you turn off
   warnings about...," "how do I tell it to link my libraries").  If you
   want to know why your virtual CmOk() function isn't being called in
   your OWL program, your question is probably more appropriate in the
   Windows programming newsgroup.  If you can write a small stand-alone
   program which exhibits the same undesired compiler error or behavior
   as your OWL program, by all means post here in comp.lang.c++ since C++
   programmers using other systems could be of help.

2. Be descriptive in the subject line.  "C++ problem" leaves a lot to the
   imagination.  "Problem new'ing a multi-dimensional array" is good.
   Refrain from exclamation points, cries for HELPPP, and the once funny
   "SEX SEX SEX."  If you think the problem is specific to your compiler,
   you might want to mention the compiler/version in the subject line.

3. Post code that is complete and compilable.  It's extremely difficult
   to debug or reconstruct a program from a human language description.
   By "complete code" I mean that any types and functions used are
   declared, headers are #include'd, etc.  Please strip the code down to
   the bare essentials.  We don't need a program that does something
   useful at run-time, or even links.  We just need to be able to
   reproduce the undesired compiler error (possibly on a different
   compiler).  By "compilable code" I mean that it doesn't contain a
   bunch of uncommented ellipses or line numbers at the beginning of each
   line:

	14:	#include <iostream.h>
	15:	class Foo { ... };  // this is annoying

   Try to organize the code into one linear program instead of making us cut
   out and create header files.  Be very careful if you are typing the code
   into your article -- it's often difficult to tell whether something is a
   typo or the real cause of the problem.  Try using your editor's
   cut&paste or "insert file" feature instead.

4. Mention what compiler, compiler version, and system you're using.  I
   know, I just said that system-specific questions should go to a
   system-specific newsgroup, but compiler information is often very
   useful in diagnosing the problem: ("yeah, I remember Acme 1.2 having
   lots of problems in this area").  It also warns other users of that
   compiler about possible bugs.

5. Show us the exact compiler and linker options and libraries you used
   when building your program.

6. List the exact error message and where the error was given.  "Virtual
   functions don't work" doesn't tell us whether its a compile-, link-, or
   run-time problem.  If the problem is at run-time, give a good
   description of the behavior and any relevant information about your
   system setup.

7. Include a working e-mail address in your signature.  If the address in
   given your article's "From:" line is not correct, please notify your
   system administrator.  Until it is fixed, add a "Reply-To:" line to
   your headers that uses your correct e-mail address.

8. Please read the rest of this FAQ -- chances are your problem, or a
   closely related problem, is discussed here.  Thank you and I hope these
   suggestions help you find a solution to your problem.

==============================================================================
SECTION 3: Environmental/managerial issues
==============================================================================

Q3: What is OOP?  What is C++?

OO programming techniques are the best way we know of to develop large, complex
software applications and systems.

C++ is an OO programming language.  C++ can be used both as an OOPL and simply
"as a better C."  However if you use it "as a better C," don't expect to get
the benefits of object-oriented programming.

OO hype: the software industry is "failing" to meet demands for large, complex
software systems.  But this "failure" is actually due to our SUCCESSES: our
successes have propelled users to ask for more.  Unfortunately we created a
market hunger that the "structured" analysis, design and programming techniques
couldn't satisfy.  This required us to create a better paradigm.

==============================================================================

Q4: What are some advantages of C++?

GROWTH OF C++: C++ is by far the most popular OOPL.  The number of C++ users is
doubling every 7.5 to 9 months.  Knowing C++ is a good resume-stuffer (but use
it as an OOPL rather than just as a better C).

ENCAPSULATION: Hiding our data structures allows us to change one chunk of a
system without breaking other chunks.  We provide our software chunks (we call
them "classes") with safe interfaces.  Users of a chunk use its interface only.
The relatively volatile "implementation" of this interface is "encapsulated"
("put into a capsule") to prevent users from becoming reliant on its temporary
decisions.  In simple C, this was done by making a module's data "static", thus
preventing another module from accessing our module's bits.

MULTIPLE INSTANCES: The typical C solution to encapsulation (see above) doesn't
support multiple instances of the data (it's hard to make multiple instances of
a module's "static" data).  If we needed multiple instances in C, we used a
"struct" (but this doesn't support "encapsulation").  In C++, we can have both
multiple instances and encapsulation via a "class": the "public" part of a
class contains the class's interface (normally these are a special kind of
function called a "member function"), and the "private" part of a class
contains the class's implementation (typically these are where the bits live).

INLINE FUNCTION CALLS: In straight C, you can achieve "encapsulated structs" by
putting a "void*" in a struct (the access functions use pointer casts).  This
forfeits type safety, and also imposes a function call to access even trivial
fields of the struct (if you allowed direct access to the struct's fields, the
underlying data structure would be difficult to change since too many chunks
would RELY on it being the "old" way).  Function call overhead is small, but
can add up.  C++ classes allow function calls to be expanded "inline," so you
have: the 1) safety of encapsulation, 2) convenience of multiple instances, 3)
speed of direct access.  Furthermore the parameter types of these inline
functions are checked by the compiler, an improvement over C's #define macros.

OVERLOADING OPERATORS: C++ lets you overload the standard operators on a class,
which lets users exploit their intuition (e.g., "myString + yourString" might
do string concatenation, "myDate++" might increment the date, "z1 * z2" might
multiply complex numbers z1 and z2, "a[i]" might access the "i"th element of
the "linked list" called "a", etc.  You can even have "smart pointers" that
could "point" to a disk record or wherever ("x = *p" could "dereference" such a
pointer, which could seek to the location on disk where p "points" and return
its value").  This allows users to program in the language of the problem
domain rather than in the language of the machine.

INHERITANCE: We still have just scratched the surface.  In fact, we haven't
even gotten to the "object-oriented" part yet!  Suppose you have a Stack data
type with operations push, pop, etc.  Suppose you want an InvertableStack,
which is "just like" Stack except it also has an "invert" operation.  In "C"
style, you'd have to either (1) modify the existing Stack module (trouble if
"Stack" is being used by others), or (2) copy Stack into another file and text
edit that file (results in lots of code duplication, another chance to break
something tricky in the Stack part of InvertableStack, and especially twice as
much code to maintain).  C++ provides a much cleaner solution: inheritance.
You say "InvertableStack inherits everything from Stack, and InvertableStack
adds the invert operation."  Done.  Stack itself remains "closed" (untouched,
unmodified), and InvertableStack doesn't duplicate the code for push/pop/etc.

POLYMORPHISM AND DYNAMIC BINDING: The real power of OOP isn't just inheritance,
but is the ability to pass an InvertableStack around as if it actually were a
Stack.  This is "safe" since (in C++ at least) the is-a relation follows public
inheritance (i.e., a InvertableStack is-a Stack that can also invert itself).
Polymorphism and dynamic binding are easiest to understand from an example, so
here's a "classic": a graphical draw package might deal with Circles, Squares,
Rectangles, general Polygons, and Lines.  All of these are Shapes.  Most of the
draw package's functions need a "Shape" parameter (as opposed to some
particular kind of shape like Square).  E.g., if a Shape is picked by a mouse,
the Shape might get dragged across the screen and placed into a new location.
Polymorphism and dynamic binding allow the code to work correctly even if the
compiler knows only that the parameter is a "Shape" without knowing the exact
kind of Shape it is.  Furthermore suppose the "pick_and_drag(Shape*) function
just mentioned was compiled on Tuesday, and on Wednesday you decide to add the
Hexagon shape.  Strange as it sounds, pick_and_drag() will still work with
Hexagons, even though the Hexagon didn't even exist when pick_and_drag() was
compiled!!  (it's not really "amazing" once you understand how the C++ compiler
does it -- but it's still very convenient!)

==============================================================================

Q5: Who uses C++?

Lots and lots of companies and government sites.  Lots.

Statistically, 5 people became new C++ programmers while you read the words of
the previous FAQ.

==============================================================================

Q6: Are there any C++ standardization efforts underway?

Yes; ANSI (American) and ISO (International) groups are working closely with
each other.  The ANSI-C++ committee is called "X3J16".  The ISO C++ standards
group is called "WG21".  The major players in the ANSI/ISO C++ standards
process includes just about everyone:

AT&T, IBM, DEC, HP, Sun, MS, Borland, Zortech, Apple, OSF, etc ad nauseum.
About 70 people attend each meeting.  People come from USA, UK, Japan, Germany,
Sweden, Denmark, France, ... (all have "local" committees sending official
representatives and conducting "local" meetings).

==============================================================================

Q7: Where can I get a copy of the latest ANSI-C++ draft standard?

The ISO Committee Draft for C++ and the ANSI C++ Draft (the document that is
going out for public review) is available from:
	http://www.cygnus.com/~mrs/wp-draft

You can also get Postscript and Adobe Acrobat versions from:
	ftp://research.att.com/dist/stdc++/WP

You can get HTML and ASCII versions:
	ftp://ftp.cygnus.com/pub/g++

You can also get a paper copy from:
	X3 Secretariat
	1250 Eye Street NW
	Suite 200
	Washington, DC  20005
	202-626-5738

You can also order via email:
	lbarra@itic.nw.dc.us (Lynn Barra)

Ask for the latest version of "Draft Proposed American National Standard for
Information Systems -- Programming Language C++" which is document number
CD14882.  It is typically shipped 2-day FedEx (within the continental US), so
people usually get it quickly.

==============================================================================

Q8: Is C++ backward compatible with ANSI-C?

Almost.

C++ is as close as possible to compatible with C, but no closer.  In practice,
the major difference is that C++ requires prototypes, and that "f()" declares a
function that takes no parameters (in C, "f()" is the same as "f(...)").  There
are some very subtle differences as well, like sizeof('x') is equal to
sizeof(char) in C++ but is equal to sizeof(int) in C.  Also, C++ puts structure
"tags" in the same namespace as other names, whereas C requires an explicit
"struct" (the "typedef struct Fred Fred" technique still works, but is
redundant in C++).

==============================================================================

Q9: How long does it take to learn C++?

Companies like Paradigm Shift, Inc. successfully teach standard industry "short
courses", where we compress a university semester course into one 40hr work
week.  However true mastery takes experience; there's no substitute for time.
Hands-on projects are essential, since they allow concepts to "gel."

It takes 6-12 months to become proficient in C++/OOP.  Less if the developers
have easy access to a "local" body of experts, more if there isn't a "good"
general purpose C++ class library available.  To become one of these experts
who can mentor others takes around 3 years.

Some people never make it.  You don't have a chance unless you are teachable
and have personal drive.  As a bare minimum on "teachability," you have to be
able to admit when you've are wrong.  As a bare minimum on "drive," you must
be willing to put in some extra hours (changing the way you think [a paradigm
shift] is a LOT more painful than learning a few new facts).

==============================================================================
SECTION 4: Basics of the paradigm
==============================================================================

Q10: What is a class?

The fundamental building block of OO software.

A class defines a data type, much like a struct would be in C.  In a computer
science sense, a type consists of both a set of states AND a set of operations
which transition between those states.  Thus "int" is a "type" because it has
both a set of states AND it has operations like "add two ints" or "int*int,"
etc.  In exactly the same way, a "class" provides a set of (usually public)
operations, and a set of (usually non-public) data bits representing the
abstract values that instances of the type can have.  From a C language
perspective, a class is a struct whose members default to "private".

Think of "int" as a class that has methods called "operator++", etc.

==============================================================================

Q11: What is an object?

A region of storage with associated semantics.

After the declaration "int i;" we say that "i is an object of type int."  In
C++/OOP, "object" usually means "an instance of a class."  Thus a class defines
the behavior of possibly many objects (instances).

==============================================================================

Q12: What is a reference?

An alias (an alternate name) for an object.

References are frequently used for pass-by-reference:

	void swap(int& i, int& j)
	{
	  int tmp = i;
	  i = j;
	  j = tmp;
	}

	main()
	{
	  int x, y;
	  //...
	  swap(x,y);
	}

Here "i" and "j" are aliases for main's "x" and "y" respectively.  In other
words, "i" IS "x" -- not a pointer to "x", nor a copy of "x", but "x" itself.
Anything you do to "i" gets done to "x", and vise versa.

Underneath it all, references are typically implemented by pointers.  The
effect is as if you used the C style pass-by-pointer, but the "&" is moved from
the caller into the callee, and you eliminate all the "*"s.

==============================================================================

Q13: What happens if you assign to a reference?

You change the referrent (the object to which the reference refers).

Remember: the reference IS the referrent, so changing the reference changes the
referrent (a reference is an "Lvalue" [something that can appear on the
"L"eft-hand-side of an assignment statement] for the referrent).

This insight can be pushed a bit farther by allowing references to be RETURNED.
This allows function calls on the left hand side of an assignment statement,
which is useful with operator overloading.

==============================================================================

Q14: How can you reseat a reference to make it refer to a different object?

No way.

Unlike a pointer, once a reference is bound to an object, it can NOT be
"reseated" to another object.  The reference itself isn't an object (it has no
address; taking the address of a reference gives you the address of the
referrent; remember: the reference IS its referrent).

You can't separate the reference from the referent.

==============================================================================

Q15: When should I use references, and when should I use pointers?

Use references when you can, and pointers when you have to.

References are usually preferred over ptrs whenever you don't need "reseating"
(see previous FAQ).  This usually means that references are most useful in a
class's public interface.  References typically appear on the skin of an
object, and pointers on the inside.

The exception to the above is where a function's parameter or return value
needs a "sentinel" reference.  This is usually best done by returning/taking a
pointer, and giving the NULL pointer this special significance (references
should always alias objects, not a dereferenced NULL ptr).

NOTE: Old line C programmers sometimes don't like references since they provide
reference semantics that isn't explicit in the caller's code.  After some C++
experience, however, one quickly realizes this is a form of information hiding,
which is an asset rather than a liability.  E.g., programmers should write code
in the language of the problem rather than the language of the machine.

==============================================================================

Q16: What's the deal with inline functions?

An inline function is a function whose code gets inserted into the caller's
code stream.  Like a macro, inline functions improve performance by avoiding
the overhead of the call itself and (especially!) by the compiler being able to
optimize THROUGH the call ("procedural integration").  Unlike macros, inline
functions avoid infamous macro errors by evaluating all arguments exactly once
(the "call" is semantically like a regular function call, only faster).  Also
unlike macros, argument types are checked, and necessary conversions are
performed correctly (macros are bad for your health; don't use them unless you
absolutely have to).

Beware that overuse of inline functions can cause code bloat, which can in
turn have a negative performance impact in paging environments.

They are declared by using the "inline" keyword when the function is defined:

	inline void f(int i, char c) { /*...*/ }

or by including the function definition itself within a class:

	class Fred {
	public:
	  void f(int i, char c) { /*...*/ }
	};

or by defining the member function as "inline" outside the class:

	class Fred {
	public:
	  void f(int i, char c);
	};

	inline void Fred::f(int i, char c) { /*...*/ }

==============================================================================
SECTION 5: Constructors and destructors
==============================================================================

Q17: What's the deal with constructors?

Constructors build objects from dust.

Constructors are like "init functions"; they turn a pile of arbitrary bits into
a living object.  Minimally they initialize internally used fields.  They may
also allocate resources (memory, files, semaphores, sockets, etc).

"ctor" is a typical abbreviation for constructor.

==============================================================================

Q18: How can I make a constructor call another constructor as a primitive?

No way.

Dragons be here: if you call another constructor, the compiler initializes a
temporary local object; it does NOT initialize "this" object.  You can combine
both constructors by using a default parameter, or you can share their common
code in a private "init()" member function.

==============================================================================

Q19: What's the deal with destructors?

A destructor gives an object its last rites.

Destructors are used to release any resources allocated by the object.  E.g., a
Lock class might lock a semaphore, and the destructor will release that
semaphore.  The most common example is when the constructor uses "new", and the
destructor uses "delete".

Destructors are a "prepare to die" method.  They are often abbreviated "dtor".

==============================================================================
SECTION 6: Operator overloading
==============================================================================

Q20: What's the deal with operator overloading?

It allows users of your classes to use intuitive syntax.

Operator overloading allows C/C++ operators to have user-defined meanings on
user-defined types (classes).  They're syntactic sugar for function calls:

	class Fred {
	public:
	  //...
	};

	#if 0
	  Fred add(Fred, Fred);		//without operator overloading
	  Fred mul(Fred, Fred);
	#else
	  Fred operator+(Fred, Fred);	//with operator overloading
	  Fred operator*(Fred, Fred);
	#endif

	Fred f(Fred a, Fred b, Fred c)
	{
	  #if 0
	    return add(add(mul(a,b), mul(b,c)), mul(c,a));  //without...
	  #else
	    return a*b + b*c + c*a;                         //with...
	  #endif
	}

==============================================================================

Q21: What operators can/cannot be overloaded?

Most can be overloaded. The only C operators that can't be are "." and "?:"
(and "sizeof," which is technically an operator).  C++ adds a few of its own
operators, most of which can be overloaded except "::" and ".*".

Here's an example of the subscript operator (it returns a reference).  First
withOUT operator overloading:

	class Array {
	public:
	  #if 0
	    int& elem(unsigned i) { if (i>99) error(); return data[i]; }
	  #else
	    int& operator[] (unsigned i) { if (i>99) error(); return data[i]; }
	  #endif
	private:
	  int data[100];
	};

	main()
	{
	  Array a;

	  #if 0
	    a.elem(10) = 42;
	    a.elem(12) += a.elem(13);
	  #else
	    a[10] = 42;
	    a[12] += a[13];
	  #endif
	}

==============================================================================

Q22: Can I create a "**" operator for "to-the-power-of" operations?

Nope.

The names of, precedence of, associativity of, and arity of operators is fixed
by the language.  There is no "**" operator in C++, so you cannot create one
for a class type.

If you're in doubt, consider that "x ** y" is the same as "x * (*y)" (in other
words, the compiler assumes "y" is a pointer).  Besides, operator overloading
is just syntactic sugar for function calls.  Although this particular syntactic
sugar can be very sweet, it doesn't add anything fundamental.  I suggest you
overload "pow(base,exponent)" (a double precision version is in <math.h>).

BTW: operator^ can work, except it has the wrong precedence and associativity.

==============================================================================
SECTION 7: Friends
==============================================================================

Q23: What is a "friend"?

Something to allow your class to grant access to another class or function.

Friends can be either functions or other classes.  A class grants access
privileges to its friends.  Normally a developer has political and technical
control over both the friends and methods of a class (else you need permission
from the owner of the other pieces when you want to update your class).

==============================================================================

Q24: Do "friends" violate encapsulation?

If they're used properly, they actually ENHANCE encapsulation.

You often need to split a class in half when the two halves will have different
numbers of instances or different lifetimes.  In these cases, the two halves
usually need direct access to each other (the two halves USED to be in the same
class, so you haven't INCREASED the number of methods that have direct access
to a data structure; you've simply MOVED some of those methods).  The safest
way to implement this is to make the two halves friends of each other.

If you use friends like just described, you'll keep private things private.  In
a naive effort to avoid using friendship in situations like the above, many
people actually destroy encapsulation by either using public data (grotesque!),
or by making the data accessible between the halves via public get/set methods.
Having a public get and set method for a private datum is ok only when the
private datum "makes sense" from outside the class (from a user's perspective).
In many cases, these get/set methods are almost as bad as public data: they
hide (only) the NAMES of the private data members, but they don't hide the
existence of the private data members.

Similarly, if you use friend functions as a syntactic variant of a class's
public access functions, they don't violate encapsulation any more than a
member function violates encapsulation.  In other words, a class's friends and
members ARE the encapsulation barrier, as defined by the class itself.

==============================================================================

Q25: What are some advantages/disadvantages of using friend functions?

They provide a degree of freedom in the interface design options.

Member fns and friend fns are equally privileged (100% vested).  The major
difference is that a friend function is called like "f(x)", while a member is
called like "x.f()".  Thus friend fns allow the class's designer to select
the syntax that is deemed most readable, which lowers maintenance costs.

The major disadvantage of friend functions is that they require an extra line
of code when you want dynamic binding.  To get the effect of a virtual friend,
the friend function should call a hidden (usually "protected:") virtual member
fn; e.g., "void f(Base& b) { b.do_f(); }".  Derived classes override the hidden
virtual member function ("void Derived::do_f()"), NOT the friend function.

==============================================================================

Q26: What does it mean that "friendship is neither inherited nor transitive"?

The privileges of friendship aren't inherited: derived classes of a friend
aren't necessarily friends (I may declare you as my friend, but that doesn't
mean I necessarily trust your kids).  If class "Base" declares "f()" to be a
friend, "f()" doesn't have any automatic special access rights to the extra
stuff declared in derived class, "Derived."

The privileges of friendship aren't transitive: friends of a friend class
aren't necessarily friends of the original class (a friend of a friend isn't
necessarily a friend).  E.g., if class "Fred" declares class "Wilma" as a
friend, and class "Wilma" declares "f()" as a friend, "f()" doesn't necessarily
have any special access rights to "Fred".

==============================================================================

Q27: Should my class declare a member function or a friend function?

Use a member when you can, and a friend when you have to.

Sometimes friends are syntactically better (e.g., in class "Fred", friend fns
allow the "Fred" param to be second, while members require it to be first).
Another good use of friend functions are the binary infix arithmetic operators
(e.g., "aComplex + aComplex" probably should be defined as a friend rather than
a member, since you want to allow "aFloat + aComplex" as well; recall members
don't allow promotion of the left hand arg, since that would change the class
of the object that is the recipient of the member function invocation).

In other cases, choose a member function over a friend function.

==============================================================================
SECTION 8: Input/output via <iostream.h> and <stdio.h>
==============================================================================

Q28: How can I provide printing for a "class Fred"?

Provide a friend operator<<:

	class Fred {
	public:
	  friend ostream& operator<< (ostream& o, const Fred& fred)
	    { return o << fred.i; }
	  //...
	private:
	  int i;    //just for illustration
	};

We use a friend rather than a member since the "Fred" parameter is second
rather than first.  Input is similar, but the signature is:

	istream& operator>> (istream& i, Fred& fred);
	                              // ^^^^^------- not "const Fred& fred"!

==============================================================================

Q29: Why should I use <iostream.h> instead of the traditional <stdio.h>?

Increase type safety, reduce errors, improve performance, allow extensibility,
and provide subclassability.

Printf is arguably not broken, and scanf is perhaps livable despite being error
prone, however both are limited with respect to what C++ I/O can do.  C++ I/O
(using "<<" and ">>") is, relative to C (using "printf()" and "scanf()"):

 * Type safe -- type of object being I/O'd is known statically by the compiler,
   rather than via dynamically tested via "%" fields.

 * Less error prone -- redundant info increases the chance of errors.  C++ I/O
   has no redundant "%" tokens to get right.

 * Faster -- printf is an "interpreter" of a tiny language whose constructs
   mainly include "%" fields; it uses these fields to select the right
   formatting primitive at run-time.  C++ I/O picks these routines statically
   based on actual types of the args.  This improves performance.

 * Extensible -- the C++ I/O mechanism allows new user-defined types to be
   added without breaking existing code (imagine the chaos if everyone was
   simultaneously adding new incompatible "%" fields to printf and scanf?!).

 * Subclassable -- ostream and istream (the C++ replacements for FILE*) are
   real classes, and hence subclassable.  This means you can have other user
   defined things that look and act like streams, yet that do whatever strange
   and wonderful things you want.  You automatically get to use the zillions of
   lines of I/O code written by users you don't even know, and they don't need
   to know about your "extended stream" class.

==============================================================================

Q30: Why does my input seem to process past the end of file?
Because the eof state is not set until after a read is attempted past the
end of file.  That is, reading the last byte from a file does not set the
eof state.

If your code looks like this:

	int i = 0;
	while (! cin.eof())  {
	  cin >> x;
	  ++i;
	  // work with x
	}

Then you have an off by one error with the count i.  
What you really need is:

	int i;
	while (cin >> x)  {
	  ++i;
	  // work with x
	}

==============================================================================

Q31: Why is my program ignoring my input request after the first iteration?
Because the numerical extractor leaves non digits behind in the input buffer.

If your code looks like this:

	char name[1000];
	int age;

	for (;;) {
	  cout << "Name: ";
	  cin >> name;
	  cout << "Age: ";
	  cin >> age;
	}

What you really want is:

	for (;;) {
	  cout << "Name: ";
	  cin >> name;
	  cout << "Age: ";
	  cin >> age;
	  cin.ignore(INT_MAX, '\n');
	}

==============================================================================

Q32: How can I "reopen" cin and cout in binary mode under DOS and/or OS/2?

Here's the typical scenario that leads to this question: Someone wants to do
binary I/O using cin and cout, but their operating system (such as DOS or
OS/2) insists on doing translations on carriagereturn-linefeed pairs.

Here's the answer: The predefined streams cin, cout, cerr are assumed to be
text streams, and there is no standard way to cause them to be opened in
binary mode.  Closing the streams and attempting to reopen them in binary mode
might have unexpected or undesirable results.

On systems where it makes a difference, the implementation might provide a way
to make them binary streams, but you would have to check the manuals to find
out.

--
Paradigm Shift, Inc. / P.O. Box 5108 / Potsdam, NY  13676
Voice: 315-353-6100 / FAX: 315-353-6110

From csus.edu!csusac!zimmer!waldorf.csc.calpoly.edu!charnel.ecst.csuchico.edu!psgrain!usenet.eel.ufl.edu!news.mathworks.com!news.kei.com!ub!library.erc.clarkson.edu!sun.soe.clarkson.edu!cline Sun Oct 15 13:08:07 1995
From: cline@sun.soe.clarkson.edu (Marshall Cline)
Newsgroups: comp.lang.c++
Subject: C++ FAQ: posting #2/4
Followup-To: comp.lang.c++
Date: 2 Oct 1995 21:32:03 GMT
Organization: Paradigm Shift, Inc (OO consulting/training)
Lines: 954
Sender: cline@sun.soe.clarkson.edu
Distribution: world
Expires: +1 month
Message-ID: <44ploj$kg0@library.erc.clarkson.edu>
Reply-To: cline@parashift.com (Marshall Cline)
NNTP-Posting-Host: sun.soe.clarkson.edu
Summary: Please read this before posting to comp.lang.c++
Status: O

comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
Copyright (C) 1991-95 Marshall P. Cline, Ph.D.
Posting 2 of 4.
Posting #1 explains copying permissions, (no)warranty, table-of-contents, etc

==============================================================================
SECTION 9: Freestore management
==============================================================================

Q33: Does "delete p" delete the pointer "p", or the pointed-to-data, "*p"?

The pointed-to-data.

"delete" really means "delete the thing pointed to by."  The same abuse of
English occurs when "free"ing the memory pointed to by a ptr in C ("free(p)"
really means "free_the_stuff_pointed_to_by(p)").

==============================================================================

Q34: Can I "free()" pointers allocated with "new"?  Can I "delete" pointers
   alloc'd with "malloc()"?

No.

It is perfectly legal, moral, and wholesome to use malloc/free and new/delete
in the same program, but it is illegal, immoral, and despicable to free a
pointer allocated via new, or to delete a pointer allocated via malloc.

==============================================================================

Q35: Why should I use "new" instead of trustworthy old malloc()?

Constructors/destructors, type safety, overridability.

Constructors/destructors: unlike "malloc(sizeof(Fred))", "new Fred()" calls
Fred's constructor.  Similarly, "delete p" calls "*p"'s destructor.

Type safety: malloc() returns a "void*" which isn't type safe.  "new Fred()"
returns a ptr of the right type (a "Fred*").

Overridability: "new" is an operator that can be overridden by a class, while
"malloc" is not overridable on a per-class basis.

==============================================================================

Q36: Why doesn't C++ have a "realloc()" along with "new" and "delete"?

To save you from disaster.

When realloc() has to copy the allocation, it uses a BITWISE copy operation,
which will tear most C++ objects to shreds.  C++ objects should be allowed to
copy themselves: they use their own copy constructor or assignment operator.

==============================================================================

Q37: How do I allocate / unallocate an array of things?

Use new[] and delete[]:

	Fred* p = new Fred[100];
	//...
	delete [] p;

Any time you use the "[...]" in the "new" expression, you *!*MUST*!* use "[]"
in the "delete" statement.  This syntax is necessary because there is no
syntactic difference between a pointer to a thing and a pointer to an array of
things (something we inherited from C).

==============================================================================

Q38: What if I forget the "[]" when "delete"ing array allocated via "new
   Fred[n]"?

All life comes to a catastrophic end.

It is the programmer's --not the compiler's-- responsibility to get the
connection between new[] and delete[] correct.  If you get it wrong, neither a
compile-time nor a run-time error message will be generated by the compiler.
Heap corruption is a likely result.  Or worse.  Your program will probably die.

==============================================================================

Q39: Is it legal (and moral) for a member function to say "delete this"?

As long as you're careful, you'll be ok.

Here's how I define "careful":
1) You're absolutely 100% positive sure that "this" was allocated via "new"
   (not by "new[]", nor by placement "new", by by plain ordinary "new").
2) You're absolutely 100% positive sure that your member function will be
   the last member function invoked on this object.
3) After you do the suicide thing ("delete this;"), you must not touch any
   piece of "this" object, including data or methods.
4) After you do the suicide thing ("delete this;"), you must not touch the
   "this" pointer.  In other words, you must not examine it, compare it with
   another pointer or with NULL, print it, cast it, do anything with it.

Naturally the usual caveats apply in cases where your "this" pointer is a
pointer to a base class and the destructor isn't virtual.

==============================================================================

Q40: How do I allocate multidimensional arrays using new?

There are many ways to do this, depending on how flexible you want the array
sizing to be.  On one extreme, if you know all the dimensions at compile-time,
you can allocate multidimensional arrays statically (as in C):

	class Fred { /*...*/ };

	void manipulateArray()
	{
	  Fred matrix[10][20];

	  //use matrix[i][j]...

	  //no need for explicit deallocation
	}

On the other extreme, if you want to allow the various slices of the matrix to
have a different sizes, you can allocate everything off the freestore:

	void manipulateArray(unsigned nrows, unsigned ncols[])
	//'nrows' is the number of rows in the array.
	//therefore valid row numbers are from 0 to nrows-1 inclusive.
	//'ncols[r]' is the number of columns in row 'r' ('r' in [0..nrows-1]).
	{
	  Fred** matrix = new Fred*[nrows];
	  for (unsigned r = 0; r < nrows; ++r)
	    matrix[r] = new Fred[ ncols[r] ];

	  //use matrix[i][j]...

	  //deletion is the opposite of allocation:
	  for (r = nrows; r > 0; --r)
	    delete [] matrix[r-1];
	  delete [] matrix;
	}

==============================================================================

Q41: Does C++ have arrays whose length can be specified at run-time?

Yes, in the sense that STL has a vector template that provides this behavior.
See on "STL" in the "Libraries" section.

No, in the sense that built-in array types need to have their length specified
at compile time.

Yes, in the sense that even built-in array types can specify the first index
bounds at run-time.  E.g., comparing with the previous FAQ, if you only need
the first array dimension to vary, then you can just ask new for an array of
arrays (rather than an array of pointers to arrays):

	const unsigned ncols = 100;
	//'ncols' is not a run-time variable (number of columns in the array)

	class Fred { ... };

	void manipulateArray(unsigned nrows)
	//'nrows' is a run-time variable (number of rows in the array)
	{
	  Fred (*matrix)[ncols] = new Fred[nrows][ncols];

	  //use matrix[i][j]

	  //deletion is the opposite of allocation:
	  delete [] matrix;
	}

You can't do this if you need anything other than the first dimension
of the array to change at run-time.

==============================================================================

Q42: How can I ensure objects of my class are always created via "new" rather
   than as locals or global/static objects?

Make sure the class's constructors are "private:", and define "friend" or
"static" fns that return a ptr to the objects created via "new" (make the
constructors "protected:" if you want to allow derived classes).

	class Fred {	//only want to allow dynamicly allocated Fred's
	public:
	  static Fred* create()                 { return new Fred();     }
	  static Fred* create(int i)            { return new Fred(i);    }
	  static Fred* create(const Fred& fred) { return new Fred(fred); }
	private:
	  Fred();
	  Fred(int i);
	  Fred(const Fred& fred);
	  virtual ~Fred();
	};

	main()
	{
	  Fred* p = Fred::create(5);
	  ...
	  delete p;
	}

==============================================================================
SECTION 10: Debugging and error handling
==============================================================================

Q43: How can I handle a constructor that fails?

Throw an exception.

Constructors don't have a return type, so it's not possible to use error codes.
The best way to signal constructor failure is therefore to throw an exception.

Before C++ had exceptions, we signaled constructor failure by putting the
object into a "half baked" state (e.g., by setting an internal status bit).
There was a query ("inspector") method to check this bit, that allowed clients
to discover whether they had a live object.  Other member functions would also
check this bit, and, if the object wasn't really alive, do a no-op (or perhaps
something more obnoxious such as "abort()").  This was really ugly.

==============================================================================

Q44: How should I handle resources if my constructors may throw exceptions?

Every data member inside your object should clean up its own mess.

If a constructor throws an exception, the object's destructor is NOT run.  If
your object has already done something that needs to be undone (such as
allocating some memory, opening a file, or locking a semaphore), this "stuff
that needs to be undone" MUST be remembered by a data member inside the object.

For example, rather than allocating memory into a raw "Fred*" data member, put
the allocated memory into a "smart pointer" member object, and the destructor
of this smart pointer will delete the Fred object when the smart pointer dies.

==============================================================================
SECTION 11: Const correctness
==============================================================================

Q45: What is "const correctness"?

A good thing.

Const correctness uses the keyword "const" to ensure const objects don't get
mutated.  E.g., if function "f()" accepts a "String", and "f()" wants to
promise not to change the "String", you:

 * can either pass by value:	void  f(      String  s   )  { /*...*/ }
 * or by constant reference:	void  f(const String& s   )  { /*...*/ }
 * or by constant pointer:	void  f(const String* sptr)  { /*...*/ }
 * but NOT by non-const ref:	void  f(      String& s   )  { /*...*/ }
 * NOR by non-const pointer:	void  f(      String* sptr)  { /*...*/ }

Attempted changes to "s" within a fn that takes a "const String&" are flagged
as compile-time errors; neither run-time space nor speed is degraded.

Declaring the "constness" of a parameter is just another form of type safety.
It is almost as if a constant String, for example, "lost" its various mutative
operations.  If you find type safety helps you get systems correct (it does;
especially in large systems), you'll find const correctness helps also.

==============================================================================

Q46: Should I try to get things const correct "sooner" or "later"?

At the very, very, VERY beginning.

Back-patching const correctness results in a snowball effect: every "const" you
add "over here" requires four more to be added "over there."

==============================================================================

Q47: What is a "const member function"?

A member function that inspects (rather than mutates) its object.

	class Fred {
	public:
	  void f() const;
	};      // ^^^^^--- this implies "fred.f()" won't change "fred"

This means that the ABSTRACT (client-visible) state of the object isn't going
to change (as opposed to promising that the "raw bits of the object's struct
aren't going to change).  C++ compilers aren't allowed to take the "bitwise"
interpretation, since a non-const alias could exist which could modify the
state of the object (gluing a "const" ptr to an object doesn't promise the
object won't change; it promises only that the object won't change VIA THAT
POINTER).

"const" member functions are often called "inspectors."  Non-"const" member
functions are often called "mutators."

==============================================================================

Q48: What do I do if I want to update an "invisible" data member inside a
   "const" member function?

Use "mutable", or use "const_cast".

A small percentage of inspectors need to make innocuous changes to data members
(e.g., a "Set" object might want to cache its last lookup in hopes of improving
the performance of its next lookup).  By saying the changes are "inocuous," I
mean that the changes wouldn't be visible from outside the object's interface
(otherwise the method would be a mutator rather than an inspector).

When this happens, the data member which will be modified should be marked as
"mutable" (put the "mutable" keyword just before the data member's declaration;
i.e., in the same place where you could put "const").  This tells the compiler
that the data member is allowed to change during a const member function.  If
you can't use "mutable", you can cast away the constness of "this" via
"const_cast".  E.g., in "Set::lookup() const", you might say,

	Set* self = const_cast<Set*>(this);

After this line, "self" will have the same bits as "this" (e.g., "self==this"),
but "self" is a "Set*" rather than a "const Set*".  Therefore you can use
"self" to modify the object pointed to by "this".

==============================================================================

Q49: Does "const_cast" mean lost optimization opportunities?

In theory, yes; in practice, no.

Even if a compiler outlawed "const_cast", the only way to avoid flushing the
register cache across a "const" member function call would be to ensure that
there are no non-const pointers that alias the object.  This can happen only in
rare cases (when the object is constructed in the scope of the const member fn
invocation, and when all the non-const member function invocations between the
object's construction and the const member fn invocation are statically bound,
and when every one of these invocations is also "inline"d, and when the
constructor itself is "inline"d, and when any member fns the constructor calls
are inline).

==============================================================================
SECTION 12: Inheritance
==============================================================================

Q50: Is inheritance important to C++?

Yep.

Inheritance is what separates abstract data type (ADT) programming from OOP.

==============================================================================

Q51: When would I use inheritance?

As a specification device.

Human beings abstract things on two dimensions: part-of and kind-of.  A Ford
Taurus is-a-kind-of-a Car, and a Ford Taurus has-a Engine, Tires, etc.  The
part-of hierarchy has been a part of software since the ADT style became
relevant; inheritance adds "the other" major dimension of decomposition.

==============================================================================

Q52: How do you express inheritance in C++?

By the ": public" syntax:

	class Car : public Vehicle {
	        //^^^^^^^^---- ": public" is pronounced "is-a-kind-of-a'
	  //...
	};

We state the above relationship in several ways:
 * Car is "a kind of a" Vehicle
 * Car is "derived from" Vehicle
 * Car is "a specialized" Vehicle
 * Car is the "subclass" of Vehicle
 * Vehicle is the "base class" of Car
 * Vehicle is the "superclass" of Car (this not as common in the C++ community)

==============================================================================

Q53: Is it ok to convert a pointer from a derived class to its base class?

Yes.

A derived class is a specialized version of the base class ("Derived is a
kind-of Base").  The upward conversion is perfectly safe, and happens all the
time (if I am pointing at a car, I am in fact pointing at a vehicle):

	void f(Vehicle* v);
	void g(Car* c) { f(c); }	//perfectly safe; no cast

Note that the answer to this FAQ assumes we're talking about "public"
inheritance; see below on "private/protected" inheritance for "the other kind".

==============================================================================

Q54: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?

C++ allows a Derived* to be converted to a Base*, since a Derived object is a
kind of a Base object.  However trying to convert a Derived** to a Base** is
(correctly) flagged as an error (if it was allowed, the Base** could be
dereferenced (yielding a Base*), and the Base* could be made to point to an
object of a DIFFERENT derived class.  This would be an error.

As a corollary, an array of Deriveds is-NOT-a-kind-of array of Bases.  At
Paradigm Shift, Inc. we use the following example in our C++ training sessions:

               "A bag of apples is NOT a bag of fruit".

If a bag of apples COULD be passed as a bag of fruit, someone could put a
banana into the bag of apples!

==============================================================================

Q55: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are
   bad?

Yes, "arrays are evil" (jest kidd'n :-).

There's a very subtle problem with using raw built-in arrays.  Consider this:

	void f(Base* arrayOfBase)
	{
	  arrayOfBase[3].memberfn();
	}

	main()
	{
	  Derived arrayOfDerived[10];
	  f(arrayOfDerived);
	}

The compiler thinks this is perfectly type-safe, since it can convert a
Derived* to a Base*.  But in reality it is horrendously evil: since Derived
might be larger than Base, the array index in f() not only isn't type safe, it
may not even be pointing at a real object!  In general it'll be pointing
somewhere into the innards of some poor Derived.

The root problem is that C++ can't distinguish between a ptr-to-a-thing and a
ptr-to-an-array-of-things.  Naturally C++ "inherited" this feature from C.

NOTE: if we had used an array-like CLASS instead of using a raw array (e.g., an
"Array<T>" rather than a "T[]"), this problem would have been properly trapped
as an error at compile time rather than at run-time.

==============================================================================
SUBSECTION 12A: Inheritance -- Virtual functions
==============================================================================

Q56: What is a "virtual member function"?

A virtual function allows derived classes to replace the implementation
provided by the base class.  The compiler ensures the replacement is always
called whenever the object in question is actually of the derived class, even
if the object is accessed by a base pointer rather than a derived pointer.
This allows algorithms in the base class to be replaced in the derived class,
even if users don't know about the derived class.

Note: the derived class can partially replace ("override") the base class
method (the derived class method can invoke the base class version if desired).

==============================================================================

Q57: How can C++ achieve dynamic binding yet also static typing?

In the following discussion, "ptr" means either a pointer or a reference.

When you have a ptr, there are two types: the (static) type of the ptr, and the
(dynamic) type of the pointed-to object (the object may actually be of a class
that is derived from the class of the ptr).

"Static typing" means that the "legality" of the call is checked based on the
static type of the ptr: if the type of the ptr can handle the member fn,
certainly the pointed-to object can handle it as well.

"Dynamic binding" means that the "code" that is called is based on the dynamic
type of the pointed-to object.  This is called "dynamic binding," since the
actual code being called is determined dynamically (at run time).

==============================================================================

Q58: Should a derived class replace ("override") a non-virtual fn from a base
   class?

It's legal, but it ain't moral.

Experienced C++ programmers will sometimes redefine a non-virtual fn for
efficiency (the alternate implementation might make better use of the derived
class' resources), or to get around the hiding rule (see below, and ARM
["Annotated Reference Manual"] sect.13.1).  However the client-visible effects
must be IDENTICAL, since non-virtual fns are dispatched based on the static
type of the ptr/ref rather than the dynamic type of the pointed-to/referenced
object.

==============================================================================

Q59: What's the meaning of, "Warning: Derived::f(int) hides Base::f(float)"?

It means you're going to die.

Here's the mess you're in: if Derived declares a member function named "f", and
Base declares a member function named "f" with a different signature (e.g.,
different parameter types and/or constness), then the Base "f" is "hidden"
rather than "overloaded" or "overridden" (even if the Base "f" is virtual).

Here's how you get out of the mess: Derived must redefine the Base member
function(s) that are hidden (even if they are non-virtual).  Normally this
re-definition merely calls the appropriate Base member function.  E.g.,

	class Base {
	public:
	  void f(int);
	};

	class Derived : public Base {
	public:
	  void f(double);
	  void f(int i) { Base::f(i); }
	};             // ^^^^^^^^^^--- redefinition merely calls Base::f(int)

==============================================================================
SUBSECTION 12B: Inheritance -- Conformance
==============================================================================

Q60: Should I hide public member fns inherited from my base class?

Never, never, never do this.  Never.  NEVER!

Attempting to hide (eliminate, revoke) inherited public member functions is an
all-too-common design error.  It usually stems from muddy thinking.

==============================================================================

Q61: Is a "Circle" a kind-of an "Ellipse"?

Not if Ellipse promises to be able to change its size asymmetrically.

For example, suppose Ellipse has a "setSize(x,y)" method, and suppose this
method promises "the Ellipse's width() will be x, and its height() will be y".
In this case, Circle can't be a kind-of Ellipse.  Simply put, if Ellipse can do
something Circle can't, then Circle can't be a kind of Ellipse.

This leaves two potential (valid) relationships between Circle and Ellipse:
 * Make Circle and Ellipse completely unrelated classes.
 * Derive Circle and Ellipse from a base class representing "Ellipses that
   can't NECESSARILY perform an unequal-setSize operation."

In the first case, Ellipse could be derived from class "AsymmetricShape" (with
setSize(x,y) being introduced in AsymmetricShape), and Circle could be derived
from "SymmetricShape," which has a setSize(size) member fn.

In the second case, class "Oval" could only have "setSize(size)" which sets
both the "width()" and the "height()" to "size", then derive both Ellipse and
Circle from Oval.  Ellipse --but not Circle-- adds the "setSize(x,y)" operation
(see the "hiding rule" for a caveat if the same method name "setSize()" is used
for both operations).

==============================================================================

Q62: Are there other options to the "Circle is/isnot kind-of Ellipse"
   dilemma?

If you claim that all Ellipses can be squashed asymmetrically, and you claim
that Circle is a kind-of Ellipse, and you claim that Circle can't be squashed
asymmetrically, clearly you've got to adjust (revoke, actually) one of your
claims.  Thus you've either got to get rid of "Ellipse::setSize(x,y)", get rid
of the inheritance relationship between Circle and Ellipse, or admit that your
"Circle"s aren't necessarily circular.

Here are the two most common traps new OO/C++ programmers regularly fall into.
They attempt to use coding hacks to cover up a broken design (they redefine
Circle::setSize(x,y) to throw an exception, call "abort()", or choose the
average of the two parameters, or to be a no-op).  Unfortunately all these
hacks will surprise users, since users are expecting "width() == x" and
"height() == y".

The only rational way out of this would be to weaken the promise made by
Ellipse's "setSize(x,y)" (e.g., you'd have to change it to, "This method MIGHT
set width() to x and height() to y, or it might do NOTHING").  Unfortunately
this dilutes the contract into dribble, since the user can't rely on any
meaningful behavior.  The whole hierarchy therefore begins to be worthless
(it's hard to convince someone to use an object if you have to shrug your
shoulders when asked what the object does for them).

==============================================================================
SUBSECTION 12C: Inheritance -- Access rules
==============================================================================

Q63: Why can't my derived class access "private" things from my base class?

To protect you from future changes to the base class.

Derived classes do not get access to private members of a base class.  This
effectively "seals off" the derived class from any changes made to the private
members of the base class.

==============================================================================

Q64: What's the difference between "public:", "private:", and "protected:"?

"Private:" is discussed in the previous section, and "public:" means "anyone
can access it."  The third option, "protected:", makes a member (either data
member or member fn) accessible to subclasses.

==============================================================================

Q65: How can I protect subclasses from breaking when I change internal parts?

A class has two distinct interfaces for two distinct sets of clients:
 * its "public:" interface serves unrelated classes.
 * its "protected:" interface serves derived classes.

Unless you expect all your subclasses to be built by your own team, you should
consider making your base class's bits be "private:", and use "protected:"
inline access functions to access these data.  This way the private bits can
change, but the derived class's code won't break unless you change the
protected access functions.

==============================================================================
SUBSECTION 12D: Inheritance -- Constructors and destructors
==============================================================================

Q66: When my base class's constructor calls a virtual function, why doesn't my
   derived class's override of that virtual function get invoked?

During the Base class's constructor, the object isn't yet a Derived, so if
"Base::Base()" calls a virtual function "virt()", the "Base::virt()" will be
invoked, even if "Derived::virt()" exists.

Similarly, during Base's destructor, the object is no longer a Derived, so when
Base::~Base() calls "virt()", "Base::virt()" gets control, NOT the
"Derived::virt()" override.

You'll quickly see the wisdom of this approach when you imagine the disaster if
"Derived::virt()" touched a member object from the Derived class.

==============================================================================

Q67: Does a derived class destructor need to explicitly call the base
   destructor?

No, never explicitly call a destructor (where "never" means "rarely").

A derived class's destructor (whether or not you explicitly define one)
AUTOMATICALLY invokes the destructors for member objects and base class
subobjects.  Member objects are destroyed in the reverse order they appear
within the class, then base class subobjects are destroyed in the reverse order
that they appear in the class's list of base classes.

You should explicitly call a destructor ONLY in esoteric situations, such as
when destroying an object created by the "placement new operator."

==============================================================================
SUBSECTION 12E: Inheritance -- Private and protected inheritance
==============================================================================

Q68: How do you express "private inheritance"?

When you use ": private" instead of ": public."  E.g.,

	class Foo : private Bar {
	  //...
	};

==============================================================================

Q69: How are "private inheritance" and "composition" similar?

Private inheritance is a syntactic variant of composition (has-a).

E.g., the "car has-a engine" relationship can be expressed using composition:

	class Engine {
	public:
	  Engine(int numCylinders);
	  void start();			//starts this Engine
	};

	class Car {
	public:
	  Car() : e_(8) { }		//initializes this Car with 8 cylinders
	  void start() { e_.start(); }	//start this Car by starting its engine
	private:
	  Engine e_;
	};

The same "has-a" relationship can also be expressed using private inheritance:

	class Car : private Engine {
	public:
	  Car() : Engine(8) { }		//initializes this Car with 8 cylinders
	  Engine::start;		//start this Car by starting its engine
	};

There are several similarities between these two forms of composition:
 * in both cases there is exactly one Engine member object contained in a Car.
 * in neither case can users (outsiders) convert a Car* to an Engine*.

There are also several distinctions:
 * the first form is needed if you want to contain several Engines per Car.
 * the second form can introduce unnecessary multiple inheritance.
 * the second form allows members of Car to convert a Car* to an Engine*.
 * the second form allows access to the "protected" members of the base class.
 * the second form allows Car to override Engine's virtual functions.

Note that private inheritance is usually used to gain access into the
"protected:" members of the base class, but this is usually a short-term
solution (translation: a band-aid; see below).

==============================================================================

Q70: Which should I prefer: composition or private inheritance?

Composition.

Normally you don't WANT to have access to the internals of too many other
classes, and private inheritance gives you some of this extra power (and
responsibility).  But private inheritance isn't evil; it's just more expensive
to maintain, since it increases the probability that someone will change
something that will break your code.

A legitimate, long-term use for private inheritance is when you want to build a
class Fred that uses code in a class Wilma, and the code from class Wilma needs
to invoke methods from your new class, Fred.  In this case, Fred calls
non-virtuals in Wilma, and Wilma calls (usually pure) virtuals in itself, which
are overridden by Fred.  This would be much harder to do with composition.

	class Wilma {
	protected:
	  void fredCallsWilma()
	    { cout << "Wilma::fredCallsWilma()\n"; wilmaCallsFred(); }
	  virtual void wilmaCallsFred() = 0;
	};

	class Fred : private Wilma {
	public:
	  void barney()
	    { cout << "Fred::barney()\n"; Wilma::fredCallsWilma(); }
	protected:
	  virtual void wilmaCallsFred()
	    { cout << "Fred::wilmaCallsFred()\n"; }
	};

==============================================================================

Q71: Should I pointer-cast from a "privately" derived class to its base
   class?

Generally, No.

From a method or friend of a privately derived class, the relationship to the
Status: O

base class is known, and the upward conversion from PrivatelyDer* to Base* (or
PrivatelyDer& to Base&) is safe; no cast is needed or recommended.

However users of PrivateDer should avoid this unsafe conversion, since it is
based on a "private" decision of PrivateDer, and is subject to change without
notice.

==============================================================================

Q72: How is protected inheritance related to private inheritance?

Similarities: both allow overriding virtuals in the private/protected base
class, neither claims the derived is a kind-of its base.

Dissimilarities: protected inheritance allows derived classes of derived
classes to know about the inheritance relationship (it exposes your grand kids
to your implementation details).  This has both benefits (it allows subclasses
of the protected derived class to exploit the relationship to the protected
base class) and costs (the protected derived class can't change the
relationship without potentially breaking further derived classes).

Protected inheritance uses the ": protected" syntax:

	class Car : protected Engine {
	  //...
	};

==============================================================================

Q73: What are the access rules with "private" and "protected" inheritance?

Take these classes as examples:

	class B                    { /*...*/ };
	class D_priv : private   B { /*...*/ };
	class D_prot : protected B { /*...*/ };
	class D_publ : public    B { /*...*/ };
	class UserClass            { B b; /*...*/ };

None of the subclasses can access anything that is private in B.  In D_priv,
the public and protected parts of B are "private".  In D_prot, the public and
protected parts of B are "protected".  In D_publ, the public parts of B are
public and the protected parts of B are protected (D_publ is-a-kind-of-a B).
Class "UserClass" can access only the public parts of B, which "seals off"
UserClass from B.

To make a public member of B so it is public in D_priv or D_prot, state the
name of the member with a "B::" prefix.  E.g., to make member "B::f(int,float)"
public in D_prot, you would say:

	class D_prot : protected B {
	public:
	  B::f;    //note: not  "B::f(int,float)"
	};

==============================================================================
SECTION 13: Abstraction
==============================================================================

Q74: What's the big deal of separating interface from implementation?

Interfaces are a company's most valuable resources.  Designing an interface
takes longer than whipping together a concrete class which fulfills that
interface.  Furthermore interfaces require the time of more expensive people.

Since interfaces are so valuable, they should be protected from being tarnished
by data structures and other implementation artifacts.  Thus you should
separate interface from implementation.

==============================================================================

Q75: How do I separate interface from implementation in C++ (like Modula-2)?

Use an ABC (see next FAQ).

==============================================================================

Q76: What is an ABC ("abstract base class")?

At the design level, an ABC corresponds to an abstract concept.  If you asked a
Mechanic if he repaired Vehicles, he'd probably wonder what KIND-OF Vehicle you
had in mind.  Chances are he doesn't repair space shuttles, ocean liners,
bicycles, or nuclear submarines.  The problem is that the term "Vehicle" is an
abstract concept (e.g., you can't build a "vehicle" unless you know what kind
of vehicle to build).  In C++, class Vehicle would be an ABC, with Bicycle,
SpaceShuttle, etc, being subclasses (an OceanLiner is-a-kind-of-a Vehicle).  In
real-world OOP, ABCs show up all over the place.

As programming language level, an ABC is a class that has one or more pure
virtual member functions (see next FAQ).  You cannot make an object (instance)
of an ABC.

==============================================================================

Q77: What is a "pure virtual" member function?

A member function of an ABC that you can implement only in a derived class.

Some member functions exist in concept, but can't have any actual defn.  E.g.,
suppose I asked you to draw a Shape at location (x,y) that has size 7.  You'd
ask me "what kind of shape should I draw?" (circles, squares, hexagons, etc,
are drawn differently).  In C++, we indicate the existence of the "draw()"
method, but we recognize it can (logically) be defined only in subclasses:

	class Shape {
	public:
	  virtual void draw() const = 0;
	  //...                     ^^^--- "= 0" means it is "pure virtual"
	};

This pure virtual function makes "Shape" an ABC.  If you want, you can think of
the "= 0" syntax as if the code were at the NULL pointer.  Thus "Shape"
promises a service to its users, yet Shape isn't able to provide any code to
fulfill that promise.  This ensures any actual object created from a [concrete]
class derived of Shape *WILL* have the indicated member fn, even though the
base class doesn't have enough information to actually DEFINE it yet.

==============================================================================

Q78: How can I provide printing for an entire hierarchy of classes?

Provide a friend operator<< that calls a protected virtual function:

	class Base {
	public:
	  friend ostream& operator<< (ostream& o, const Base& b)
	    { b.print(o); return o; }
	  //...
	protected:
	  virtual void print(ostream& o) const;  //or "=0;" if "Base" is an ABC
	};

	class Derived : public Base {
	protected:
	  virtual void print(ostream& o) const;
	};

Now all subclasses of Base merely provide their own "print(ostream&) const"
member function (they all share the common "<<" operator).  This technique
allows friends to ACT as if they supported dynamic binding.

==============================================================================

Q79: When should my destructor be virtual?

When you may "delete" a derived object via a base pointer.

Virtual fns bind to the code associated with the class of the object, rather
than with the class of the pointer/ref.  When you say "delete basePtr", and the
base class has a virtual destructor, the destructor that gets invoked is the
one associated with the type of the object *basePtr, rather than the one
associated with the type of the pointer.  This is generally A Good Thing.

To make life easy for you, the only time you wouldn't want to make a class's
destructor virtual is if that class has NO virtual fns, since the introduction
of the first virtual fn imposes some space overhead in each object (typically
one machine word).  This is how the compiler implements the magic of dynamic
binding; it usually boils down to an extra ptr per object called the "virtual
table pointer" or "vptr".

==============================================================================

Q80: What is a "virtual constructor"?

An idiom that allows you to do something that C++ doesn't directly support.

You can get the effect of virtual constructor by a virtual "createCopy()"
member fn (for copy constructing), or a virtual "createSimilar()" member fn
(for the default constructor).

	class Shape {
	public:
	  virtual ~Shape() { }		//see on "virtual destructors" for more
	  virtual void draw() = 0;
	  virtual void move() = 0;
	  //...
	  virtual Shape* createCopy() const = 0;
	  virtual Shape* createSimilar() const = 0;
	};

	class Circle : public Shape {
	public:
	  Circle* createCopy()    const { return new Circle(*this); }
	  Circle* createSimilar() const { return new Circle(); }
	  //...
	};

The invocation of "Circle(*this)" is that of copy construction ("*this" has
type "const Circle&" in these methods).  "createSimilar()" is similar, but it
constructs a "default" Circle.

Users use these as if they were "virtual constructors":

	void userCode(Shape& s)
	{
	  Shape* s2 = s.createCopy();
	  Shape* s3 = s.createSimilar();
	  //...
	  delete s2;	//relies on destructor being virtual!!
	  delete s3;	// ditto
	}

This fn will work correctly regardless of whether the Shape is a Circle,
Square, or some other kind-of Shape that doesn't even exist yet.

--
Paradigm Shift, Inc. / P.O. Box 5108 / Potsdam, NY  13676
Voice: 315-353-6100 / FAX: 315-353-6110

From csus.edu!csulb.edu!info.ucla.edu!library.ucla.edu!newsfeed.internetmci.com!news.mathworks.com!news.kei.com!ub!library.erc.clarkson.edu!sun.soe.clarkson.edu!cline Sun Oct 15 13:08:08 1995
From: cline@sun.soe.clarkson.edu (Marshall Cline)
Newsgroups: comp.lang.c++
Subject: C++ FAQ: posting #3/4
Followup-To: comp.lang.c++
Date: 2 Oct 1995 21:32:17 GMT
Organization: Paradigm Shift, Inc (OO consulting/training)
Lines: 638
Sender: cline@sun.soe.clarkson.edu
Distribution: world
Expires: +1 month
Message-ID: <44plp1$kg1@library.erc.clarkson.edu>
Reply-To: cline@parashift.com (Marshall Cline)
NNTP-Posting-Host: sun.soe.clarkson.edu
Summary: Please read this before posting to comp.lang.c++
Status: O

comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
Copyright (C) 1991-95 Marshall P. Cline, Ph.D.
Posting 3 of 4.
Posting #1 explains copying permissions, (no)warranty, table-of-contents, etc

==============================================================================
SECTION 14: Style guidelines
==============================================================================

Q81: What are some good C++ coding standards?

Thank you for reading this answer rather than just trying to set your own
coding standards.

But please don't ask this question on comp.lang.c++.  Nearly every software
engineer has, at some point, felt that coding standards are or can be used as a
"power play."  Furthermore some attempts to set C++ coding standards have been
made by those unfamiliar with the language and/or paradigm, so the standards
end up being based on what WAS the state-of-the-art when the standards setters
where writing code.  Such impositions generate an attitude of mistrust for
coding standards.

Obviously anyone who asks this question on comp.lang.c++ wants to be trained so
they DON'T run off on their own ignorance, but nonetheless the answers tend to
generate more heat than light.

==============================================================================

Q82: Are coding standards necessary?  Are they sufficient?

Coding standards do not make non OO programmers into OO programmers; only
training and experience do that.  If coding standards have merit, it is that
they discourage the petty fragmentation that occurs when large organizations
coordinate the activities of diverse groups of programmers.

But you really want more than a coding standard.  The structure provided by
coding standards gives neophytes one less degree of freedom to worry about,
however pragmatics go well beyond pretty-printing standards.  Organizations
need a consistent PHILOSOPHY of design and implementation.  E.g., strong or
weak typing?  references or ptrs in interfaces?  stream I/O or stdio?  should
C++ code call our C?  vise versa?  how should ABCs be used?  should inheritance
be used as an implementation technique or as a specification technique?  what
testing strategy should be employed?  inspection strategy?  should interfaces
uniformly have a "get" and/or "set" method for each data member?  should
interfaces be designed from the outside-in or the inside-out?  should errors be
handled by try/catch/throw or return codes?  etc.

What is needed is a "pseudo standard" for detailed DESIGN.  I recommend a
three-pronged approach to achieving this standardization: training, mentoring,
and libraries.  Training provides "intense instruction," mentoring allows OO to
be caught rather than just taught, and a high quality C++ class library
provides "long term instruction."  There is a thriving commercial market for
all three kinds of "training."  Advice by organizations who have been through
the mill is consistent: Buy, Don't Build.  Buy libraries, buy training, buy
tools, buy consulting.  Companies who have attempted to become a self-taught
tool-shop as well as an application/system shop have found success difficult.

Few argue that coding standards are "ideal," or even "good," however they are
necessary in the kind of organizations/situations described above.

The following FAQs provide some basic guidance in conventions and styles.

==============================================================================

Q83: Should our organization determine coding standards from our C
   experience?

No!

No matter how vast your C experience, no matter how advanced your C expertise,
being a good C programmer does not make you a good C++ programmer.  Converting
from C to C++ is more than just learning the syntax and semantics of the "++"
part of C++.  Organizations who want the promise of OOP, but who fail to put
the "OO" into OOP, are fooling themselves; the balance sheet will show their
folly.

C++ coding standards should be tempered by C++ experts.  Asking comp.lang.c++
is a start (but don't use the term "coding standard" in the question; instead
simply say, "what are the pros and cons of this technique?").  Seek out experts
who can help guide you away from pitfalls.  Get training.  Buy libraries and
see if "good" libraries pass your coding standards.  Do NOT set standards by
yourself unless you have considerable experience in C++.  Having no standard is
better than having a bad standard, since improper "official" positions "harden"
bad brain traces.  There is a thriving market for both C++ training and
libraries from which to pool expertise.

One more thing: whenever something is in demand, the potential for charlatans
increases.  Look before you leap.  Also ask for student-reviews from past
companies, since not even expertise makes someone a good communicator.
Finally, select a practitioner who can teach, not a full time teacher who has a
passing knowledge of the language/paradigm.

==============================================================================

Q84: Should I declare locals in the middle of a fn or at the top?

Declare near first use.

An object is initialized (constructed) the moment it is declared.  If you don't
have enough information to initialize an object until half way down the fn, you
can either initialize it to an "empty" value at the top then "assign" it later,
or initialize it correctly half way down the fn.  It's cheaper (in runtime
performance) to get it right the first time than to build it once, tear it
down, and build it again.  Simple examples show a factor of 350% speed hit for
simple classes like "String".  Your mileage may vary; surely the overall system
degradation will be less that 300+%, but there WILL be degradation.
UNNECESSARY degradation.

A common retort to the above is: "we"ll provide "set" methods for every datum
in our objects, so the cost of construction will be spread out."  This is worse
than the performance overhead, since now you're introducing a maintenance
nightmare.  Providing "set" methods for every datum is tantamount to public
data: you've exposed your implementation technique to the world.  The only
thing you've hidden is the physical NAMES of your member objects, but the fact
that you're using a List and a String and a float (for example) is open for all
to see.  Maintenance generally consumes far more resources than run-time CPU.

Locals should be declared near their first use.  Sorry that this isn't familiar
to C experts, but "new" doesn't necessarily mean "bad."

==============================================================================

Q85: What source-file-name convention is best? "foo.C"? "foo.cc"? "foo.cpp"?

If you already have a convention, use it.  If not, consult your compiler to see
what the compiler expects.  Typical answers are: ".C", ".cc", ".cpp", or
".cxx" (naturally the ".C" extension assumes a case-sensitive file system to
distinguish ".C" from ".c").

At Paradigm Shift, Inc., we use ".C" in our Makefiles even on case-insensitive
file systems (on case-insensitive file systems, we supply the compiler option
that means "assume all .c files are C++ source files"; e.g., "-Tdp" for IBM
CSet++, "-cpp" for Zortech C++, "-P" for Borland C++, etc).

==============================================================================

Q86: What header-file-name convention is best? "foo.H"? "foo.hh"? "foo.hpp"?

If you already have a convention, use it.  If not, and if you don't need your
editor to distinguish between C and C++ files, simply use ".h".  Otherwise use
whatever the editor wants, such as ".H", ".hh", or ".hpp".

At Paradigm Shift, Inc., we use ".h" for both C and C++ source files (then
again, we don't create many straight C header files).

==============================================================================

Q87: Are there any lint-like guidelines for C++?

Yes, there are some practices which are generally considered dangerous.
However none of these are universally "bad," since situations arise when
even the worst of these is needed:
 * a class "Fred"s assignment operator should return "*this" as an "Fred&"
   (allows chaining of assignments)
 * a class with any virtual fns ought to have a virtual destructor
 * a class with any of {destructor, assignment operator, copy constructor}
   generally needs all 3
 * a class "Fred"s copy constructor and assignment operator should have "const"
   in the parameter: respectively "Fred::Fred(const Fred&)" and
   "Fred& Fred::operator=(const Fred&)".
 * always use initialization lists for class sub-objects rather than assignment
   the performance difference for user-defined classes can be substantial (3x!)
 * many assignment operators should start by testing if "we" are "them"; e.g.,
	Fred& Fred::operator= (const Fred& fred)
	{
	  if (this == &fred) return *this;
	  //...normal assignment duties...
	  return *this;
	}
   sometimes there is no need to check, but these situations generally
   correspond to when there's no need for an explicit user-specified assignment
   op (as opposed to a compiler-synthesized assignment-op).
 * in classes that define both "+=," "+" and "=," "a+=b" and "a=a+b" should
   generally do the same thing; ditto for the other identities of builtin types
   (e.g., a+=1 and ++a; p[i] and *(p+i); etc).  This can be enforced by writing
   the binary ops using the "op=" forms; e.g.,
	Fred operator+ (const Fred& a, const Fred& b)
	{
	  Fred ans = a;
	  ans += b;
	  return ans;
	}
   This way the "constructive" binary ops don't even need to be friends.  But
   it is sometimes possible to more efficiently implement common ops (e.g., if
   class "Fred" is actually "String," and "+=" has to reallocate/copy string
   memory, it may be better to know the eventual length from the beginning).

==============================================================================
SECTION 15: Keys for Smalltalk programmers to learn C++
==============================================================================

Q88: Why does C++'s FAQ have a section on Smalltalk? Is this
   Smalltalk-bashing?

The two "major" OOPLs in the world are C++ and Smalltalk.  Due to its
popularity as the OOPL with the second largest user pool, many new C++
programmers come from a Smalltalk background.  This section answers the
questions:
 * what's different about the two languages
 * what must a Smalltalk-turned-C++ programmer know to master C++

This section does *!*NOT*!* attempt to answer the questions:
 * which language is "better"?
 * why is Smalltalk "bad"?
 * why is C++ "bad"?

Nor is it an open invitation for some Smalltalk terrorist to slash my tires
while I sleep (on those rare occasions when I have time to rest these days :-).

==============================================================================

Q89: What's the difference between C++ and Smalltalk?

The most important differences are:

 * static typing vs dynamic typing?
 * must inheritance be used for subtyping only?
 * value vs reference semantics?

The first two differences are illuminated in the remainder of this section; the
third point is the subject of the section that follows.

If you're a Smalltalk programmer who wants to learn C++, you'd be very wise to
study the next three FAQs carefully.

==============================================================================

Q90: What is "static typing", and how is it similar/dissimilar to Smalltalk?

Static typing says the compiler checks the type-safety of every operation
STATICALLY (at compile-time), rather than to generate code which will check
things at run-time.  For example, with static typing, the signature matching of
fn arguments is checked, and an improper match is flagged as an error by the
COMPILER, not at run-time.

In OO code, the most common "typing mismatch" is invoking a member function
against an object which isn't prepared to handle the operation.  E.g., if class
"Fred" has member fn "f()" but not "g()", and "fred" is an instance of class
"Fred", then "fred.f()" is legal and "fred.g()" is illegal.  C++ (statically
typed) catches the error at compile time, and Smalltalk (dynamically typed)
catches the error at run-time.  (Technically speaking, C++ is like Pascal
--PSEUDO statically typed-- since ptr casts and unions can be used to violate
the typing system; which reminds me: only use ptr casts and unions as often as
you use "goto"s).

==============================================================================

Q91: Which is a better fit for C++: "static typing" or "dynamic typing"?

If you want to use C++ most effectively, use it as a statically typed language.

C++ is flexible enough that you can (via ptr casts, unions, and #defines) make
it "look" like Smalltalk.  But don't.  Which reminds me: try to avoid #define.

There are places where ptr casts and unions are necessary and even wholesome,
but they should be used carefully and sparingly.  A ptr cast tells the compiler
to believe you.  An incorrect ptr cast might corrupt your heap, scribble into
memory owned by other objects, call nonexistent methods, and cause general
failures.  It's not a pretty sight.  If you avoid these and related constructs,
you can make your C++ code both safer and faster, since anything that can be
checked at compile time is something that doesn't have to be done at run-time.

Even if you're in love with dynamic typing, please avoid it in C++, or else
please consider using another language that better supports your desire to
defer typing decisions to run-time.  C++ performs 100% of its type checking at
compile time; it has NO built-in mechanism to do ANY type checking at run-time.
If you use C++ as a dynamically typed OOPL, your life is in your own hands.

==============================================================================

Q92: How can you tell if you have a dynamically typed C++ class library?

Hint #1: when everything is derived from a single root class, usually "Object."
Hint #2: when the container classes (List, Stack, Set, etc) are non-templates.
Hint #3: when the container classes (List, Stack, Set, etc) insert/extract
elements as pointers to "Object" (you can put an Apple into such a container,
but when you get it out, the compiler knows only that it is derived from
Object, so you have to use a pointer cast to convert it back to an Apple*; and
you better pray a lot that it really IS an Apple, cause your blood is on your
own head).

You can make the pointer cast "safe" by using "dynamic_cast" (added to the
language in 1994), but this dynamic testing is just that: dynamic.  This
coding style is the essence of dynamic typing in C++.  You call a function
that says "convert this Object into an Apple or give me NULL if its not an
Apple," and you've got dynamic typing: you don't know what will happen until
run-time.

When you use with templates to implement your containers, the C++ compiler can
statically validate 99% of an application's typing information (the figure
"99%" is apocryphal; some claim they always get 100%, those who need
persistence get something less than 100% static type checking).  The point is:
C++ gets genericity from templates, not from inheritance.

==============================================================================

Q93: How do you use inheritance in C++, and is that different from Smalltalk?

Some people believe that the purpose of inheritance is code reuse.  In C++,
this is wrong.  Stated plainly, "inheritance is not 'for' code reuse."

The purpose of inheritance in C++ is to express interface compliance
(subtyping), not to get code reuse.  In C++, code reuse usually comes via
composition rather than via inheritance.  In other words, inheritance is mainly
a specification technique rather than an implementation technique.

This is a major difference with Smalltalk, where there is only one form of
inheritance (C++ provides "private" inheritance to mean "share the code but
don't conform to the interface", and "public" inheritance to mean "kind-of").
The Smalltalk language proper (as opposed to coding practice) allows you to
have the EFFECT of "hiding" an inherited method by providing an override that
calls the "does not understand" method.  Furthermore Smalltalk allows a
conceptual "is-a" relationship to exist APART from the subclassing hierarchy
(subtypes don't have to be subclasses; e.g., you can make something that is-a
Stack yet doesn't inherit from class Stack).

In contrast, C++ is more restrictive about inheritance: there's no way to make
a "conceptual is-a" relationship without using inheritance (the C++ work-around
is to separate interface from implementation via ABCs).  The C++ compiler
exploits the added semantic information associated with public inheritance to
provide static typing.

==============================================================================

Q94: What are the practical consequences of diffs in Smalltalk/C++
   inheritance?

Smalltalk lets you make a subtype that isn't a subclass, and allows you to make
a subclass that isn't a subtype.  This allows Smalltalk programmers to be very
carefree in putting data (bits, representation, data structure) into a class
(e.g., you might put a linked list into a Stack class).  After all, if someone
wants an array-based-Stack, they don't have to inherit from Stack; they could
inherit such a class from Array if desired, even though an ArrayBasedStack is
NOT a kind-of Array!

In C++, you can't be nearly as carefree.  Only mechanism (method code), but not
representation (data bits) can be overridden in subclasses.  Therefore you're
usually better off NOT putting the data structure in a class.  This leads to a
stronger reliance on Abstract Base Classes (ABCs).

I like to think of the difference between an ATV and a Maseratti.  An ATV (all
terrain vehicle) is more fun, since you can "play around" by driving through
fields, streams, sidewalks, and the like.  A Maseratti, on the other hand, gets
you there faster, but it forces you to stay on the road.  My advice to C++
programmers is simple: stay on the road.  Even if you're one of those people
who like the "expressive freedom" to drive through the bushes, don't do it in
C++; it's not a good fit.

==============================================================================

Q95: Do you need to learn a "pure" OOPL before you learn C++?

No (in fact, doing so might actually hurt you).

(Note that Smalltalk is a "pure" OOPL, and C++ is a "hybrid" OOPL).  Before
reading this, please read the previous FAQs on the difference between C++ and
Smalltalk.

The "purity" of the OOPL doesn't make the transition to C++ any easier.  In
fact, the typical use of dynamic typing and non-subtyping inheritance can make
it even harder for Smalltalk programmers to learn C++.  Paradigm Shift, Inc.,
has taught OO technology to literally thousands of people, and we have noticed
that people who want to learn C++ from a Smalltalk background usually have just
as hard a time as those who've never seen inheritance before.  In fact, those
with extensive experience with a dynamically typed OOPL (usually but not always
Smalltalk) might even have a HARDER time, since it's harder to UNLEARN habits
than it is to learn the statically typed way from the beginning.

==============================================================================

Q96: What is the NIHCL?  Where can I get it?

NIHCL stands for "national-institute-of-health's-class-library."
it can be acquired via anonymous ftp from [128.231.128.7]
in the file pub/NIHCL/nihcl-3.0.tar.Z

NIHCL (some people pronounce it "N-I-H-C-L," others pronounce it like "nickel")
is a C++ translation of the Smalltalk class library.  There are some ways where
NIHCL's use of dynamic typing helps (e.g., persistent objects).  There are also
places where its use of dynamic typing creates tension with the static typing
of the C++ language.

See previous FAQs on Smalltalk for more.

==============================================================================
SECTION 16: Reference and value semantics
==============================================================================

Q97: What is value and/or reference semantics, and which is best in C++?

With reference semantics, assignment is a pointer-copy (i.e., a REFERENCE).
Value (or "copy") semantics mean assignment copies the value, not just the
pointer.  C++ gives you the choice: use the assignment operator to copy the
value (copy/value semantics), or use a ptr-copy to copy a pointer (reference
semantics).  C++ allows you to override the assignment operator to do anything
your heart desires, however the default (and most common) choice is to copy the
VALUE.

Pros of reference semantics: flexibility and dynamic binding (you get dynamic
binding in C++ only when you pass by ptr or pass by ref, not when you pass by
value).

Pros of value semantics: speed.  "Speed" seems like an odd benefit to for a
feature that requires an object (vs a ptr) to be copied, but the fact of the
matter is that one usually accesses an object more than one copies the object,
so the cost of the occasional copies is (usually) more than offset by the
benefit of having an actual object rather than a ptr to an object.

There are three cases when you have an actual object as opposed to a pointer to
an object: local vars, global/static vars, and fully contained member objects
in a class.  The most important of these is the last ("composition").

More info about copy-vs-reference semantics is given in the next FAQs.  Please
read them all to get a balanced perspective.  The first few have intentionally
been slanted toward value semantics, so if you only read the first few of the
following FAQs, you'll get a warped perspective.

Assignment has other issues (e.g., shallow vs deep copy) which are not covered
here.

==============================================================================

Q98: What is "virtual data," and how-can / why-would I use it in C++?

Virtual data allows a derived class to change the exact class of a base class's
member object.  Virtual data isn't strictly "supported" by C++, however it
can be simulated in C++.  It ain't pretty, but it works.

To simulate virtual data in C++, the base class must have a pointer to the
member object, and the derived class must provide a "new" object to be pointed
to by the base class's pointer.  The base class would also have one or more
normal constructors that provide their own referrent (again via "new"), and the
base class's destructor would "delete" the referent.

For example, class "Stack" might have an Array member object (using a pointer),
and derived class "StretchableStack" might override the base class member data
from "Array" to "StretchableArray".  For this to work, StretchableArray would
have to inherit from Array, so Stack would have an "Array*".  Stack's normal
constructors would initialize this "Array*" with a "new Array", but Stack would
also have a (possibly "protected:") constructor that would accept an "Array*"
from a derived class.  StretchableArray's constructor would provide a "new
StretchableArray" to this special constructor.

Pros:
 * Easier implementation of StretchableStack (most of the code is inherited).
 * Users can pass a StretchableStack as a kind-of Stack.

Cons:
 * Adds an extra layer of indirection to access the Array.
 * Adds some extra freestore allocation overhead (both new and delete).
 * Adds some extra dynamic binding overhead (reason given in next FAQ).

In other words, we succeeded at making OUR job easier as the implementor of
StretchableStack, but all our users pay for it.  Unfortunately the extra
overhead was imposed on both users of StretchableStack AND on users of Stack.

See the FAQ after the next to find out how much the users "pay."  Also: PLEASE
read the few FAQs that follow the next one too (YOU WILL NOT GET A BALANCED
PERSPECTIVE WITHOUT THE OTHERS).

==============================================================================

Q99: What's the difference between virtual data and dynamic data?

The easiest way to see the distinction is by an analogy with "virtual fns":
A virtual member fn means the declaration (signature) must stay the same in
subclasses, but the defn (body) can be overridden.  The overriddenness of an
inherited member fn is a static property of the subclass; it doesn't change
dynamically throughout the life of any particular object, nor is it possible
for distinct objects of the subclass to have distinct defns of the member fn.

Now go back and re-read the previous paragraph, but make these substitutions:
 * "member fn" --> "member object"
 * "signature" --> "type"
 * "body"      --> "exact class'
After this, you'll have a working definition of virtual data.

Another way to look at this is to distinguish "per-object" member functions
from "dynamic" member functions.  A "per-object" member fn is a member fn that
is potentially different in any given instance of an object, and could be
implemented by burying a function ptr in the object; this pointer could be
"const", since the pointer will never be changed throughout the object's life.
A "dynamic" member fn is a member fn that will change dynamically over time;
this could also be implemented by a function ptr, but the fn ptr would not be
const.

Extending the analogy, this gives us three distinct concepts for data members:
 * virtual data: the defn ("class") of the member object is overridable in
   subclasses provided its declaration ("type") remains the same, and this
   overriddenness is a static property of the subclass.
 * per-object-data: any given object of a class can instantiate a different
   conformal (same type) member object upon initialization (usually a "wrapper"
   object), and the exact class of the member object is a static property of
   the object that wraps it.
 * dynamic-data: the member object's exact class can change dynamically over
   time.

The reason they all look so much the same is that none of this is "supported"
in C++.  It's all merely "allowed," and in this case, the mechanism for faking
each of these is the same: a ptr to a (probably abstract) base class.  In a
language that made these "first class" abstraction mechanisms, the difference
would be more striking, since they'd each have a different syntactic variant.

==============================================================================

Q100: Should I normally use pointers to freestore allocated objects for my
   data members, or should I use "composition"?

Composition.

Your member objects should normally be "contained" in the composite object (but
not always; "wrapper" objects are a good example of where you want a ptr/ref;
also the N-to-1-uses-a relationship needs something like a ptr/ref).

There are three reasons why fully contained member objects ("composition") has
better performance than ptrs to freestore-allocated member objects:

 * Extra layer to indirection every time you need to access the member object.
 * Extra freestore allocations ("new" in constructor, "delete" in destructor).
 * Extra dynamic binding (reason given below).

==============================================================================

Q101: What are relative costs of the 3 performance hits associated with
   allocating member objects from the freestore?

The three performance hits are enumerated in the previous FAQ:
 * By itself, an extra layer of indirection is small potatoes.
 * Freestore allocations can be a performance issue (the performance of the
   typical implementation of malloc degrades when there are many allocations;
   OO s/w can easily become "freestore bound" unless you're careful).
 * The extra dynamic binding comes from having a ptr rather than an object.
   Whenever the C++ compiler can know an object's EXACT class, virtual fn
   calls can be STATICALLY bound, which allows inlining.  Inlining allows
   zillions (would you believe half a dozen :-) optimization opportunities
   such as procedural integration, register lifetime issues, etc.  The C++
   compiler can know an object's exact class in three circumstances: local
   variables, global/static variables, and fully-contained member objects.

Thus fully-contained member objects allow significant optimizations that
wouldn't be possible under the "member objects-by-ptr" approach.  This is the
main reason that languages which enforce reference-semantics have "inherent"
performance challenges.

NOTE: PLEASE READ THE NEXT THREE FAQs TO GET A BALANCED PERSPECTIVE!

==============================================================================

Q102: Are "inline virtual" member fns ever actually "inlined"?

Yes but...

A virtual call via a ptr or ref is always resolved dynamically, which can never
be inlined.  Reason: the compiler can't know which actual code to call until
run-time (i.e., dynamically), since the code may be from a derived class that
was created after the caller was compiled.

Therefore the only time an inline virtual call can be inlined is when the
compiler knows the "exact class" of the object which is the target of the
virtual function call.  This can happen only when the compiler has an actual
object rather than a pointer or reference to an object.  I.e., either with a
local object, a global/static object, or a fully contained object inside a
composite.

Note that the difference between inlining and non-inlining is normally MUCH
more significant than the difference between a regular fn call and a virtual fn
call.  For example, the difference between a regular fn call and a virtual fn
call is often just two extra memory references, but the difference between an
inline function and a non-inline function can be as much as an order of
magnitude (for zillions of calls to insignificant member fns, loss of inlining
virtual fns can result in 25X speed degradation!  [Doug Lea, "Customization in
C++," proc Usenix C++ 1990]).

A practical consequence of this insight: don't get bogged down in the endless
debates (or sales tactics!) of compiler/language vendors who compare the cost
of a virtual function call on their language/compiler with the same on another
language/compiler.  Such comparisons are largely meaningless when compared with
the ability of the language/compiler to "inline expand" member function calls.
I.e., many language implementation vendors make a big stink about how good
their dispatch strategy is, but if these implementations don't INLINE method
calls, the overall system performance would be poor, since it is inlining --NOT
dispatching-- that has the greatest performance impact.

NOTE: PLEASE READ THE NEXT TWO FAQs TO SEE THE OTHER SIDE OF THIS COIN!

==============================================================================

Q103: Sounds like I should never use reference semantics, right?

Wrong.

Reference semantics are A Good Thing.  We can't live without pointers.  We just
don't want our s/w to be One Gigantic Rats Nest Of Pointers.  In C++, you can
pick and choose where you want reference semantics (ptrs/refs) and where you'd
like value semantics (where objects physically contain other objects etc).  In
a large system, there should be a balance.  However if you implement absolutely
EVERYTHING as a pointer, you'll get enormous speed hits.

Objects near the problem skin are larger than higher level objects.  The
IDENTITY of these "problem space" abstractions is usually more important than
their "value."  Thus reference semantics should be used for problem-space
objects.

Note that these problem space objects are normally at a higher level of
abstraction than the solution space objects, so the problem space objects
normally have a relatively lower frequency of interaction.  Therefore C++ gives
us an IDEAL situation: we choose reference semantics for objects that need
unique identity or that are too large to copy, and we can choose value
semantics for the others.  Thus the highest frequency objects will end up with
value semantics, since we install flexibility where it doesn't hurt us (only),
and we install performance where we need it most!

These are some of the many issues the come into play with real OO design.
OO/C++ mastery takes time and high quality training.  If you want a powerful
tool, you've got to invest.

           <<<<DON'T STOP NOW!  READ THE NEXT FAQ TOO!!>>>>

==============================================================================

Q104: Does the poor performance of ref semantics mean I should pass-by-value?

Nope.

The previous FAQ were talking about MEMBER OBJECTS, not parameters.  Generally,
objects that are part of an inheritance hierarchy should be passed by ref or by
ptr, NOT by value, since only then do you get the (desired) dynamic binding
(pass-by-value doesn't mix with inheritance, since larger subclass objects get
"sliced" when passed by value as a base class object).

Unless compelling reasons are given to the contrary, member objects should be
by value and parameters should be by reference.  The discussion in the previous
few FAQs indicates some of the "compelling reasons" for when member objects
should be by reference.

--
Paradigm Shift, Inc. / P.O. Box 5108 / Potsdam, NY  13676
Voice: 315-353-6100 / FAX: 315-353-6110

From csus.edu!csulb.edu!info.ucla.edu!library.ucla.edu!newsfeed.internetmci.com!news.mathworks.com!news.kei.com!ub!library.erc.clarkson.edu!sun.soe.clarkson.edu!cline Sun Oct 15 13:08:13 1995
From: cline@sun.soe.clarkson.edu (Marshall Cline)
Newsgroups: comp.lang.c++
Subject: C++ FAQ: posting #4/4
Followup-To: comp.lang.c++
Date: 2 Oct 1995 21:32:30 GMT
Organization: Paradigm Shift, Inc (OO consulting/training)
Lines: 823
Sender: cline@sun.soe.clarkson.edu
Distribution: world
Expires: +1 month
Message-ID: <44plpe$kg2@library.erc.clarkson.edu>
Reply-To: cline@parashift.com (Marshall Cline)
NNTP-Posting-Host: sun.soe.clarkson.edu
Summary: Please read this before posting to comp.lang.c++
Status: O

comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
Copyright (C) 1991-95 Marshall P. Cline, Ph.D.
Posting 4 of 4.
Posting #1 explains copying permissions, (no)warranty, table-of-contents, etc

==============================================================================
SECTION 17: Linkage-to/relationship-with C
==============================================================================

Q105: How can I call a C function "f(int,char,float)" from C++ code?

Tell the C++ compiler that it is a C function:
	extern "C" void f(int,char,float);

Be sure to include the full function prototype.  A block of many C functions
can be grouped via braces, as in:

	extern "C" {
	  void* malloc(size_t);
	  char* strcpy(char* dest, const char* src);
	  int   printf(const char* fmt, ...);
	}

==============================================================================

Q106: How can I create a C++ function "f(int,char,float)" that is callable by
   my C code?

The C++ compiler must know that "f(int,char,float)" is to be called by a C
compiler using the same "extern C" construct detailed in the previous FAQ.
Then you define the function in your C++ module:

	void f(int x, char y, float z)
	{
	  //...
	}

The "extern C" line tells the compiler that the external information sent to
the linker should use C calling conventions and name mangling (e.g., preceded
by a single underscore).  Since name overloading isn't supported by C, you
can't make several overloaded fns simultaneously callable by a C program.

Caveats and implementation dependencies:
 * your "main()" should be compiled with your C++ compiler (for static init).
 * your C++ compiler should direct the linking process (for special libraries).
 * your C and C++ compilers may need to come from same vendor and have
   compatible versions (i.e., needs same calling convention, etc.).

==============================================================================

Q107: Why's the linker giving errors for C/C++ fns being called from C++/C
   fns?

See the previous two FAQs on how to use "extern "C"."

==============================================================================

Q108: How can I pass an object of a C++ class to/from a C function?

Here's an example:

	/****** C/C++ header file: Fred.h ******/
	#ifdef __cplusplus    /*"__cplusplus" is #defined if/only-if compiler is C++*/
	  extern "C" {
	#endif

	#ifdef __STDC__
	  extern void c_fn(struct Fred*);	/* ANSI-C prototypes */
	  extern struct Fred* cplusplus_callback_fn(struct Fred*);
	#else
	  extern void c_fn();			/* K&R style */
	  extern struct Fred* cplusplus_callback_fn();
	#endif

	#ifdef __cplusplus
	  }
	#endif

	#ifdef __cplusplus
	  class Fred {
	  public:
	    Fred();
	    void wilma(int);
	  private:
	    int a_;
	  };
	#endif

"Fred.C" would be a C++ module:

	#include "Fred.h"
	Fred::Fred() : a_(0) { }
	void Fred::wilma(int a) : a_(a) { }

	Fred* cplusplus_callback_fn(Fred* fred)
	{
	  fred->wilma(123);
	  return fred;
	}

"main.C" would be a C++ module:

	#include "Fred.h"

	int main()
	{
	  Fred fred;
	  c_fn(&fred);
	  return 0;
	}

"c-fn.c" would be a C module:

	#include "Fred.h"
	void c_fn(struct Fred* fred)
	{
	  cplusplus_callback_fn(fred);
	}

Passing ptrs to C++ objects to/from C fns will FAIL if you pass and get back
something that isn't EXACTLY the same pointer.  For example, DON'T pass a base
class ptr and receive back a derived class ptr, since your C compiler won't
understand the pointer conversions necessary to handle multiple and/or virtual
inheritance.

==============================================================================

Q109: Can my C function access data in an object of a C++ class?

Sometimes.

(First read the previous FAQ on passing C++ objects to/from C functions.)

You can safely access a C++ object's data from a C function if the C++ class:
 * has no virtual functions (including inherited virtual fns)
 * has all its data in the same access-level section (private/protected/public)
 * has no fully-contained subobjects with virtual fns

If the C++ class has any base classes at all (or if any fully contained
subobjects have base classes), accessing the data will TECHNICALLY be
non-portable, since class layout under inheritance isn't imposed by the
language.  However in practice, all C++ compilers do it the same way: the base
class object appears first (in left-to-right order in the event of multiple
inheritance), and subobjects follow.

Furthermore, if the class (or any base class) contains any virtual functions,
you can often (but less than always) assume a "void*" appears in the object
either at the location of the first virtual function or as the first word in
the object.  Again, this is not required by the language, but it is the way
"everyone" does it.

If the class has any virtual base classes, it is even more complicated and less
portable.  One common implementation technique is for objects to contain an
object of the virtual base class (V) last (regardless of where "V" shows up as
a virtual base class in the inheritance hierarchy).  The rest of the object's
parts appear in the normal order.  Every derived class that has V as a virtual
base class actually has a POINTER to the V part of the final object.

==============================================================================

Q110: Why do I feel like I'm "further from the machine" in C++ as opposed to
   C?

Because you are.

As an OOPL, C++ allows you to model the problem domain itself, which allows you
to program in the language of the problem domain rather than in the language of
the solution domain.

One of C's great strengths is the fact that it has "no hidden mechanism": what
you see is what you get.  You can read a C program and "see" every clock cycle.
This is not the case in C++; old line C programmers (such as many of us once
were) are often ambivalent (can anyone say, "hostile") about this feature, but
they soon realize that it provides a level of abstraction and economy of
expression which lowers maintenance costs without destroying run-time
performance.

Naturally you can write bad code in any language; C++ doesn't guarantee any
particular level of quality, reusability, abstraction, or any other measure of
"goodness."  C++ doesn't try to make it impossible for bad programmers to write
bad programs; it enables reasonable developers to create superior software.

==============================================================================
SECTION 18: Pointers to member functions
==============================================================================

Q111: Is the type of "ptr-to-member-fn" different from "ptr-to-fn"?

Yep.

Consider the following function:

	int f(char a, float b);

If this is an ordinary function, its type is:    int (*)      (char,float);
If this is a method of class Fred, its type is:  int (Fred::*)(char,float);

==============================================================================

Q112: How do I pass a ptr to member fn to a signal handler, X event callback,
   etc?

Don't.

Because a member function is meaningless without an object to invoke it on, you
can't do this directly (if The X Windows System was rewritten in C++, it would
probably pass references to OBJECTS around, not just pointers to fns; naturally
the objects would embody the required function and probably a whole lot more).

As a patch for existing software, use a top-level (non-member) function as a
wrapper which takes an object obtained through some other technique (held in a
global, perhaps).  The top-level function would apply the desired member
function against the global object.

E.g., suppose you want to call Fred::memfn() on interrupt:

	class Fred {
	public:
	  void memfn();
	  static void staticmemfn();	//a static member fn can handle it
	  //...
	};

	//wrapper fn remembers the object on which to invoke memfn in a global:
	Fred* object_which_will_handle_signal;
	void Fred_memfn_wrapper() { object_which_will_handle_signal->memfn(); }

	main()
	{
	  /* signal(SIGINT, Fred::memfn); */   //Can NOT do this
	  signal(SIGINT, Fred_memfn_wrapper);  //Ok
	  signal(SIGINT, Fred::staticmemfn);   //Also Ok
	}

Note: static member functions do not require an actual object to be invoked, so
ptrs-to-static-member-fns are type compatible with regular ptrs-to-fns (see ARM
["Annotated Reference Manual"] p.25, 158).

==============================================================================

Q113: Why do I keep getting compile errors (type mismatch) when I try to use a
   member function as an interrupt service routine? 

This is a special case of the previous two questions, therefore read the
previous two answers first.

Non-static member functions have a hidden parameter that corresponds to the
'this' pointer.  The 'this' pointer points to the instance data for the
object.  The interrupt hardware/firmware in the system is not capable of
providing the 'this' pointer argument.  You must use "normal" functions (non
class members) or static member functions as interrupt service routines.

One possible solution is to use a static member as the interrupt service
routine and have that function look somewhere to find the instance/member pair
that should be called on interrupt.  Thus the effect is that a normal method
is invoked on an interrupt, but for technical reasons you need to call an
intermediate function first.

==============================================================================

Q114: Why am I having trouble taking the address of a C++ function?

This is a corollary to the previous FAQ.

Long answer: In C++, member fns have an implicit parameter which points to the
object (the "this" ptr inside the member fn).  Normal C fns can be thought of
as having a different calling convention from member fns, so the types of their
ptrs (ptr-to-member-fn vs ptr-to-fn) are different and incompatible.  C++
introduces a new type of ptr, called a ptr-to-member, which can be invoked only
by providing an object (see ARM ["Annotated Reference Manual"] 5.5).

NOTE: do NOT attempt to "cast" a ptr-to-mem-fn into a ptr-to-fn; the result is
undefined and probably disastrous.  E.g., a ptr-to- member-fn is NOT required
to contain the machine addr of the appropriate fn (see ARM, 8.1.2c, p.158).  As
was said in the last example, if you have a ptr to a regular C fn, use either a
top-level (non-member) fn, or a "static" (class) member fn.

==============================================================================

Q115: How do I declare an array of pointers to member functions?

Keep your sanity with "typedef".

	class Fred {
	public:
	  int f(char x, float y);
	  int g(char x, float y);
	  int h(char x, float y);
	  int i(char x, float y);
	  //...
	};

	typedef  int (Fred::*FredPtr)(char x, float y);

Here's the array of pointers to member functions:

	FredPtr a[4] = { &Fred::f, &Fred::g, &Fred::h, &Fred::i };

To call one of the member functions on object "fred":

	void userCode(Fred& fred, int methodNum, char x, float y)
	{
	  //assume "methodNum" is between 0 and 3 inclusive
	  (fred.*a[methodNum])(x, y);
	}

You can make the call somewhat clearer using a #define:

	#define  callMethod(object,ptrToMethod)   ((object).*(ptrToMethod))
	callMethod(fred, a[methodNum]) (x, y);

==============================================================================
SECTION 19: Container classes and templates
==============================================================================

Q116: How can I insert/access/change elements from a linked
   list/hashtable/etc?

I'll use an "inserting into a linked list" as a prototypical example.  It's easy
to allow insertion at the head and tail of the list, but limiting ourselves to
these would produce a library that is too weak (a weak library is almost worse
than no library).

This answer will be a lot to swallow for novice C++'ers, so I'll give a couple
of options.  The first option is easiest; the second and third are better.

[1] Empower the "List" with a "current location," and methods such as
advance(), backup(), atEnd(), atBegin(), getCurrElem(), setCurrElem(Elem),
insertElem(Elem), and removeElem().  Although this works in small examples, the
notion of "a" current position makes it difficult to access elements at two or
more positions within the List (e.g., "for all pairs x,y do the following...").

[2] Remove the above methods from the List itself, and move them to a separate
class, "ListPosition."  ListPosition would act as a "current position" within a
List.  This allows multiple positions within the same List.  ListPosition would
be a friend of List, so List can hide its innards from the outside world (else
the innards of List would have to be publicized via public methods in List).
Note: ListPosition can use operator overloading for things like advance() and
backup(), since operator overloading is syntactic sugar for normal methods.

[3] Consider the entire iteration as an atomic event, and create a class
template to embodies this event.  This enhances performance by allowing the
public access methods (which may be virtual fns) to be avoided during the inner
loop.  Unfortunately you get extra object code in the application, since
templates gain speed by duplicating code.  For more, see [Koenig, "Templates as
interfaces," JOOP, 4, 5 (Sept 91)], and [Stroustrup, "The C++ Programming
Language Second Edition," under "Comparator"].

==============================================================================

Q117: What's the idea behind "templates"?

A template is a cookie-cutter that specifies how to cut cookies that all look
pretty much the same (although the cookies can be made of various kinds of
dough, they'll all have the same basic shape).  In the same way, a class
template is a cookie cutter to description of how to build a family of classes
that all look basically the same, and a function template describes how to
build a family of similar looking functions.

Class templates are often used to build type safe containers (although this
only scratches the surface for how they can be used).

==============================================================================

Q118: What's the syntax / semantics for a "function template"?

Consider this function that swaps its two integer arguments:

	void swap(int& x, int& y)
	{
	  int tmp = x;
	  x = y;
	  y = tmp;
	}

If we also had to swap floats, longs, Strings, Sets, and FileSystems, we'd get
pretty tired of coding lines that look almost identical except for the type.
Mindless repetition is an ideal job for a computer, hence a function template:

	template<class T>
	void swap(T& x, T& y)
	{
	  T tmp = x;
	  x = y;
	  y = tmp;
	}

Every time we used "swap()" with a given pair of types, the compiler will go to
the above definition and will create yet another "template function" as an
instantiation of the above.  E.g.,

	main()
	{
	  int    i,j;  /*...*/  swap(i,j);  //instantiates a swap for "int"
	  float  a,b;  /*...*/  swap(a,b);  //instantiates a swap for "float"
	  char   c,d;  /*...*/  swap(c,d);  //instantiates a swap for "char"
	  String s,t;  /*...*/  swap(s,t);  //instantiates a swap for "String"
	}

(note: a "template function" is the instantiation of a "function template").

==============================================================================

Q119: What's the syntax / semantics for a "class template"?

Consider a container class of that acts like an array of integers:

	//this would go into a header file such as "Array.h"
	class Array {
	public:
	  Array(int len=10)                  : len_(len), data_(new int[len]){}
	 ~Array()                            { delete [] data_; }
	  int len() const                    { return len_;     }
	  const int& operator[](int i) const { data_[check(i)]; }
	        int& operator[](int i)       { data_[check(i)]; }
	  Array(const Array&);
	  Array& operator= (const Array&);
	private:
	  int  len_;
	  int* data_;
	  int  check(int i) const
	    { if (i < 0 || i >= len_) throw BoundsViol("Array", i, len_);
	      return i; }
	};

Just as with "swap()" above, repeating the above over and over for Array of
float, of char, of String, of Array-of-String, etc, will become tedious.

	//this would go into a header file such as "Array.h"
	template<class T>
	class Array {
	public:
	  Array(int len=10)                : len_(len), data_(new T[len]) { }
	 ~Array()                          { delete [] data_; }
	  int len() const                  { return len_;     }
	  const T& operator[](int i) const { data_[check(i)]; }
	        T& operator[](int i)       { data_[check(i)]; }
	  Array(const Array<T>&);
	  Array& operator= (const Array<T>&);
	private:
	  int len_;
	  T*  data_;
	  int check(int i) const
	    { if (i < 0 || i >= len_) throw BoundsViol("Array", i, len_);
	      return i; }
	};

Unlike template functions, template classes (instantiations of class templates)
need to be explicit about the parameters over which they are instantiating:

	main()
	{
	  Array<int>           ai;
	  Array<float>         af;
	  Array<char*>         ac;
	  Array<String>        as;
	  Array< Array<int> >  aai;
	}              // ^^^-- note the space; do NOT use "Array<Array<int>>"
	               //       (the compiler sees ">>" as a single token).

==============================================================================

Q120: What is a "parameterized type"?

Another way to say, "class templates."

A parameterized type is a type that is parameterized over another type or some
value.  List<int> is a type ("List") parameterized over another type ("int").

==============================================================================

Q121: What is "genericity"?

Yet another way to say, "class templates."

Not to be confused with "generality" (which just means avoiding solutions which
are overly specific), "genericity" means class templates.

==============================================================================
SECTION 20: Libraries
==============================================================================

Q122: Where can I get a copy of "STL"?

"STL" is the "Standard Templates Library".  You can get a copy from:

STL HP official site:	ftp://butler.hpl.hp.com/stl
STL code alternate:	ftp://ftp.cs.rpi.edu/stl
STL code + examples:	http://www.cs.rpi.edu/~musser/stl.html

STL hacks for GCC-2.6.3 are part of the GNU libg++ package 2.6.2.1 or later
(and they may be in an earlier version as well).  Thanks to Mike Lindner.

==============================================================================

Q123: Where can I ftp the code that accompanies "Numerical Recipes"?

This software is sold and there for it would be illegal to provide it on the
net.  However, its only about $30.

==============================================================================

Q124: Why is my executable so large?

Many people are surprised by how big executables are, especially if the source
code is trivial.  For example, a simple "hello world" program can generate an
executable that is larger than most people expect (40+K bytes).

One reason executables can be large is that portions of the C++ runtime
library gets linked with your program. How much gets linked in depends on how
much of it you are using, and on how the implementor split up the library into
pieces.  For example, the iostream library is quite large, and consists of
numerous classes and virtual functions. Using any part of it might pull in
nearly all of the iostream code as a result of the interdependencies.

You might be able to make your program smaller by using a dynamically-linked
version of the library instead of the static version.

You have to consult your compiler manuals or the vendor's technical support
for a more detailed answer.

==============================================================================
SECTION 21: Nuances of particular implementations
==============================================================================

Q125: GNU C++ (g++) produces big executables for tiny programs; Why?

libg++ (the library used by g++) was probably compiled with debug info (-g).
On some machines, recompiling libg++ without debugging can save lots of disk
space (~1 Meg; the down-side: you'll be unable to trace into libg++ calls).
Merely "strip"ping the executable doesn't reclaim as much as recompiling
without -g followed by subsequent "strip"ping the resultant "a.out"s.

Use "size a.out" to see how big the program code and data segments really are,
rather than "ls -s a.out" which includes the symbol table.

==============================================================================

Q126: Is there a yacc-able C++ grammar?

Jim Roskind is the author of a yacc grammar for C++. It's roughly compatible
with the portion of the language implemented by USL cfront 2.0 (no templates,
no exceptions, no run-time-type-identification).  Jim's grammar deviates from
C++ in a couple of minor-but-subtle ways.

The grammar can be accessed by anonymous ftp from the following sites:
 * ics.uci.edu (128.195.1.1) in "gnu/c++grammar2.0.tar.Z".
 * mach1.npac.syr.edu (128.230.7.14) in "pub/C++/c++grammar2.0.tar.Z".

==============================================================================

Q127: What is C++ 1.2?  2.0?  2.1?  3.0?

These are not versions of the language, but rather versions of cfront, which
was the original C++ translator implemented by AT&T.  It has become generally
accepted to use these version numbers as if they were versions of the language
itself.

*VERY* roughly speaking, these are the major features:
 * 2.0 includes multiple/virtual inheritance and pure virtual functions.
 * 2.1 includes semi-nested classes and "delete [] ptr_to_array."
 * 3.0 includes fully-nested classes, templates and "i++" vs "++i."
 * 4.0 will include exceptions.

==============================================================================

Q128: If name mangling was standardized, could I link code compiled with
   compilers from different compiler vendors?

Short answer: Probably not.

In other words, some people would like to see name mangling standards
incorporated into the proposed C++ ANSI standards in an attempt to avoiding
having to purchase different versions of class libraries for different
compiler vendors.  However name mangling differences are one of the smallest
differences between implementations, even on the same platform.  Here is a
partial list of other differences:

1) Number and type of hidden arguments to member functions.
   1a) is 'this' handled specially?
   1b) where is the return-by-value pointer passed?
2) Assuming a vtable is used:
   2a) what is its contents and layout?
   2b) where/how is the adjustment to 'this' made for multiple inheritance?
3) How are classes laid out, including:
   3a) location of base classes?
   3b) handling of virtual base classes?
   3c) location of vtable pointers, if vtables are used?
4) Calling convention for functions, including:
   4a) does caller or callee adjust the stack?
   4b) where are the actual parameters placed?
   4c) in what order are the actual parameters passed?
   4d) how are registers saved?
   4e) where does the return value go?
   4f) special rules for passing or returning structs or doubles?
   4g) special rules for saving registers when calling leaf functions?
5) How is the run-time-type-identification laid out?
6) How does the runtime exception handling system know which local objects
   need to be destructed during an exception throw?

==============================================================================
SECTION 22: Miscellaneous technical and environmental issues
==============================================================================
SUBSECTION 22A: Miscellaneous technical issues:
==============================================================================

Q129: Why are classes with static data members getting linker errors?

Static data members must be explicitly defined in exactly one module.  E.g.,

	class Fred {
	public:
	  //...
	private:
	  static int i_;  //declares static data member "Fred::i_"
	  //...
	};

The linker will holler at you ("Fred::i_ is not defined") unless you define (as
opposed to declare) "Fred::i_" in (exactly) one of your source files:

	int Fred::i_ = some_expression_evaluating_to_an_int;
or:
	int Fred::i_;

The usual place to define static data members of class "Fred" is file "Fred.C"
(or "Fred.cpp", etc; whatever filename extension you use).

==============================================================================

Q130: What's the difference between the keywords struct and class?

The members and base classes of a struct are public by default, while in class,
they default to private.  Note: you should make your base classes EXPLICITLY
public, private, or protected, rather than relying on the defaults.

"struct" and "class" are otherwise functionally equivalent.

==============================================================================

Q131: Why can't I overload a function by its return type?

If you declare both "char f()" and "float f()", the compiler gives you an error
message, since calling simply "f()" would be ambiguous.

==============================================================================

Q132: What is "persistence"?  What is a "persistent object"?

A persistent object can live after the program which created it has stopped.
Persistent objects can even outlive different versions of the creating program,
can outlive the disk system, the operating system, or even the hardware on
which the OS was running when they were created.

The challenge with persistent objects is to effectively store their method code
out on secondary storage along with their data bits (and the data bits and
method code of all member objects, and of all their member objects and base
classes, etc).  This is non-trivial when you have to do it yourself.  In C++,
you have to do it yourself.  C++/OO databases can help hide the mechanism for
all this.

==============================================================================

Q133: Why is floating point so inaccurate?  Why doesn't this print 0.43?

	#include<iostream.h> 

	main()
	{
	  float a = 1000.43;
	  float a = 1000.0;
	  cout << a - b << '\n';
	} 

(note, on one C++ implementation, this prints 0.429993) 

Disclaimer: Frustration with rounding/truncation/approximation isn't really a
C++ issue.  It's a computer science issue.  However, people keep asking about
it on comp.lang.c++, so here's a nominal answer.

Answer: Floating point is an approximation.  The IEEE standard for 32 bit
float supports 1 bit of sign, 8 bits of exponent, and 23 bits of mantissa.
Since a normalized binary-point mantissa always has the form 1.xxxxx... the
leading 1 is dropped and you get effectively 24 bits of mantissa.  The number
1000.43 (and many, many others) is not exactly representable in float or
double format.  1000.43 is actually represented as the following bitpattern
(the 's' shows the position of the sign bit, the 'e's show the positions of
the exponent bits, and the 'm's show the positions of the mantissa bits):

    seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm 
    01000100011110100001101110000101 

The shifted mantissa is 1111101000.01101110000101 or 1000 + 7045/16384.  The
fractional part is 0.429992675781.  With 24 bits of mantissa you only get
about 1 part in 16M of precision for float.  The 'double' type provides more
precision (53 bits of mantissa).

==============================================================================
SUBSECTION 22B: Miscellaneous environmental issues:
==============================================================================

Q134: Is there a TeX or LaTeX macro that fixes the spacing on "C++"?

Yes, here are two:

\def\CC{C\raise.22ex\hbox{{\footnotesize +}}\raise.22ex\hbox{\footnotesize +}}

\def\CC{{C\hspace{-.05em}\raisebox{.4ex}{\tiny\bf ++}}}

==============================================================================

Q135: Where can I access C++2LaTeX, a LaTeX pretty printer for C++ source?

Here are a few ftp locations:

Host aix370.rrz.uni-koeln.de   (134.95.80.1) Last updated 15:41 26 Apr 1991
    Location: /tex
      FILE      rw-rw-r--     59855  May  5  1990   C++2LaTeX-1.1.tar.Z
Host utsun.s.u-tokyo.ac.jp   (133.11.11.11) Last updated 05:06 20 Apr 1991
    Location: /TeX/macros
      FILE      rw-r--r--     59855  Mar  4 08:16   C++2LaTeX-1.1.tar.Z
Host nuri.inria.fr   (128.93.1.26) Last updated 05:23  9 Apr 1991
    Location: /TeX/tools
      FILE      rw-rw-r--     59855  Oct 23 16:05   C++2LaTeX-1.1.tar.Z
Host iamsun.unibe.ch   (130.92.64.10) Last updated 05:06  4 Apr 1991
    Location: /TeX
      FILE      rw-r--r--     59855  Apr 25  1990   C++2LaTeX-1.1.tar.Z
Host iamsun.unibe.ch   (130.92.64.10) Last updated 05:06  4 Apr 1991
    Location: /TeX
      FILE      rw-r--r--     51737  Apr 30  1990
      C++2LaTeX-1.1-PL1.tar.Z
Host tupac-amaru.informatik.rwth-aachen.de   (192.35.229.9) Last updated 05:07 18 Apr 1991
    Location: /pub/textproc/TeX
      FILE      rw-r--r--     72957  Oct 25 13:51  C++2LaTeX-1.1-PL4.tar.Z
Host wuarchive.wustl.edu   (128.252.135.4) Last updated 23:25 30 Apr 1991
    Location: /packages/tex/tex/192.35.229.9/textproc/TeX
      FILE      rw-rw-r--     49104  Apr 10  1990   C++2LaTeX-PL2.tar.Z
      FILE      rw-rw-r--     25835  Apr 10  1990   C++2LaTeX.tar.Z
Host tupac-amaru.informatik.rwth-aachen.de   (192.35.229.9) Last updated 05:07 18 Apr 1991
    Location: /pub/textproc/TeX
      FILE rw-r--r-- 74015  Mar 22 16:23 C++2LaTeX-1.1-PL5.tar.Z
    Location: /pub
      FILE rw-r--r-- 74015  Mar 22 16:23 C++2LaTeX-1.1-PL5.tar.Z
Host sol.cs.ruu.nl   (131.211.80.5) Last updated 05:10 15 Apr 1991
    Location: /TEX/TOOLS
      FILE      rw-r--r--     74015  Apr  4 21:02x   C++2LaTeX-1.1-PL5.tar.Z
Host tupac-amaru.informatik.rwth-aachen.de (192.35.229.9) Last updated 05:07 18 Apr 1991
    Location: /pub/textproc/TeX
      FILE      rw-r--r--      4792  Sep 11  1990 C++2LaTeX-1.1-patch#1
      FILE      rw-r--r--      2385  Sep 11  1990 C++2LaTeX-1.1-patch#2
      FILE      rw-r--r--      5069  Sep 11  1990 C++2LaTeX-1.1-patch#3
      FILE      rw-r--r--      1587  Oct 25 13:58 C++2LaTeX-1.1-patch#4
      FILE      rw-r--r--      8869  Mar 22 16:23 C++2LaTeX-1.1-patch#5
      FILE      rw-r--r--      1869  Mar 22 16:23 C++2LaTeX.README
Host rusmv1.rus.uni-stuttgart.de   (129.69.1.12) Last updated 05:13 13 Apr 1991
    Location: /soft/tex/utilities
      FILE      rw-rw-r--    163840  Jul 16  1990   C++2LaTeX-1.1.tar

==============================================================================

Q136: Where can I access "tgrind," a pretty printer for C++/C/etc source?

"tgrind" reads a C++ source file, and spits out something that looks pretty on
most Unix printers.  It usually comes with the public distribution of TeX and
LaTeX; look in the directory: "...tex82/contrib/van/tgrind".  A more up-to-date
version of tgrind by Jerry Leichter can be found on: venus.ycc.yale.edu in
[.TGRIND].

==============================================================================

Q137: Is there a C++-mode for GNU emacs?  If so, where can I get it?

Yes, there is a C++-mode for GNU emacs.

The latest and greatest version of C++-mode (and c-mode) is implemented in the
file cc-mode.el.  It is an extension of Detlef & Clamen's version.
A version is included with emacs.  Newer version are availiable from
the elisp archives.

==============================================================================

Q138: Where can I get OS-specific FAQs answered (e.g.,BC++,DOS,Windows,etc)?

See one of the following:
 * comp.os.msdos.programmer
 * comp.windows.ms.programmer
 * comp.unix.programmer

[If anyone has an email address for a BC++, VC++, or Semantic C++ bug list
and/or discussion mailing list, please let me know how to subscribe, and I'll
mention it here].

==============================================================================

Q139: Why does my DOS C++ program says "Sorry: floating point code not
   linked"?

The compiler attempts to save space in the executable by not including the
float-to-string format conversion routines unless they are necessary, but
sometimes it guesses wrong, and gives you the above error message.  You can fix
this by (1) using <iostream.h> instead of <stdio.h>, or (2) by including the
following function somewhere in your compilation (but don't call it!):

	static void dummyfloat(float *x) { float y; dummyfloat(&y); }

See FAQ on stream I/O for more reasons to use <iostream.h> vs <stdio.h>.

==============================================================================

Q140: Why does my BC++ Windows app crash when I'm not running the BC45 IDE?

If you're using BC++ for a Windows app, and it works ok as long as you have the
BC45 IDE running, but when the BC45 IDE is shut down you get an exception
during the creation of a window, then add the following line of code to the
InitMainWindow() method of your application ("YourApp::InitMainWindow()"):

	EnableBWCC(TRUE);

==============================================================================

--
Paradigm Shift, Inc. / P.O. Box 5108 / Potsdam, NY  13676
Voice: 315-353-6100 / FAX: 315-353-6110


From csus.edu!csulb.edu!info.ucla.edu!library.ucla.edu!newsfeed.internetmci.com!tank.news.pipex.net!pipex!in2.uu.net!chronos.synopsys.com!news.synopsys.com!jbuck Tue Sep 19 16:09:02 1995
From: jbuck@synopsys.com (Joe Buck)
Newsgroups: gnu.g++.help,comp.lang.c++,news.answers,comp.answers
Subject: FAQ for g++ and libg++, texinfo version [Revised 01 Sep 1995]
Supersedes: <g++FAQ_08_15_1995_plain@synopsys.com>
Followup-To: poster
Date: 2 Sep 1995 04:53:05 GMT
Organization: Synopsys, Inc.
Lines: 1806
Approved: news-answers-request@MIT.edu
Expires: 1 Oct 1995 00:00:00 GMT
Message-ID: <g++FAQ_09_01_1995_plain@synopsys.com>
References: <g++FAQ_09_01_1995_texi@synopsys.com>
NNTP-Posting-Host: deerslayer.synopsys.com
Originator: jbuck@deerslayer
Xref: csus.edu gnu.g++.help:10817 comp.lang.c++:138752 news.answers:51917 comp.answers:13961
Status: O

Archive-name: g++-FAQ/texi
Last-modified: 01 Sep 1995
Frequency: bimonthly

[ This is the texinfo version.  If you don't know what texinfo is,
  then you probably want to use the companion plain-text version. ]

------------- cut here ----------------------------------------------
\input texinfo.tex      @c -*-texinfo-*-
@c %**start of header
@setfilename g++FAQ.info
@settitle Frequently asked questions about the GNU C++ compiler
@setchapternewpage off
@c version: %W% %G%
@c %**end of header

@iftex
@finalout
@end iftex
@titlepage
@title G++ FAQ
@subtitle Frequently asked questions about the GNU C++ compiler
@subtitle August 15, 1995
@sp 1
@author Joe Buck
@page
@end titlepage

@ifinfo
@node Top, new stuff, (dir), (dir)
@top
@unnumbered Preface
@cindex FAQ for g++, latest version
@cindex Archive site for FAQ lists
@cindex rtfm.mit.edu
@cindex Joe Buck <jbuck@@synopsys.com>
@cindex FAQ for C++
@cindex Marshall Cline [FAQ for comp.lang.c++]
@end ifinfo

This is a list of frequently asked questions (FAQ) for g++ users; thanks to
all those who sent suggestions for improvements.  Thanks to Marcus Speh
for doing the index.

Please send updates and corrections to the FAQ to
@code{jbuck@@synopsys.com}.  Please do @emph{not} use me as a resource
to get your questions answered; that's what gnu.g++.help is for and I
don't have the time to support the net's use of g++.

Many FAQs, including this one, are available on the archive site
rtfm.mit.edu, in the directory @file{pub/usenet/news.answers}.
This FAQ may be found in the subdirectory g++-FAQ.

This FAQ is intended to supplement, not replace, Marshall Cline's
excellent FAQ for the C++ language and for the newsgroup
comp.lang.c++.  Especially if g++ is the first C++
compiler you've ever used, the question ``How do I do <X> with g++?''
is probably really ``How do I do <X> in C++?''.
You can find this FAQ on rtfm.mit.edu under @file{pub/usenet/comp.lang.c++}.
 
@menu
* new stuff::       The latest poop -- gcc-2.7.0
* getting g++::     Obtaining Source Code
* installation::    Installation Issues and Problems
* User Problems::   User Problems
* legalities::      What are the rules for shipping code built with g++ and libg++?
* index::           Concept Index

 --- The Detailed Node Listing ---

New Stuff: The Latest Poop -- Gcc-2.7.0

* for scope::       gcc-2.7.0 breaks declarations in "for" statements!
* version 2.7::     What's new in version 2.7.x of gcc/g++
* repository::      How do I use the new template repository code?
* libstdc++::       The GNU Standard C++ Library

Obtaining Source Code

* latest versions::  What is the latest version of gcc, g++, and libg++?
* g++ for Unix::    How do I get a copy of g++ for Unix?
* g++ for HP::  Getting gcc/g++ for the HP Precision Architecture
* g++ for Solaris 2.x::  Getting gcc/g++ binaries for Solaris 2.x
* g++ for other platforms::  How do I get a copy of g++ for (some other platform)?
* 1.x vs 2.x versions::  But I can only find g++-1.42!

Installation Issues and Problems

* gcc-2 + g++-1::   I can't build g++ 1.x.y with gcc-2.x.y!
* what else do I need?::  OK, I've obtained gcc; what else do I need?
* use GNU linker?::  Should I use the GNU linker, or should I use "collect"?
* Use GNU assembler?::  Should I use the GNU assembler, or my vendor's assembler?
* Use GNU C library?::  Should I use the GNU C library?
* Global constructor problems:: Global constructors aren't being called
* Strange assembler errors:: Strange assembler errors when linking C++ programs
* Other problems building libg++::  
* Rebuild libg++?:: Do I need to rebuild libg++ to go with my new g++?

User Problems

* unused parameter warnings:: How to silence ``unused parameter'' warnings
* jump crosses initialization:: g++ objects to a declaration in a case statement
* 2.5.x changes in overloading:: Changes in function overloading
* Demangler::	    Where can I find a demangler?
* etags for C++::   Where can I find a version of etags for C++?
* static data members::  Linker reports undefined symbols for static data members
* internal compiler error:: What does ``internal compiler error'' mean?
* bug reports::     I think I have found a bug in g++.
* porting to g++::  Porting programs from other compilers to g++
* name mangling::   Why does g++ mangle names differently from other C++ compilers?
* problems linking with other libraries::  Why can't g++ code link with code from other C++ compilers?
* documentation::   What documentation exists for g++ 2.x?
* templates::       Problems with the template implementation
* undefined templates::  I get undefined symbols when using templates
* redundant templates::  I get multiply defined symbols when using templates
* Standard Template Library:: Does g++ support the Standard Template Library?
* agreement with standards::  What are the differences between g++ and the ARM specification of C++?
* compiling standard libraries::  Will g++ compile InterViews?  The NIH class library?
* debugging on SVR4 systems::  Debugging on SVR4 systems
* X11 conflicts with libg++::  Conflict over meaning of String
* assignment to streams::  Why can't I assign one stream to another?
@end menu

@node new stuff, getting g++, Top, Top
@chapter The latest poop -- gcc-2.7.0

This section is intended to describe more recent changes to g++, libg++,
and such.  Some things in this section will eventually move elsewhere.

The big news is that version 2.7.0 has just been released.  This, of
course, means new FAQs.  I haven't had a lot of time to whip out this
section yet, so suggestions for improvement are welcome.

@menu
* for scope::       gcc-2.7.0 breaks declarations in "for" statements!
* version 2.7::     What's new in version 2.7.x of gcc/g++
* repository::      How do I use the new template repository code?
* libstdc++::       The GNU Standard C++ Library
@end menu

@node for scope, version 2.7, new stuff, new stuff
@section gcc-2.7.0 breaks declarations in "for" statements!

@cindex declarations in for statements
@cindex for statements: declarations

gcc-2.7.0 implements the new ANSI/ISO rule on the scope of variables
declared in for loops.

@example
for (int i = 1; i <= 10; i++) @{
        // do something here
@}
foo(i);
@end example

In the above example, most existing C++ compilers would pass the
value 11 to the function @code{foo}.  In gcc 2.7 and in the ANSI/ISO
working paper, the scope of @code{i} is only the for loop body, so
this is an error.  So that old code can be compiled, the new gcc has
a flag @code{-fno-for-scope} that causes the old rule to be used.
@cindex -fno-for-scope

@node version 2.7, repository, for scope, new stuff
@section What's new in version 2.7.0 of gcc/g++

The long-awaited version 2.7.0 of gcc/g++ (along with a matching version
of libg++) have now been released.  This represents a great deal
of work on the part of the g++ maintainers to fix outstanding bugs and
move the compiler closer to the current ANSI/ISO standards committee's
working paper, including supporting many of the new features that have
been added to the language.  I recommend that everyone read the NEWS
file contained in the distribution (and that system administrators make
the file available to their users).  I've borrowed liberally from this
file here.

@cindex C++ working paper
If any features seem unfamiliar, you will probably want to
look at the recently-released public review copy of the C++ Working
Paper.  For PostScript and PDF (Adobe Acrobat) versions, see the
archive at ftp://research.att.com/dist/stdc++/WP.  For HTML and ASCII
versions, see ftp://ftp.cygnus.com/pub/g++.  On the World Wide Web, see
http://www.cygnus.com/~mrs/wp-draft.

@itemize @bullet
@item
@cindex for scope
As described above, the scope of variables declared in the
initialization part of a for statement has been changed; such variables
are now visible only in the loop body.  Use @code{-fno-for-scope} to get
the old behavior.  You'll need this flag to build groff version 1.09,
Ptolemy, and many others.

@item
@cindex vtable duplication
Code that does not use #pragma interface/implementation will most
likely shrink dramatically, as g++ now only emits the vtable for a
class in the translation unit where its first non-inline, non-abstract
virtual function is defined.

@item
@cindex automatic template instantiation
Support for automatic template instantiation has @emph{not} been enabled
in the official distribution, due to a disagreement over design philosophies.
But you can get a patch from Cygnus to turn it on; retrieve the patch
from @file{ftp://ftp.cygnus.com/pub/g++/gcc-2.7.0-repo.gz}.

@item
@cindex exception handling, 2.7.0
Support for exception handling has been improved; more targets are now
supported, and throws will use the RTTI mechanism to match against the
catch parameter type.  You must give the @code{-fhandle-exceptions} to
turn it on.  Optimization is @emph{not supported} with
@code{-fhandle-exceptions}; no need to report this as a bug.  You'll
probably get an internal compiler error if you try it.

For exception handling to work your CPU must be a SPARC, RS6000/PowerPC,
386/486/Pentium, or ARM.  Other platforms are missing the function to
unwind the stack.

@item
@cindex run-time type identification
Support for Run-Time Type Identification has been added with @code{-frtti}.
This support is still in alpha; one major restriction is that any file
compiled with @code{-frtti} must include @code{<typeinfo>} (@emph{not}
@code{typeinfo.h} as the NEWS file says).
Also, all code you link with (including libg++) has to be built with
@code{-frtti}, so it's still tricky to use.

@item
@cindex compiler-generated operators
Synthesis of compiler-generated constructors, destructors and
assignment operators is now deferred until the functions are used.

@item
@cindex assignment in conditional expressions
The parsing of expressions such as @code{a ? b : c = 1}
has changed from
@code{(a ? b : c) = 1} to @code{a : b ? (c = 1)}.  This is a new C/C++
incompatibility brought to you by the ANSI/ISO standards committee.

@item
@cindex new operator keywords
The operator keywords and, and_eq, bitand, bitor, compl, not, not_eq,
or, or_eq, xor and xor_eq are now supported.  Use @code{-ansi} or
@code{-foperator-names} to enable them.

@item
@cindex explicit keyword
The @code{explicit} keyword is now supported.  @code{explicit} is used to mark
constructors and type conversion operators that should not be used
implicitly.

@item
@cindex user-defined type conversion
Handling of user-defined type conversion has been improved.

@item
@cindex explicit template instantiation
Explicit instantiation of template methods is now supported.  Also,
@code{inline template class foo<int>;}
can be used to emit only the vtable
for a template class.

@item
@cindex -fcheck-new
With -fcheck-new, g++ will check the return value of all calls to
operator new, and not attempt to modify a returned null pointer.

@item
collect2 now demangles linker output, and c++filt has become part of
the gcc distribution.

@item
Improvements to template instantiation: only members actually used
are instantiated.
@end itemize

@node repository, libstdc++, version 2.7, new stuff
@section How do I use the new repository code?

Because there is some disagreement about the details of the template
repository mechanism, you'll need to obtain a patch from Cygnus Support
to enable the 2.7.0 repository code.  You can obtain the patch by
anonymous FTP: @file{ftp://ftp.cygnus.com/pub/g++/gcc-2.7.0-repo.gz}.

After you've applied the patch, the @code{-frepo} flag will enable the
repository mechanism.  The flag works much like the existing
@code{-fno-implicit-templates} flag, except that auxiliary files, with
an @file{.rpo} extension, are built that specify what template
expansions are needed.  At link time, the (patched) collect program
detects missing templates and recompiles some of the object files
so that the required templates are expanded.

Note that the mechanism differs from that of cfront in that template
definitions still must be visible at the point where they are to be
expanded.  No assumption is made that @file{foo.C} contains template
definitions corresponding to template declarations in @file{foo.h}.

Jason Merrill writes: ``To perform closure on a set of objects, just try
to link them together.  It will fail, but as a side effect all needed
instances will be generated in the objects.''

@node libstdc++, , repository, new stuff
@section The GNU Standard C++ Library

The GNU Standard C++ Library (also called the ``GNU ANSI C++ Library''
in places in the code) is not libg++, though it is included in the
libg++ distribution.  Rather, it contains classes and functions
required by the ANSI/ISO standard.  The copyright conditions are the
same as those for for the iostreams classes; the LGPL is not used.  See
@xref{legalities}.

This library, libstdc++, is in the libg++ distribution in versions 2.6.2
and later.  It requires at least gcc 2.6.3 to build the libg++-2.6.2
version; use at least gcc 2.7.0 to build the libg++ 2.7.0 version.  It
contains a hacked-up version of HP's implementation of the Standard
Template Library (see @xref{Standard Template Library}).  I've
successfully used this Standard Template Library version to build
a number of the demos you'll see on various web pages.

As of version 2.7.0, the streams classes are now in libstdc++ instead of
libg++, and libiostream is being phased out (don't use it).  The g++
program searches this library.

@node getting g++, installation, new stuff, Top
@chapter Obtaining Source Code
@cindex Source code

@menu
* latest versions::  What is the latest version of gcc, g++, and libg++?
* g++ for Unix::    How do I get a copy of g++ for Unix?
* g++ for HP::  Getting gcc/g++ for the HP Precision Architecture
* g++ for Solaris 2.x::  Getting gcc/g++ binaries for Solaris 2.x
* g++ for other platforms::  How do I get a copy of g++ for (some other platform)?
* 1.x vs 2.x versions::  But I can only find g++-1.42!
@end menu

@node latest versions,  g++ for Unix, , getting g++
@section What is the latest version of gcc, g++, and libg++?

@cindex gcc/g++, version date
The latest "2.x" version of gcc/g++ is 2.7.0, released June 16, 1995.
The latest version of libg++ is 2.7.0a, released June 19, 1995 (2.7.0
had an error in a makefile and was almost immediately replaced).
.
Don't use 2.5.x, with x less than 5, for C++ code; there were some
serious bugs that didn't have easy workarounds.  2.5.8 is the most
solid 2.5.x release.  2.6.3 is the most solid 2.6.x release.

For some non-Unix platforms, the latest port of gcc may be an earlier
version (2.5.8, say).  You'll need to use a version of libg++ that
has the same first two digits as the compiler version, e.g. use libg++
2.5.x (for the latest x you can find) with gcc version 2.5.8.

The latest "1.x" version of gcc is 1.42, and the latest "1.x" version of
g++ is 1.42.0.
While gcc 1.42 is quite usable for C programs,
I recommend against using g++ 1.x except in special circumstances
(and I can't think of any such circumstances).

@node g++ for Unix, g++ for HP, latest versions, getting g++
@section How do I get a copy of g++ for Unix?

First, you may already have it if you have gcc for your platform;
g++ and gcc are combined now (as of gcc version 2.0).
@cindex GNU gcc, version
@cindex GNU g++ and gcc

You can get g++ from a friend who has a copy, by anonymous FTP or
UUCP, or by ordering a tape or CD-ROM from the Free Software
Foundation.
@cindex g++, ordering
@cindex g++, getting a copy

The Free Software Foundation is a nonprofit organization that
distributes software and manuals to raise funds for more GNU
development.  Getting your copy from the FSF contributes directly to
paying staff to develop GNU software.  CD-ROMs cost $400 if an
organization is buying, or $100 if an individual is buying.  Tapes
cost around $200 depending on media type.  I recommend asking for
version 2, not version 1, of g++.
@cindex FSF [Free Software Foundation]
@cindex GNU [GNU's not unix]

For more information about ordering from the FSF, contact
gnu@@prep.ai.mit.edu, phone (617) 542-5942 or anonymous ftp file
@file{ftp://prep.ai.mit.edu/pub/gnu/GNUinfo/ORDERS} (you can
also use one of the sites listed below if you can't get into ``prep'').

@cindex FSF, contact <gnu@@prep.ai.mit.edu>

Here is a list of anonymous FTP archive sites for GNU software.
If no directory is given, look in @file{/pub/gnu}.

@cindex GNUware, anonymous FTP sites

@example
ASIA: ftp.cs.titech.ac.jp, utsun.s.u-tokyo.ac.jp:/ftpsync/prep,
cair.kaist.ac.kr, ftp.nectec.or.th:/pub/mirrors/gnu

AUSTRALIA: archie.oz.au:/gnu (archie.oz or archie.oz.au for ACSnet)

AFRICA: ftp.sun.ac.za

MIDDLE-EAST: ftp.technion.ac.il:/pub/unsupported/gnu

EUROPE: irisa.irisa.fr, ftp.univ-lyon1.fr:, ftp.mcc.ac.uk,
unix.hensa.ac.uk:/pub/uunet/systems/gnu, ftp.denet.dk,
src.doc.ic.ac.uk:/gnu, ftp.eunet.ch, nic.switch.ch:/mirror/gnu,
ftp.informatik.rwth-aachen.de, ftp.informatik.tu-muenchen.de,
ftp.win.tue.nl, ftp.funet.fi, ftp.stacken.kth.se, isy.liu.se,
ftp.luth.se:/pub/unix/gnu, ftp.sunet.se, archive.eu.net

SOUTH AMERICA: ftp.unicamp.br, ftp.inf.utfsm.cl

WESTERN CANADA: ftp.cs.ubc.ca:/mirror2/gnu

USA: wuarchive.wustl.edu:/systems/gnu, labrea.stanford.edu,
ftp.digex.net, ftp.kpc.com:/pub/mirror/gnu,
f.ms.uky.edu:/pub3/gnu, jaguar.utah.edu:/gnustuff,
ftp.hawaii.edu:/mirrors/gnu, vixen.cso.uiuc.edu:/gnu,
mrcnext.cso.uiuc.edu, ftp.cs.columbia.edu:/archives/gnu/prep,
col.hp.com:/mirrors/gnu, gatekeeper.dec.com:/pub/GNU,
ftp.uu.net:/systems/gnu

@end example

The ``official site'' is prep.ai.mit.edu, but your transfer will probably
go faster if you use one of the above machines.

@cindex gzip
Most GNU utilities are compressed with ``gzip'', the GNU compression
utility.  All GNU archive sites should have a copy of this program,
which you will need to uncompress the distributions.

@cindex UUNET
@cindex UUCP
UUNET customers can get GNU sources from UUNET via UUCP.
UUCP-only sites can get GNU sources by ``anonymous UUCP'' from site
"osu-cis" at Ohio State University.  You pay for the long-distance call
to OSU; the price isn't too bad on weekends at 9600 bps.  Send mail to 
uucp@@cis.ohio-state.edu or osu-cis!uucp for more information.

OSU lines are often busy.  If you're in the USA, and are willing to spend
more money, you can get sources via UUCP from UUNET using their 900 number:
1-900-GOT-SRCS (900 numbers don't work internationally).  You will be
billed $0.50/minute by your phone company.

@cindex libg++
Don't forget to retrieve libg++ as well!

@node g++ for HP, g++ for Solaris 2.x, g++ for Unix, getting g++
@section Getting gcc/g++ for the HP Precision Architecture

@cindex HP Precision Architecture
@cindex Hewlett-Packard
@cindex GNU GAS 
@cindex GNU gdb

If you use the HP Precision Architecture (HP-9000/7xx and HP-9000/8xx)
and you want to use debugging, you'll need to use the GNU assembler, GAS
(version 2.3 or later).  If you build from source, you must tell the
configure program that you are using GAS or you won't get debugging
support.  A non-standard debug format is used, since until recently HP
considered their debug format a trade secret.  Thanks to the work of
lots of good folks both inside and outside HP, the company has seen the
error of its ways and has now released the required information.  The
team at the University of Utah that did the gcc port now has code that
understands the native HP format.

Some enhancements for the HP that haven't been integrated back into the
official GCC are available from the University of Utah, site
jaguar.cs.utah.edu.  You can retrieve sources and prebuilt binaries for
GCC, GDB, binutils,and libg++; see the directory @file{/dist}.

The libg++ version is actually the same as the FSF 2.6.  The Utah
version of GDB can now understand both the GCC and HP C compiler debug
formats, so it is no longer necessary to have two different GDB versions.

I recommend that HP users use the Utah versions of the tools (see
above), though at this point the standard FSF versions will work well.

HP GNU users can also find useful stuff on the site geod.emr.ca in the
@file{/pub/UNIX/GNU-HP} directory.

Jeff Law is leaving the University of Utah, so the Utah prebuilt
binaries may be discontinued.

@node g++ for Solaris 2.x, g++ for other platforms, g++ for HP, getting g++
@section Getting gcc/g++ binaries for Solaris 2.x

``Sun took the C compiler out of Solaris 2.x.  Am I stuck?''

@cindex Solaris
@cindex gcc/g++ binaries for Solaris

No; prep.ai.mit.edu and its mirror sites provide GCC binaries for
Solaris.  As a rule, these binaries are not updated as often as the
sources are, so if you want the very latest version of gcc/g++, you
may need to grab and install binaries for an older version and use it to
bootstrap the latest version from source.

@cindex gzip
The latest gcc binaries on prep.ai.mit.edu and its mirror sites are for
version 2.5.6 for Solaris on the Sparc, and version 2.4.5 for Solaris on
Intel 386/486 machines.
There are also binaries for ``gzip'', the GNU compression utility, which
you'll need for uncompressing the binary distribution.  On any GNU
archive site, look in subdirectories @file{i486-sun-solaris2} or
@file{sparc-sun-solaris2}.

@cindex Solaris pkgadd utility
The ftp directory /pub/GNU on site ftp.quintus.com contains various
GNU and freeware programs for Solaris2.X running on the sparc. These are
packaged to enable installation using the Solaris ``pkgadd'' utility.
These include GNU emacs 19.27, gcc (and g++) 2.6.0, Perl 4.036, and others.

@node g++ for other platforms, 1.x vs 2.x versions, g++ for Solaris 2.x, getting g++
@section How do I get a copy of g++ for (some other platform)?

@cindex VMS support
@cindex VAX
@cindex VMS, g++/libg++ precompiled
The standard gcc/g++ distribution includes VMS support.  Since the
FSF people don't use VMS, it's likely to be somewhat less solid than
the Unix version.  Precompiled copies of g++ and libg++ in VMS-installable
form are available by FTP from mango.rsmas.miami.edu.  See also
the site ftp.stacken.kth.se (in Sweden), directory /pub/GNU-VMS/contrib,
which has gcc-2.5.8 and libg++-2.5.3.

@cindex MS-DOS support
@cindex Delorie's gcc/g++
@cindex DJGPP
@cindex EMX
There are two different versions of gcc/g++ for MS-DOS: EMX and DJGPP.
EMX also works for OS/2 and is described later.
DJGPP is DJ Delorie's port.  It can be found on many FTP archive
sites; its "home" is on oak.oakland.edu, directory @file{~ftp/pub/msdos/djgpp}.

The latest version of DJGPP is 1.12.maint1.  This version runs under
Windows 3.x.  It includes a port of gcc 2.6.0, plus support software.

FSF sells floppies with DJGPP on them; see above for ordering software
from the FSF.

A new Usenet group, @code{comp.os.msdos.djgpp}, has recently been
created.

@cindex Amiga support
For information on Amiga ports of gcc/g++, retrieve the file
@file{/pub/gnu/MicrosPorts/Amiga} from prep.ai.mit.edu, or write
to Markus M. Wild <wild@@nessie.cs.id.ethz.ch>, who I hope won't be too upset
that I mentioned his name here.

@cindex Atari ST support
A port of gcc to the Atari ST can be found on the site
``atari.archive.umich.edu'', under @file{/atari/Gnustuff/Tos}, along with many
other GNU programs.  This version is usually the same as the latest FSF
release.  See the ``Software FAQ'' for the Usenet group
``comp.sys.atari.st'' for more information.

@cindex EMX port 
@cindex gcc/2
@cindex OS/2 support

There are two different ports of gcc to OS/2, the
so-called EMX port (which also runs on MS-DOS), and a port called ``gcc/2''.
The EMX port's C library attempts to provide a Unix-like environment;
gcc/2 uses
a rather buggy port of the BSD libc.  For more information ask
around on ``comp.os.os2.programmer.misc''.

The EMX port is available by FTP from

@example
ftp.uni-stuttgart.de(129.69.1.12) in /pub/systems/os2/emx-0.9a
src.doc.ic.ac.uk(146.169.2.1) in /pub/packages/os2/unix/emx09a
ftp.informatik.tu-muenchen.de(131.159.0.198) in
        /pub/comp/os/os2/devtools/emx+gcc
@end example

gcc/2, together with other
GNUware for OS/2, can be obtained by FTP from

@example
ftp-os2.cdrom.com(192.153.46.2) in /pub/os2/2_x/unix/gnu
ftp-os2.nmsu.edu (128.123.35.151) in /pub/os2/2_x/unix/gnu
luga.latrobe.edu.au (131.172.2.2) in /pub/os2/2_x/unix/gnu
@end example

The current maintainer of the gcc/2 port is Colin Jensen (Michael Johnson
did the original port).  His address is cjensen@@netcom.com.

Eberhard Mattes did the EMX port.  His address is
mattes@@azu.informatik.uni-stuttgart.de.

@cindex Apple support
@cindex Macintosh support

I'm looking for more information on gcc/g++ support on the Apple
Macintosh.  Until recently, this FAQ did not provide such information,
but FSF is no longer boycotting Apple as the League for Programming
Freedom boycott has been dropped.

Mike White (cons116@@twain.oit.umass.edu) says:
``Versions 1.37.1 and 2.3.3 of gcc were ported by Stan Shebs and are available
at ftp.cygnus.com under /pub/shebs.  They are both interfaced to MPW.
Shebs is apparently working on a cross compiler of 2.6.3 to create
Mac apps from Unix boxes.''

I don't know anything about more recent versions.

@node 1.x vs 2.x versions, ,g++ for other platforms, getting g++
@section But I can only find g++-1.42!

``I keep hearing people talking about g++ 2.5.8 (or some other number
starting with 2), but the latest version I can find is g++ 1.42.
Where is it?''

@cindex Objective-C
@cindex g++, version number
As of gcc 2.0, C, C++, and Objective-C as well are all combined into a
single distribution called gcc.  If you get gcc you already have g++.  The
standard installation procedure for any gcc version 2 compiler will
install the C++ compiler as well.

One could argue that we shouldn't even refer to "g++-2.x.y" but it's a
convention.  It means ``the C++ compiler included with gcc-2.x.y.''

@node installation, User Problems, getting g++, Top
@chapter Installation Issues and Problems

@menu
* gcc-2 + g++-1::   I can't build g++ 1.x.y with gcc-2.x.y!
* what else do I need?::  OK, I've obtained gcc; what else do I need?
* use GNU linker?::  Should I use the GNU linker, or should I use "collect"?
* Use GNU assembler?::  Should I use the GNU assembler, or my vendor's assembler?
* Use GNU C library?::  Should I use the GNU C library?
* Global constructor problems:: Global constructors aren't being called
* Strange assembler errors:: Strange assembler errors when linking C++ programs
* Other problems building libg++::  Other problems building libg++
* More size_t problems::        But I'm still having problems with size_t!
* Rebuild libg++?::  Rebuild libg++ to go with my new g++?
@end menu

@node gcc-2 + g++-1, what else do I need?, , installation
@section I can't build g++ 1.x.y with gcc-2.x.y!

``I obtained gcc-2.x.y and g++ 1.x.y and I'm trying to build it, but
I'm having major problems.  What's going on?''

@cindex g++, building 
If you wish to build g++-1.42, you must obtain gcc-1.42 first.  The
installation instructions for g++ version 1 leave a lot to be desired,
unfortunately, and I would recommend that, unless you have a special
reason for needing the 1.x compiler, that C++ users use the latest
g++-2.x version, as it
is the version that is being actively maintained.

@cindex g++, template support
@cindex Templates
@cindex ANSI draft standard
There is no template support in g++-1.x, and it is generally much further
away from the ANSI draft standard than g++-2.x is.

@node what else do I need?, use GNU linker?, gcc-2 + g++-1, installation
@section OK, I've obtained gcc; what else do I need?

@cindex libg++
First off, you'll want libg++ as you can do almost nothing without it
(unless you replace it with some other class library).

@cindex GNU GAS 
@cindex GNU GAS [assembler]
Second, depending on your platform, you may need "GAS", the GNU assembler,
or the GNU linker (see next question).

@cindex GNU gdb
Finally, while it is not required, you'll almost certainly want the GNU
debugger, gdb.  The latest version is 4.14, released March 2, 1995.  Other
debuggers (like dbx, for example) will normally not be able to
understand at least some of the debug information produced by g++.

@node use GNU linker?, Use GNU assembler?, what else do I need?, installation
@section Should I use the GNU linker, or should I use "collect"?

@cindex Linker
@cindex System VR3, linker
@cindex System VR4, linker
First off, for novices: special measures must be taken with C++ to arrange
for the calling of constructors for global or static objects before the
execution of your program, and for the calling of destructors at the end.
(Exception: System VR3 and System VR4 linkers, Linux/ELF, and some other
systems support user-defined
segments; g++ on these systems requires neither the GNU linker nor
collect.  So if you have such a system, the answer is that you don't
need either one).

@cindex AT&T cfront
@cindex Cfront-end
@cindex collect program
@cindex GNU linker
@cindex GNU binutils
If you have experience with AT&T's "cfront", this function is performed
there by programs named "patch" or "munch".  With GNU C++, it is performed
either by the GNU linker or by a program known as "collect".  The collect
program is part of the gcc-2.x distribution; you can obtain the GNU linker
separately as part of the "binutils" package.  The latest version of
binutils is 2.5.2, released November 2, 1994.

(To be technical, it's "collect2"; there were originally several
alternative versions of collect, and this is the one that survived).

There are advantages and disadvantages to either choice.

Advantages of the GNU linker:
@cindex GNU linker, advantages
@cindex GNU ld
@cindex ld [GNU linker]

It's faster than using collect -- collect basically runs the standard Unix
linker on your program twice, inserting some extra code after the first
pass to call the constructors.  This is a sizable time penalty for large
programs.  The GNU linker does not require this extra pass.

GNU ld reports undefined symbols using their true names, not the mangled
names (but as of 2.7.0 so does collect).

If there are undefined symbols, GNU ld reports which object file(s) refer to
the undefined symbol(s).

As of binutils version 2.2, on systems that use the so-called "a.out"
debug format (e.g. Suns running SunOS 4.x), the GNU linker compresses
the debug symbol table considerably.

@cindex collect linker, advantages
Advantages of collect:

@cindex Shared libraries
If your native linker supports shared libraries, you can use shared
libraries with collect.  This used to be a strong reason @emph{not}
to use the GNU linker, but recent versions of GNU ld support linking
with shared libraries on many platforms, and creating shared libraries
on a few (such as Intel x86 systems that use ELF object format).

Note: using existing shared libraries (X and libc, for example) works
very nicely.  Generating shared libraries from g++-compiled code is
another matter, generally requiring OS-dependent tricks if it is
possible at all.  But progress has been made recently.

As of 2.7.0, building C++ shared libraries should work fine on supported
platforms (HPUX 9+, IRIX 5+, DEC UNIX (formerly OSF/1), SunOS 4, and all
targets using SVR4-style ELF shared libraries).

@cindex Shared version of libg++
However, as of libg++ 2.6.2, the libg++ distribution contains some
patches to build libg++ as a shared library on some OSes (those listed
above).  Check the file @file{README.SHLIB} from that distribution.

@cindex GNU linker, porting
The GNU linker has not been ported to as many platforms as g++ has, so you
may be forced to use collect.

If you use collect, you don't need to get something extra and figure out
how to install it; the standard gcc installation procedure will do it for you.

In conclusion, I don't see a clear win for either alternative at this
point.  Take your pick.

@node Use GNU assembler?, Use GNU C library?, use GNU linker?, installation
@section Should I use the GNU assembler, or my vendor's assembler?

@cindex Assembler
@cindex GNU GAS
This depends on your platform and your decision about the GNU linker.  For
most platforms, you'll need to use GAS if you use the GNU linker.  For
some platforms, you have no choice; check the gcc installation notes to
see whether you must use GAS.  But you can usually use the vendor's
assembler if you don't use the GNU linker.

The GNU assembler assembles faster than many native assemblers; however,
on many platforms it cannot support the local debugging format.

If you want to build shared libraries from gcc/g++ output and you are on
a Sun, you must @emph{not} use GNU as, as it cannot do
position-independent code correctly yet.

On HPUX or IRIX, you must use GAS (and configure gcc with the
@code{--with-gnu-as} option) to debug your programs.  GAS is
strongly recommended particularly on the HP platform because of
limitations in the HP assembler.

The GAS distribution has recently been merged with the binutils
distribution, so the GNU assembler and linker are now together in
this package (as of binutils version 2.5.1).

@node Use GNU C library?, Global constructor problems, Use GNU assembler?, installation
@section Should I use the GNU C library?

@cindex GNU C library
@cindex libg++
At this point in time, no.  The GNU C library is still very young, and
libg++ still conflicts with it in some places.  Use your native C library
unless you know a lot about the gory details of libg++ and gnu-libc.  This
will probably change in the future.

@node Global constructor problems, Strange assembler errors, Use GNU C library?, installation
@section Global constructors aren't being called

@cindex global constructors
``I've installed gcc and it almost works, but constructors and
destructors for global objects and objects at file scope aren't being
called.  What did I do wrong?''

@cindex collect program
It appears that you are running on a platform that requires you to
install either "collect2" or the GNU linker, and you have done neither.
For more information, see the section discussing the GNU linker
(@xref{use GNU linker?}).

@cindex constructor problems on Solaris
@cindex Solaris, constructor problems
On Solaris 2.x, you shouldn't need a collect program and GNU ld doesn't run.
If your global constructors aren't being called, you may need to install
a patch, available from Sun, to fix your linker.  The number of the
``jumbo patch'' that applies is 101409-03.  Thanks to Russell Street
(r.street@@auckland.ac.nz) for this info.

@cindex IRIX, installing collect
It appears that on IRIX, the collect2 program is not being installed
by default during the installation process, though it is required;
you can install it manually by executing

@example
make install-collect2
@end example

from the gcc source directory after installing the compiler.  (I'm
not certain for which versions of gcc this problem occurs, and whether
it is still present).

@node Strange assembler errors, Other problems building libg++, Global constructor problems, installation
@section Strange assembler errors when linking C++ programs

``I've installed gcc and it seemed to go OK, but when I attempt to link
any C++ program, I'm getting strange errors from the assembler!  How
can that be?''

The messages in question might look something like

@example
as: "/usr/tmp/cca14605.s", line 8: error: statement syntax
as: "/usr/tmp/cca14605.s", line 14: error: statement syntax
@end example

(on a Sun, different on other platforms).  The important thing is that
the errors come out at the link step, @emph{not} when a C++ file is
being compiled.

@cindex nm program
@cindex GNU nm program
Here's what's going on: the collect2 program uses the Unix ``nm''
program to obtain a list of symbols for the global constructors and
destructors, and it builds a little assembly language module that
will permit them all to be called.  If you're seeing this symptom,
you have an old version of GNU nm somewhere on your path.  This old
version prints out symbol names in a format that the collect2 program
does not expect, so bad assembly code is generated.

The solution is either to remove the old version of GNU nm from your
path (and that of everyone else who uses g++), or to install a newer
version (it is part of the GNU "binutils" package).  Recent versions
of GNU nm do not have this problem.

@node Other problems building libg++, More size_t problems, Strange assembler errors, installation
@section Other problems building libg++
@cindex libg++ on Ultrix
@cindex libg++ on SunOS

``I am having trouble building libg++.  Help!''

On some platforms (for example, Ultrix), you may see errors complaining
about being unable to open dummy.o.  On other platforms (for example,
SunOS), you may see problems having to do with the type of size_t.
The fix for these problems is to make libg++ by saying "make CC=gcc".
According to Per Bothner, it should no longer be necessary to specify
"CC=gcc" for libg++-2.3.1 or later.

``I built and installed libg++, but g++ can't find it.  Help!''

The string given to @file{configure} that identifies your system must
be the same when you install libg++ as it was when you installed gcc.
Also, if you used the @code{--prefix} option to install gcc somewhere
other than @file{/usr/local}, you must use the same value for
@code{--prefix} when installing libg++, or else g++ will not be able
to find libg++.

@cindex patch for libg++-2.6.2

The toplevel Makefile in the libg++ 2.6.2 distribution is broken, which
along with a bug in g++ 2.6.3 causes problems linking programs that use the
libstdc++ complex classes.  A patch for this is available from
@file{ftp.cygnus.com:pub/g++/libg++-2.6.2-fix.gz}.

@node More size_t problems, Rebuild libg++?, Other problems building libg++, installation
@section But I'm @emph{still} having problems with @code{size_t}!

@cindex Type of size_t
``I did all that, and I'm @emph{still} having problems with disagreeing
definitions of size_t, SIZE_TYPE, and the type of functions like
@code{strlen}.''

@cindex _G_config.h
The problem may be that you have an old version of @file{_G_config.h}
lying around.  As of libg++ version 2.4, @file{_G_config.h}, since it is
platform-specific, is inserted into a different directory; most include
files are in @file{$prefix/lib/g++-include}, but this file now lives in
@file{$prefix/$arch/include}.  If, after upgrading your libg++, you find that
there is an old copy of @file{_G_config.h} left around, remove it,
otherwise g++ will find the old one first.

@node Rebuild libg++?,  , More size_t problems, installation
@section Do I need to rebuild libg++ to go with my new g++?

``After I upgraded g++ to the latest version, I'm seeing undefined
symbols.''

or

``If I upgrade to a new version of g++, do I need to reinstall libg++?''

@cindex Incompatibilities between g++ versions

As a rule, the first two digits of your g++ and libg++ should be the
same.  Normally when you do an upgrade in the ``minor version number''
(2.5.7 to 2.5.8, say) there isn't a need to rebuild libg++, but there
have been a couple of exceptions in the past.

@node User Problems, legalities, installation, Top
@chapter User Problems

@menu
* unused parameter warnings:: How to silence ``unused parameter'' warnings
* jump crosses initialization:: g++ objects to a declaration in a case statement
* 2.5.x changes in overloading:: Changes in function overloading
* Demangler::	Where can I find a demangler?
* etags for C++::   Where can I find a version of etags for C++?
* static data members::  Linker reports undefined symbols for static data members
* internal compiler error:: What does ``internal compiler error'' mean?
* bug reports::     I think I have found a bug in g++.
* porting to g++::  Porting programs from other compilers to g++
* name mangling::   Why does g++ mangle names differently from other C++ compilers?
* problems linking with other libraries::  Why can't g++ code link with code from other C++ compilers?
* documentation::   What documentation exists for g++ 2.x?
* templates::       Problems with the template implementation
* undefined templates::  I get undefined symbols when using templates
* redundant templates::  I get multiply defined symbols when using templates
* Standard Template Library:: Does g++ support the Standard Template Library?
* agreement with standards::  What are the differences between g++ and the ARM specification of C++?
* compiling standard libraries::  Will g++ compile InterViews?  The NIH class library?
* debugging on SVR4 systems::  Debugging on SVR4 systems
* X11 conflicts with libg++::  Conflict over meaning of String
* assignment to streams::  Why can't I assign one stream to another?
@end menu

@node unused parameter warnings, jump crosses initialization, ,User Problems
@section How to silence ``unused parameter'' warnings

@cindex -Wall
@cindex -Wunused

``When I use @code{-Wall} (or @code{-Wunused}), g++ warns about
unused parameters.  But the parameters have to be there, for use
in derived class functions.  How do I get g++ to stop complaining?''

The answer is to simply omit the names of the unused parameters when
defining the function.  This makes clear, both to g++ and to readers
of your code, that the parameter is unused.  For example:

@example
int Foo::bar(int arg) @{ return 0; @}
@end example

will give a warning for the unused parameter @code{arg}.  To suppress
the warning write

@example
int Foo::bar(int) @{ return 0; @}
@end example

@node jump crosses initialization, 2.5.x changes in overloading, unused parameter warnings, User Problems
@section g++ objects to a declaration in a case statement

``The compiler objects to my declaring a variable in one of the branches
of a case statement.  Earlier versions used to accept this code.  Why?''

The draft standard does not allow a goto or a jump to a case label to
skip over an initialization of a variable or a class object.  For
example:

@example
  switch ( i )
    @{
      case 1:
        Object obj(0);
        ...
	break;
      case 2:
	...
	break;
      @}    
@end example

The reason is that @code{obj} is also in scope in the rest of the switch
statement.

As of version 2.7.0, the compiler will object that the jump to the
second case level crosses the initialization of @code{obj}.  Older
compiler versions would object only if class Object has a destructor.
In either case, the solution is to add a set of curly braces around
the case branch:

@example
      case 1:
       @{
        Object obj(0);
        ...
	break;
       @}
@end example

@node 2.5.x changes in overloading, Demangler, jump crosses initialization, User Problems
@section gcc 2.5.x broke my code!  Changes in function overloading

``I have a program that worked just fine with older g++ versions, but as
of version 2.5.x it doesn't work anymore.  Help!''

@cindex hiding rule
While it's always possible that a new bug has been introduced into the
compiler, it's also possible that you have been relying on bugs in older
versions of g++.  For example, version 2.5.0 was the first version of
g++ to correctly implement the ``hiding rule.''  That is, if you have
an overloaded function in a base class, and in a derived class you
redefine one of the names, the other names are effectively ``hidden''.
@emph{All} the names from the baseclass need to be redefined in the
derived class.  See section 13.1 of the ARM: ``A function member of
a derived class is @emph{not} in the same scope as a function member of
the same name in a base class''.

Here's an example that is handled incorrectly by g++ versions before 2.5.0
and correctly by newer versions:

@example
class Base @{
public:
    void foo(int);
@};

class Derived : public Base @{
public:
    void foo(double);  // @emph{note that Base::foo(int) is hidden}
@};

main() @{
    Derived d;
    d.foo(2); // @emph{Derived::foo(double), not Base::foo(int), is called}
@}
@end example

@node Demangler, etags for C++, 2.5.x changes in overloading, User Problems
@section Where can I find a demangler?

@cindex demangler program
A g++-compatible demangler named @code{c++filt} can be found in the
@file{binutils} distribution.  This distribution (which also contains
the GNU linker) can be found at any GNU archive site.

As of version 2.7.0, @code{c++filt} is included with gcc and is
installed automatically.  Even better, it is used by the @code{collect}
linker, so you don't see mangled symbols anymore.

@node etags for C++, static data members, Demangler, User Problems
@section Where can I find a version of etags for C++?

@cindex etags
The libg++ distribution contains a version of etags that works for C++
code.  Look in @file{libg++/utils}.  It's not built by default when you
install libg++, but you can cd to that directory and type

@example
make etags
@end example

after you've installed libg++.

@node static data members, internal compiler error, etags for C++, User Problems
@section Linker reports undefined symbols for static data members

@cindex Static data members
``g++ reports undefined symbols for all my static data members when I link,
even though the program works correctly for compiler XYZ.  What's going on?''

The problem is almost certainly that you don't give definitions for
your static data members.  If you have

@example
class Foo @{
	...
	void method();
	static int bar;
@};
@end example

you have only declared that there is an int named Foo::bar and a member
function named Foo::method that is defined somewhere.  You still need to
defined BOTH method() and bar in some source file.  According to the draft
ANSI standard, you must supply an initializer, such as

@example
int Foo::bar = 0;
@end example

@noindent
in one (and only one) source file.

@node internal compiler error, bug reports, static data members, User Problems
@section What does ``Internal compiler error'' mean?

It means that the compiler has detected a bug in itself.  Unfortunately,
g++ still has many bugs, though it is a lot better than it used to be.
If you see this message, please send in a complete bug report (see next
section).

@node bug reports, porting to g++, internal compiler error, User Problems
@section I think I have found a bug in g++.

@cindex Bug in g++, newly found
``I think I have found a bug in g++, but I'm not sure.  How do I know,
and who should I tell?''

@cindex Manual, for gcc
First, see the excellent section on bugs and bug reports in the gcc manual
(which is included in the gcc distribution).  As a short summary of that
section: if the compiler gets a fatal signal, for any input, it's a bug
(newer versions of g++ will ask you to send in a bug report when they
detect an error in themselves).  Same thing for producing invalid
assembly code.

When you report a bug, make sure to describe your platform (the type of
computer, and the version of the operating system it is running) and the
version of the compiler that you are running.  See the output of the
command @code{g++ -v} if you aren't sure.  Also provide enough code
so that the g++ maintainers can duplicate your bug.  Remember that the
maintainers won't have your header files; one possibility is to send
the output of the preprocessor (use @code{g++ -E} to get this).  This
is what a ``complete bug report'' means.

I will add some extra notes that are C++-specific, since the notes from
the gcc documentation are generally C-specific.

@cindex g++ bug report
First, mail your bug report to "bug-g++@@prep.ai.mit.edu".  You may also
post to gnu.g++.bug, but it's better to use mail, particularly if you
have any doubt as to whether your news software generates correct reply
addresses.  Don't mail C++ bugs to bug-gcc@@prep.ai.mit.edu.

@cindex libg++ bug report
If your bug involves libg++ rather than the compiler, mail to
bug-lib-g++@@prep.ai.mit.edu.  If you're not sure, choose one, and if you
guessed wrong, the maintainers will forward it to the other list.

@cindex C++, reference books
@cindex ARM [Annotated C++ Ref Manual]
Second, if your program does one thing, and you think it should do
something else, it is best to consult a good reference if in doubt.
The standard reference is the draft working paper from the ANSI/ISO
C++ standardization committee, which you can get on the net.
For PostScript and PDF (Adobe Acrobat) versions, see the
archive at ftp://research.att.com/dist/stdc++/WP.  For HTML and ASCII
versions, see ftp://ftp.cygnus.com/pub/g++.  On the World Wide Web, see
http://www.cygnus.com/~mrs/wp-draft.

An older
standard reference is "The Annotated C++ Reference Manual", by Ellis and
Stroustrup (copyright 1990, ISBN #0-201-51459-1).  This is what they're
talking about on the net when they refer to ``the ARM''.  But you should
know that changes have been made to the language since then.

The ANSI/ISO C++ standards committee have adopted some changes to the
C++ language since the publication of the original ARM, and newer
versions of g++ (2.5.x and later) support some of these changes, notably
the mutable keyword (added in 2.5.0), the bool type (added in 2.6.0),
and changes in the scope of variables defined in for statements (added
in 2.7.0).
You can obtain an addendum to the ARM explaining these changes by FTP
from ftp.std.com in @file{/AW/stroustrup2e/new_iso.ps}.

@cindex AT&T cfront
Note that the behavior of (any version of) AT&T's "cfront" compiler is
NOT the standard for the language.

@node porting to g++, name mangling, bug reports, User Problems
@section Porting programs from other compilers to g++

``I have a program that runs on <some other C++ compiler>, and I want
to get it running under g++.  Is there anything I should watch out
for?''

@cindex Porting to g++

Note that g++ supports many of the newer keywords that have recently
been added to the language.  Your other C++ compiler may not support
them, so you may need to rename variables and members that conflict
with these keywords.

There are two other reasons why a program that worked under one compiler
might fail under another: your program may depend on the order of
evaluation of side effects in an expression, or it may depend on the
lifetime of a temporary (you may be assuming that a temporary object
"lives" longer than the standard guarantees).  As an example of the
first:

@example
void func(int,int);

int i = 3;
func(i++,i++);
@end example

@cindex Order of evaluation, problems in porting
Novice programmers think that the increments will be evaluated in strict
left-to-right order.  Neither C nor C++ guarantees this; the second
increment might happen first, for example.  func might get 3,4, or it
might get 4,3.

@cindex Classes, problems in porting
@cindex Problems in porting, class
The second problem often happens with classes like the libg++ String
class.  Let's say I have

@example
String func1();
void func2(const char*);
@end example

and I say

@example
func2(func1());
@end example

because I know that class String has an "operator const char*".  So what
really happens is

@example
func2(func1().convert());
@end example

@cindex temporaries
where I'm pretending I have a convert() method that is the same as the
cast.  This is unsafe in g++ versions before 2.6.0, because the
temporary String object may be deleted after its last use (the call to
the conversion function), leaving the pointer pointing to garbage, so by
the time func2 is called, it gets an invalid argument.

@cindex ANSI draft standard
Both the cfront and the old g++ behaviors are legal according to the ARM,
but the powers that be have decided that compiler writers were given
too much freedom here.

The ANSI C++ committee has now come to a resolution of the lifetime of
temporaries problem: they specify that temporaries should be deleted at
end-of-statement (and at a couple of other points).  This means that g++
versions before 2.6.0 now delete temporaries too early, and cfront
deletes temporaries too late.  As of version 2.6.0, g++ does things
according to the new standard.

@cindex Scope, problems in porting
@cindex Problems in porting, scope
For now, the safe way to write such code is to give the temporary a name,
which forces it to live until the end of the scope of the name. For
example:

@example
String& tmp = func1();
func2(tmp);
@end example

Finally, like all compilers (but especially C++ compilers, it seems),
g++ has bugs, and you may have tweaked one.  If so, please file a bug
report (after checking the above issues).

@node name mangling, problems linking with other libraries, porting to g++, User Problems
@section Why does g++ mangle names differently from other C++ compilers?

See the answer to the next question.
@cindex Mangling names

@node problems linking with other libraries, documentation, name mangling, User Problems
@section Why can't g++ code link with code from other C++ compilers?

``Why can't I link g++-compiled programs against libraries compiled by
some other C++ compiler?''

@cindex Mangling names
@cindex Cygnus Support
Some people think that,
if only the FSF and Cygnus Support folks would stop being
stubborn and mangle names the same way that, say, cfront does, then any
g++-compiled program would link successfully against any cfront-compiled
library and vice versa.  Name mangling is the least of the problems.
Compilers differ as to how objects are laid out, how multiple inheritance
is implemented, how virtual function calls are handled, and so on, so if
the name mangling were made the same, your programs would link against
libraries provided from other compilers but then crash when run.  For this
reason, the ARM @emph{encourages} compiler writers to make their name mangling
different from that of other compilers for the same platform.
Incompatible libraries are then detected at link time, rather than at run
time.
@cindex ARM [Annotated C++ Ref Manual]
@cindex Compiler differences

@node documentation, templates, problems linking with other libraries, User Problems
@section What documentation exists for g++ 2.x?

@cindex g++, documentation
Relatively little.
While the gcc manual that comes with the distribution has some coverage
of the C++ part of the compiler, it focuses mainly on the C compiler
(though the information on the ``back end'' pertains to C++ as well).
Still, there is useful information on the command line options and the
#pragma interface and #pragma implementation directives in the manual,
and there is a useful section on template instantiation in the 2.6 version.
There is a Unix-style manual entry, "g++.1", in the gcc-2.x
distribution; the information here is a subset of what is in the manual.

You can buy a nicely printed and bound copy of this manual from the FSF;
see above for ordering information.

For versions 2.6.2 and later, the gcc/g++ distribution contains the
gcc manual in PostScript.  Also,
Postscript versions of GNU documentation in U.S. letter format
are available by anonymous FTP to primus.com in /pub/gnu-ps.
The same, in A4 format, are on liasun3.epfl.ch in /pub/gnu/ps-doc.

A draft of a document describing the g++ internals appears in the gcc
distribution (called g++int.texi); it is still incomplete.

@node templates, undefined templates, documentation, User Problems
@section Problems with the template implementation

@cindex g++, template support
@cindex Templates

g++ does not implement a separate pass to instantiate template functions
and classes at this point; for this reason, it will not work, for the most
part, to declare your template functions in one file and define them in
another.  The compiler will need to see the entire definition of the
function, and will generate a static copy of the function in each file
in which it is used.

(The experimental template repository code (see @xref{repository}) that
can be added to 2.7.0 does implement a separate pass, but there is still
no searching of files that the compiler never saw).

@cindex -fno-implicit-templates
For version 2.6.0, however, a new switch @code{-fno-implicit-templates}
was added; with this switch, templates are expanded only under user
control.  I recommend that all g++ users that use templates read the
section ``Template Instantiation'' in the gcc manual (version 2.6.x
and newer).  g++ now supports explicit template expansion using the
syntax from the latest C++ working paper:

@example
template class A<int>;
template ostream& operator << (ostream&, const A<int>&);
@end example

@cindex template limitations
As of version 2.6.3, there are still a few limitations in the template
implementation besides the above (thanks to Jason Merrill for this info):

@enumerate 1
@item
Static data member templates are not supported.  You can work around
this by explicitly declaring the static variable for each template
specialization:

@example
template <class T> struct A @{
  static T t;
@};

template <class T> T A<T>::t = 0; // gets bogus error
int A<int>::t = 0;                // OK (workaround)
@end example

(still a limitation in 2.7.0)

@item
Template member names are not available when defining member function
templates.

@example
template <class T> struct A @{
  typedef T foo;
  void f (foo);
  void g (foo arg) @{ ... @}; // this works
@};

template <class T> void A<T>::f (foo) @{ @} // gets bogus error
@end example

@item
Templates are instantiated using the parser.  This results in two
problems:

a) Class templates are instantiated in some situations where such
instantiation should not occur.

@example
template <class T> class A @{ @};
A<int> *aip = 0; // should not instantiate A<int> (but does)
@end example

b) Function templates cannot be inlined at the site of their
instantiation.

@example
template <class T> inline T min (T a, T b) @{ return a < b ? a : b; @}

void f () @{
  int i = min (1, 0);           // not inlined
@}

void g () @{
  int j = min (1, 0);           // inlined
@}
@end example

A workaround that works in version 2.6.1 and later is to specify

@example
extern template int min (int, int);
@end example

before @code{f()}; this will force it to be instantiated (though not
emitted). 

@item
Member function templates are always instantiated when their containing
class is.  This is wrong.
@end enumerate

@node undefined templates, redundant templates, templates, User Problems
@section I get undefined symbols when using templates

(Thanks to Jason Merrill for this section).

@cindex template instantiation
g++ does not automatically instantiate templates defined in other files.
Because of this, code written for cfront will often produce undefined
symbol errors when compiled with g++.  You need to tell g++ which template
instances you want, by explicitly instantiating them in the file where they
are defined.  For instance, given the files

@file{templates.h}:
@example
template <class T>
class A @{
public:
  void f ();
  T t;
@};

template <class T> void g (T a);
@end example

@file{templates.cc}:
@example
#include "templates.h"

template <class T>
void A<T>::f () @{ @}

template <class T>
void g (T a) @{ @}
@end example


main.cc:
@example
#include "templates.h"

main ()
@{
  A<int> a;
  a.f ();
  g (a);
@}
@end example

compiling everything with @code{g++ main.cc templates.cc} will result in
undefined symbol errors for @samp{A<int>::f ()} and @samp{g (A<int>)}.  To
fix these errors, add the lines

@example
template class A<int>;
template void g (A<int>);
@end example

to the bottom of @samp{templates.cc} and recompile.

@node redundant templates, Standard Template Library, undefined templates, User Problems
@section I get multiply defined symbols using templates

You may be running into a bug that was introduced in version 2.6.1
(and is still present in 2.6.3) that generated external linkage
for templates even when neither @code{-fexternal-templates} nor
@code{-fno-implicit-templates} is specified.  There is a patch for
this problem at ftp.cygnus.com:pub/g++/gcc-2.6.3-template-fix.
I recommend either applying the patch or
using @code{-fno-implicit-templates}
together with explicit template instantiation as described in previous
sections.

This bug is fixed in 2.7.0.

@node Standard Template Library, agreement with standards, redundant templates, User Problems
@section Does g++ support the Standard Template Library?

>From Per Bothner:

@cindex STL
@cindex Standard Template Library
The Standard Template Library (STL) uses many of the extensions that the
ANSI/ISO committee has made to templates, and g++ doesn't support
some of these yet.  So if you grab HP's free implementation of STL it
isn't going to work.  However, libg++-2.6.2 contains a
hacked version of STL, based on work by Carsten Bormann, which permits
gcc-2.6.3 to compile at least the containers.  A full implementation is
going to need improved template support, which will take a while yet.

As of libg++-2.7.0 and gcc-2.7.0, I've succeeded in making many short
STL example programs work, though there are still a number of bugs
and limitations.

@node agreement with standards, compiling standard libraries, Standard Template Library, User Problems
@section What are the differences between g++ and the ARM specification of C++?

@cindex ARM [Annotated C++ Ref Manual]
@cindex exceptions
As of version 2.7.0, g++ has exception support on most but not all
platforms
(no support on MIPS-based platforms yet), but
it doesn't work right if optimizaton is enabled, which means the
exception
implementation is still
not really ready for production use.


@cindex mutable
Some features that the ANSI/ISO standardization committee has voted in
that don't appear in the ARM are supported, notably the @code{mutable}
keyword, in version 2.5.x.  2.6.x adds support for the built-in boolean
type @code{bool}, with constants @code{true} and @code{false}.  The
beginnings of run-time type identification are present, so there are
more reserved words: @code{typeid}, @code{static_cast},
@code{reinterpret_cast}, @code{const_cast}, and @code{dynamic_cast}.

@cindex g++ bugs
As with any beta-test compiler, there are bugs.  You can help improve
the compiler by submitting detailed bug reports.

One of the weakest areas of g++ other than templates is the resolution
of overloaded functions and operators in complex cases.  The usual
symptom is that in a case where the ARM says that it is ambiguous which
function should be chosen, g++ chooses one (often the first one
declared).  This is usually not a problem when porting C++ code from
other compilers to g++, but shows up as errors when code developed under
g++ is ported to other compilers.  (I believe this is no longer a
significant problem in 2.7.0).

[A full bug list would be very long indeed, so I won't put one here.
I may add a list of frequently-reported bugs and "non-bugs" like the
static class members issue mentioned above].

@node compiling standard libraries, debugging on SVR4 systems, agreement with standards, User Problems
@section Will g++ compile InterViews?  The NIH class library?

@cindex NIH class library
@cindex NIHCL with g++
The NIH class library uses a non-portable, compiler-dependent hack
to initialize itself, which makes life difficult for g++ users.
It will not work without modification, and I don't know what modifications
are required or whether anyone has done them successfully.

In short, it's not going to happen any time soon (previous FAQs referred
to patches that a new NIHCL release would hopefully contain, but this
hasn't happened).

[ From Steinar Bang <steinarb@@idt.unit.no>]

@cindex InterViews 3.1
@cindex gcc, version 2.3.3
@cindex libg++, version 2.3
InterViews 3.1 compiles and runs with gcc-2.3.3 and libg++-2.3, except
that the "doc" application immediately dumps core when you try to run it.  
There is also a small glitch with idraw.

There is a patch for InterViews 3.1 from Johan Garpendahl
<garp@@isy.liu.se> available for FTP from site ``ugle.unit.no''.
It is in the file

@file{/pub/X11/contrib/InterViews/g++/3.1-beta3-patch}.

This fixes two things: the Doc coredump, and the pattern menu of idraw.
Read the instructions at the start of the file.

I think that as of version 2.5.6, the standard g++ will compile the
standard 3.1 InterViews completely successfully.  I'd appreciate a
confirmation.

@node debugging on SVR4 systems, X11 conflicts with libg++, compiling standard libraries, User Problems
@section Debugging on SVR4 systems
@cindex System VR4, debugging

``How do I get debugging to work on my System V Release 4 system?''

Most systems based on System V Release 4 (except Solaris) encode symbolic
debugging information in a format known as `DWARF'.

Although the GNU C compiler already knows how to write out symbolic debugging
information in the DWARF format, the GNU C++ compiler does not yet have this
feature, nor is it likely to in the immediate future.

Ron Guilmette has done a great deal of work to try to get the GNU C++ compiler
to produce DWARF format symbolic debugging information (for C++ code)
but he gave up on the project because of a lack of funding and/or interest
from the g++ user community.  If you have a strong desire to see this project
completed, contact Ron at <rfg@@netcom.com>.

In the meantime, you @emph{can} get g++ debugging under SVR4 systems by
configuring gcc with the @code{--with-stabs} option.  This causes gcc to
use an alternate debugging format, one more like that used under SunOS4.
You won't need to do anything special to GDB; it will always understand
the ``stabs'' format.

@node X11 conflicts with libg++, assignment to streams, debugging on SVR4 systems, User Problems
@section X11 conflicts with libg++ in definition of String
@cindex String, conflicts in definition

``X11 and Motif define String, and this conflicts with the String class
in libg++.  How can I use both together?''

One possible method is the following:

@example
#define String XString
#include <X11/Intrinsic.h>
/* include other X11 and Motif headers */
#undef String
@end example

and remember to use the correct @code{String} or @code{XString} when
you declare things later.

@node assignment to streams, ,X11 conflicts with libg++, User Problems
@section Why can't I assign one stream to another?

[ Thanks to Per Bothner and Jerry Schwarz for this section. ]

Assigning one stream to another seems like a reasonable thing to do, but
it's a bad idea.  Usually, this comes up because people want to assign
to @code{cout}.  This is poor style, especially for libraries, and is
contrary to good object-oriented design.  (Libraries that write directly
to @code{cout} are less flexible, modular, and object-oriented).

The iostream classes do not allow assigning to arbitrary streams, because
this can violate typing:

@example
ifstream foo ("foo");
istrstream str(...);
foo = str;
foo->close ();  /* Oops! Not defined for istrstream! */
@end example

@cindex assignment to cout

The original cfront implementation of iostreams by Jerry Schwarz allows
you to assign to @code{cin}, @code{cout}, @code{cerr}, and @code{clog},
but this is not part of the draft standard for iostreams and generally
isn't considered a good idea, so standard-conforming code shouldn't use
this technique.

The GNU implementation of iostream did not support assigning to 
@code{cin}, @code{cout}, @code{cerr}, and @code{clog}
for quite a while, but it now does, for backward
compatibility with cfront iostream (versions 2.6.1 and later of libg++).

The ANSI/ISO C++ Working Paper does provide ways of changing the
streambuf associated with a stream.  Assignment isn't allowed;
there is an explicit named member that must be used.

However, it is not wise to do this, and the results are confusing.  For
example: @code{fstream::rdbuf} is supposed to return the @emph{original}
filebuf, not the one you assigned. (This is not yet implemented in GNU
iostream.)  This must be so because @code{fstream::rdbuf} is defined to
return a @code{filebuf *}.

@node legalities, index, User Problems, Top
@chapter What are the rules for shipping code built with g++ and libg++?
@cindex Shipping rules
@cindex GPL [GNU Public License]

``Is it is possible to distribute programs for profit that are created
with g++ and use the g++ libraries?''

I am not a lawyer, and this is not legal advice.  In any case, I have
little interest in telling people how to violate the spirit of the
GNU licenses without violating the letter.  This section tells you
how to comply with the intention of the GNU licenses as best I understand
them.

@cindex FSF [Free Software Foundation]
The FSF has no objection to your making money.  Its only interest is that
source code to their programs, and libraries, and to modified versions of
their programs and libraries, is always available.

The short answer is that you do not need to release the source to
your program, but you can't just ship a stripped executable either,
unless you use only the subset of libg++ that includes the iostreams
classes (see discussion below) or the new libstdc++ library (available
in libg++ 2.6.2 and later).

Compiling your code with a GNU compiler does not affect its copyright;
it is still yours.  However, in order to ship code that links in a GNU
library such as libg++ there are certain rules you must follow.  The
rules are described in the file COPYING.LIB that accompanies gcc
distributions; it is also included in the libg++ distribution.
See that file for the exact rules.  The agreement is called the
Library GNU Public License or LGPL.  It is much "looser" than the
GNU Public License, or GPL, that covers must GNU programs.

@cindex libg++, shipping code
Here's the deal: let's say that you use some version of libg++,
completely unchanged, in your software, and you want to ship only
a binary form of your code.  You can do this, but there are several
special requirements.  If you want to use libg++ but ship only object
code for your code, you have to ship source for libg++ (or ensure
somehow that your customer already has the source for the exact
version you are using), and ship your application in linkable form.
You cannot forbid your customer from reverse-engineering or extending
your program by exploiting its linkable form.

@cindex libg++, modifying
Furthermore, if you modify libg++ itself, you must provide source
for your modifications (making a derived class does not count as
modifying the library -- that is "a work that uses the library").

@cindex special copying conditions for iostreams
For certain portions of libg++ that implement required parts of the C++
language (such as iostreams and other standard classes), the FSF has
loosened the copyright requirement still more by adding the ``special
exception'' clause, which reads as follows:

@quotation
As a special exception, if you link this library with files
compiled with GCC to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public License.
This exception does not however invalidate any other reasons why
the executable file might be covered by the GNU General Public License.
@end quotation

If your only use of libg++ uses code with this exception, you may ship
stripped executables or license your executables under different
conditions without fear of violating an FSF copyright.  It is the intent
of FSF and Cygnus that, as the other classes required by the ANSI/ISO
draft standard are developed, these will also be placed under this
``special exception'' license.
The code in the new libstdc++ library, intended to implement standard
classes as defined by ANSI/ISO, is also licensed this way.

To avoid coming under the influence of the LGPL, you can link with
@file{-liostream} rather than @file{-lg++} (for version 2.6.x and
earlier), or @file{-lstdc++} now that it is available.  In version 2.7.0
all the standard classes are in @file{-lstdc++}; you can do the link
step with @code{c++} instead of @code{g++} to search only the
@file{-lstdc++} library and avoid the LGPL'ed code in @file{-lg++}.

@node index,  , legalities, Top
@comment  node-name,  next,  previous,  up
@appendix Concept Index

@printindex cp

@page
@contents
@bye

-- 
-- Joe Buck 	<jbuck@synopsys.com>	(not speaking for Synopsys, Inc)
Anagrams for "information superhighway":	Enormous hairy pig with fan
						A rough whimper of insanity

From csus.edu!csulb.edu!info.ucla.edu!library.ucla.edu!newsfeed.internetmci.com!tank.news.pipex.net!pipex!in2.uu.net!chronos.synopsys.com!news.synopsys.com!jbuck Tue Sep 19 16:09:04 1995
From: jbuck@synopsys.com (Joe Buck)
Newsgroups: gnu.g++.help,comp.lang.c++,news.answers,comp.answers
Subject: FAQ for g++ and libg++, plain text version [Revised 01 Sep 1995]
Supersedes: <g++FAQ_08_15_1995_texi@synopsys.com>
Followup-To: poster
Date: 2 Sep 1995 04:53:10 GMT
Organization: Synopsys, Inc.
Lines: 1393
Approved: news-answers-request@MIT.edu
Expires: 1 Oct 1995 00:00:00 GMT
Message-ID: <g++FAQ_09_01_1995_texi@synopsys.com>
NNTP-Posting-Host: deerslayer.synopsys.com
Originator: jbuck@deerslayer
Xref: csus.edu gnu.g++.help:10818 comp.lang.c++:138753 news.answers:51918 comp.answers:13962
Status: O

Archive-name: g++-FAQ/plain
Last-modified: 01 Sep 1995
Frequency: bimonthly

[ this is the plain text version, the parent is the texinfo version ]


Preface
*******

   This is a list of frequently asked questions (FAQ) for g++ users;
thanks to all those who sent suggestions for improvements.  Thanks to
Marcus Speh for doing the index.

   Please send updates and corrections to the FAQ to
`jbuck@synopsys.com'.  Please do *not* use me as a resource to get your
questions answered; that's what gnu.g++.help is for and I don't have
the time to support the net's use of g++.

   Many FAQs, including this one, are available on the archive site
rtfm.mit.edu, in the directory `pub/usenet/news.answers'.  This FAQ may
be found in the subdirectory g++-FAQ.

   This FAQ is intended to supplement, not replace, Marshall Cline's
excellent FAQ for the C++ language and for the newsgroup comp.lang.c++.
Especially if g++ is the first C++ compiler you've ever used, the
question "How do I do <X> with g++?" is probably really "How do I do
<X> in C++?".  You can find this FAQ on rtfm.mit.edu under
`pub/usenet/comp.lang.c++'.

The latest poop - gcc-2.7.0
***************************

   This section is intended to describe more recent changes to g++,
libg++, and such.  Some things in this section will eventually move
elsewhere.

   The big news is that version 2.7.0 has just been released.  This, of
course, means new FAQs.  I haven't had a lot of time to whip out this
section yet, so suggestions for improvement are welcome.

gcc-2.7.0 breaks declarations in "for" statements!
==================================================

   gcc-2.7.0 implements the new ANSI/ISO rule on the scope of variables
declared in for loops.

     for (int i = 1; i <= 10; i++) {
             // do something here
     }
     foo(i);

   In the above example, most existing C++ compilers would pass the
value 11 to the function `foo'.  In gcc 2.7 and in the ANSI/ISO working
paper, the scope of `i' is only the for loop body, so this is an error.
So that old code can be compiled, the new gcc has a flag
`-fno-for-scope' that causes the old rule to be used.

What's new in version 2.7.0 of gcc/g++
======================================

   The long-awaited version 2.7.0 of gcc/g++ (along with a matching
version of libg++) have now been released.  This represents a great deal
of work on the part of the g++ maintainers to fix outstanding bugs and
move the compiler closer to the current ANSI/ISO standards committee's
working paper, including supporting many of the new features that have
been added to the language.  I recommend that everyone read the NEWS
file contained in the distribution (and that system administrators make
the file available to their users).  I've borrowed liberally from this
file here.

   If any features seem unfamiliar, you will probably want to look at
the recently-released public review copy of the C++ Working Paper.  For
PostScript and PDF (Adobe Acrobat) versions, see the archive at
ftp://research.att.com/dist/stdc++/WP.  For HTML and ASCII versions,
see ftp://ftp.cygnus.com/pub/g++.  On the World Wide Web, see
http://www.cygnus.com/~mrs/wp-draft.

   * As described above, the scope of variables declared in the
     initialization part of a for statement has been changed; such
     variables are now visible only in the loop body.  Use
     `-fno-for-scope' to get the old behavior.  You'll need this flag
     to build groff version 1.09, Ptolemy, and many others.

   * Code that does not use #pragma interface/implementation will most
     likely shrink dramatically, as g++ now only emits the vtable for a
     class in the translation unit where its first non-inline,
     non-abstract virtual function is defined.

   * Support for automatic template instantiation has *not* been enabled
     in the official distribution, due to a disagreement over design
     philosophies.  But you can get a patch from Cygnus to turn it on;
     retrieve the patch from
     `ftp://ftp.cygnus.com/pub/g++/gcc-2.7.0-repo.gz'.

   * Support for exception handling has been improved; more targets are
     now supported, and throws will use the RTTI mechanism to match
     against the catch parameter type.  You must give the
     `-fhandle-exceptions' to turn it on.  Optimization is *not
     supported* with `-fhandle-exceptions'; no need to report this as a
     bug.  You'll probably get an internal compiler error if you try it.

     For exception handling to work your CPU must be a SPARC,
     RS6000/PowerPC, 386/486/Pentium, or ARM.  Other platforms are
     missing the function to unwind the stack.

   * Support for Run-Time Type Identification has been added with
     `-frtti'.  This support is still in alpha; one major restriction
     is that any file compiled with `-frtti' must include `<typeinfo>'
     (*not* `typeinfo.h' as the NEWS file says).  Also, all code you
     link with (including libg++) has to be built with `-frtti', so
     it's still tricky to use.

   * Synthesis of compiler-generated constructors, destructors and
     assignment operators is now deferred until the functions are used.

   * The parsing of expressions such as `a ? b : c = 1' has changed from
     `(a ? b : c) = 1' to `a : b ? (c = 1)'.  This is a new C/C++
     incompatibility brought to you by the ANSI/ISO standards committee.

   * The operator keywords and, and_eq, bitand, bitor, compl, not,
     not_eq, or, or_eq, xor and xor_eq are now supported.  Use `-ansi'
     or `-foperator-names' to enable them.

   * The `explicit' keyword is now supported.  `explicit' is used to
     mark constructors and type conversion operators that should not be
     used implicitly.

   * Handling of user-defined type conversion has been improved.

   * Explicit instantiation of template methods is now supported.  Also,
     `inline template class foo<int>;' can be used to emit only the
     vtable for a template class.

   * With -fcheck-new, g++ will check the return value of all calls to
     operator new, and not attempt to modify a returned null pointer.

   * collect2 now demangles linker output, and c++filt has become part
     of the gcc distribution.

   * Improvements to template instantiation: only members actually used
     are instantiated.

How do I use the new repository code?
=====================================

   Because there is some disagreement about the details of the template
repository mechanism, you'll need to obtain a patch from Cygnus Support
to enable the 2.7.0 repository code.  You can obtain the patch by
anonymous FTP: `ftp://ftp.cygnus.com/pub/g++/gcc-2.7.0-repo.gz'.

   After you've applied the patch, the `-frepo' flag will enable the
repository mechanism.  The flag works much like the existing
`-fno-implicit-templates' flag, except that auxiliary files, with an
`.rpo' extension, are built that specify what template expansions are
needed.  At link time, the (patched) collect program detects missing
templates and recompiles some of the object files so that the required
templates are expanded.

   Note that the mechanism differs from that of cfront in that template
definitions still must be visible at the point where they are to be
expanded.  No assumption is made that `foo.C' contains template
definitions corresponding to template declarations in `foo.h'.

   Jason Merrill writes: "To perform closure on a set of objects, just
try to link them together.  It will fail, but as a side effect all
needed instances will be generated in the objects."

The GNU Standard C++ Library
============================

   The GNU Standard C++ Library (also called the "GNU ANSI C++ Library"
in places in the code) is not libg++, though it is included in the
libg++ distribution.  Rather, it contains classes and functions
required by the ANSI/ISO standard.  The copyright conditions are the
same as those for for the iostreams classes; the LGPL is not used.  See
*Note legalities::.

   This library, libstdc++, is in the libg++ distribution in versions
2.6.2 and later.  It requires at least gcc 2.6.3 to build the
libg++-2.6.2 version; use at least gcc 2.7.0 to build the libg++ 2.7.0
version.  It contains a hacked-up version of HP's implementation of the
Standard Template Library (see *Note Standard Template Library::).  I've
successfully used this Standard Template Library version to build a
number of the demos you'll see on various web pages.

   As of version 2.7.0, the streams classes are now in libstdc++
instead of libg++, and libiostream is being phased out (don't use it).
The g++ program searches this library.

Obtaining Source Code
*********************

What is the latest version of gcc, g++, and libg++?
===================================================

   The latest "2.x" version of gcc/g++ is 2.7.0, released June 16, 1995.
The latest version of libg++ is 2.7.0a, released June 19, 1995 (2.7.0
had an error in a makefile and was almost immediately replaced).  .
Don't use 2.5.x, with x less than 5, for C++ code; there were some
serious bugs that didn't have easy workarounds.  2.5.8 is the most
solid 2.5.x release.  2.6.3 is the most solid 2.6.x release.

   For some non-Unix platforms, the latest port of gcc may be an earlier
version (2.5.8, say).  You'll need to use a version of libg++ that has
the same first two digits as the compiler version, e.g. use libg++
2.5.x (for the latest x you can find) with gcc version 2.5.8.

   The latest "1.x" version of gcc is 1.42, and the latest "1.x"
version of g++ is 1.42.0.  While gcc 1.42 is quite usable for C
programs, I recommend against using g++ 1.x except in special
circumstances (and I can't think of any such circumstances).

How do I get a copy of g++ for Unix?
====================================

   First, you may already have it if you have gcc for your platform;
g++ and gcc are combined now (as of gcc version 2.0).

   You can get g++ from a friend who has a copy, by anonymous FTP or
UUCP, or by ordering a tape or CD-ROM from the Free Software Foundation.

   The Free Software Foundation is a nonprofit organization that
distributes software and manuals to raise funds for more GNU
development.  Getting your copy from the FSF contributes directly to
paying staff to develop GNU software.  CD-ROMs cost $400 if an
organization is buying, or $100 if an individual is buying.  Tapes cost
around $200 depending on media type.  I recommend asking for version 2,
not version 1, of g++.

   For more information about ordering from the FSF, contact
gnu@prep.ai.mit.edu, phone (617) 542-5942 or anonymous ftp file
`ftp://prep.ai.mit.edu/pub/gnu/GNUinfo/ORDERS' (you can also use one of
the sites listed below if you can't get into "prep").

   Here is a list of anonymous FTP archive sites for GNU software.  If
no directory is given, look in `/pub/gnu'.

     ASIA: ftp.cs.titech.ac.jp, utsun.s.u-tokyo.ac.jp:/ftpsync/prep,
     cair.kaist.ac.kr, ftp.nectec.or.th:/pub/mirrors/gnu
     
     AUSTRALIA: archie.oz.au:/gnu (archie.oz or archie.oz.au for ACSnet)
     
     AFRICA: ftp.sun.ac.za
     
     MIDDLE-EAST: ftp.technion.ac.il:/pub/unsupported/gnu
     
     EUROPE: irisa.irisa.fr, ftp.univ-lyon1.fr:, ftp.mcc.ac.uk,
     unix.hensa.ac.uk:/pub/uunet/systems/gnu, ftp.denet.dk,
     src.doc.ic.ac.uk:/gnu, ftp.eunet.ch, nic.switch.ch:/mirror/gnu,
     ftp.informatik.rwth-aachen.de, ftp.informatik.tu-muenchen.de,
     ftp.win.tue.nl, ftp.funet.fi, ftp.stacken.kth.se, isy.liu.se,
     ftp.luth.se:/pub/unix/gnu, ftp.sunet.se, archive.eu.net
     
     SOUTH AMERICA: ftp.unicamp.br, ftp.inf.utfsm.cl
     
     WESTERN CANADA: ftp.cs.ubc.ca:/mirror2/gnu
     
     USA: wuarchive.wustl.edu:/systems/gnu, labrea.stanford.edu,
     ftp.digex.net, ftp.kpc.com:/pub/mirror/gnu,
     f.ms.uky.edu:/pub3/gnu, jaguar.utah.edu:/gnustuff,
     ftp.hawaii.edu:/mirrors/gnu, vixen.cso.uiuc.edu:/gnu,
     mrcnext.cso.uiuc.edu, ftp.cs.columbia.edu:/archives/gnu/prep,
     col.hp.com:/mirrors/gnu, gatekeeper.dec.com:/pub/GNU,
     ftp.uu.net:/systems/gnu

   The "official site" is prep.ai.mit.edu, but your transfer will
probably go faster if you use one of the above machines.

   Most GNU utilities are compressed with "gzip", the GNU compression
utility.  All GNU archive sites should have a copy of this program,
which you will need to uncompress the distributions.

   UUNET customers can get GNU sources from UUNET via UUCP.  UUCP-only
sites can get GNU sources by "anonymous UUCP" from site "osu-cis" at
Ohio State University.  You pay for the long-distance call to OSU; the
price isn't too bad on weekends at 9600 bps.  Send mail to
uucp@cis.ohio-state.edu or osu-cis!uucp for more information.

   OSU lines are often busy.  If you're in the USA, and are willing to
spend more money, you can get sources via UUCP from UUNET using their
900 number: 1-900-GOT-SRCS (900 numbers don't work internationally).
You will be billed $0.50/minute by your phone company.

   Don't forget to retrieve libg++ as well!

Getting gcc/g++ for the HP Precision Architecture
=================================================

   If you use the HP Precision Architecture (HP-9000/7xx and
HP-9000/8xx) and you want to use debugging, you'll need to use the GNU
assembler, GAS (version 2.3 or later).  If you build from source, you
must tell the configure program that you are using GAS or you won't get
debugging support.  A non-standard debug format is used, since until
recently HP considered their debug format a trade secret.  Thanks to
the work of lots of good folks both inside and outside HP, the company
has seen the error of its ways and has now released the required
information.  The team at the University of Utah that did the gcc port
now has code that understands the native HP format.

   Some enhancements for the HP that haven't been integrated back into
the official GCC are available from the University of Utah, site
jaguar.cs.utah.edu.  You can retrieve sources and prebuilt binaries for
GCC, GDB, binutils,and libg++; see the directory `/dist'.

   The libg++ version is actually the same as the FSF 2.6.  The Utah
version of GDB can now understand both the GCC and HP C compiler debug
formats, so it is no longer necessary to have two different GDB
versions.

   I recommend that HP users use the Utah versions of the tools (see
above), though at this point the standard FSF versions will work well.

   HP GNU users can also find useful stuff on the site geod.emr.ca in
the `/pub/UNIX/GNU-HP' directory.

   Jeff Law is leaving the University of Utah, so the Utah prebuilt
binaries may be discontinued.

Getting gcc/g++ binaries for Solaris 2.x
========================================

   "Sun took the C compiler out of Solaris 2.x.  Am I stuck?"

   No; prep.ai.mit.edu and its mirror sites provide GCC binaries for
Solaris.  As a rule, these binaries are not updated as often as the
sources are, so if you want the very latest version of gcc/g++, you may
need to grab and install binaries for an older version and use it to
bootstrap the latest version from source.

   The latest gcc binaries on prep.ai.mit.edu and its mirror sites are
for version 2.5.6 for Solaris on the Sparc, and version 2.4.5 for
Solaris on Intel 386/486 machines.  There are also binaries for "gzip",
the GNU compression utility, which you'll need for uncompressing the
binary distribution.  On any GNU archive site, look in subdirectories
`i486-sun-solaris2' or `sparc-sun-solaris2'.

   The ftp directory /pub/GNU on site ftp.quintus.com contains various
GNU and freeware programs for Solaris2.X running on the sparc. These are
packaged to enable installation using the Solaris "pkgadd" utility.
These include GNU emacs 19.27, gcc (and g++) 2.6.0, Perl 4.036, and
others.

How do I get a copy of g++ for (some other platform)?
=====================================================

   The standard gcc/g++ distribution includes VMS support.  Since the
FSF people don't use VMS, it's likely to be somewhat less solid than
the Unix version.  Precompiled copies of g++ and libg++ in
VMS-installable form are available by FTP from mango.rsmas.miami.edu.
See also the site ftp.stacken.kth.se (in Sweden), directory
/pub/GNU-VMS/contrib, which has gcc-2.5.8 and libg++-2.5.3.

   There are two different versions of gcc/g++ for MS-DOS: EMX and
DJGPP.  EMX also works for OS/2 and is described later.  DJGPP is DJ
Delorie's port.  It can be found on many FTP archive sites; its "home"
is on oak.oakland.edu, directory `~ftp/pub/msdos/djgpp'.

   The latest version of DJGPP is 1.12.maint1.  This version runs under
Windows 3.x.  It includes a port of gcc 2.6.0, plus support software.

   FSF sells floppies with DJGPP on them; see above for ordering
software from the FSF.

   A new Usenet group, `comp.os.msdos.djgpp', has recently been created.

   For information on Amiga ports of gcc/g++, retrieve the file
`/pub/gnu/MicrosPorts/Amiga' from prep.ai.mit.edu, or write to Markus
M. Wild <wild@nessie.cs.id.ethz.ch>, who I hope won't be too upset that
I mentioned his name here.

   A port of gcc to the Atari ST can be found on the site
"atari.archive.umich.edu", under `/atari/Gnustuff/Tos', along with many
other GNU programs.  This version is usually the same as the latest FSF
release.  See the "Software FAQ" for the Usenet group
"comp.sys.atari.st" for more information.

   There are two different ports of gcc to OS/2, the so-called EMX port
(which also runs on MS-DOS), and a port called "gcc/2".  The EMX port's
C library attempts to provide a Unix-like environment; gcc/2 uses a
rather buggy port of the BSD libc.  For more information ask around on
"comp.os.os2.programmer.misc".

   The EMX port is available by FTP from

     ftp.uni-stuttgart.de(129.69.1.12) in /pub/systems/os2/emx-0.9a
     src.doc.ic.ac.uk(146.169.2.1) in /pub/packages/os2/unix/emx09a
     ftp.informatik.tu-muenchen.de(131.159.0.198) in
             /pub/comp/os/os2/devtools/emx+gcc

   gcc/2, together with other GNUware for OS/2, can be obtained by FTP
from

     ftp-os2.cdrom.com(192.153.46.2) in /pub/os2/2_x/unix/gnu
     ftp-os2.nmsu.edu (128.123.35.151) in /pub/os2/2_x/unix/gnu
     luga.latrobe.edu.au (131.172.2.2) in /pub/os2/2_x/unix/gnu

   The current maintainer of the gcc/2 port is Colin Jensen (Michael
Johnson did the original port).  His address is cjensen@netcom.com.

   Eberhard Mattes did the EMX port.  His address is
mattes@azu.informatik.uni-stuttgart.de.

   I'm looking for more information on gcc/g++ support on the Apple
Macintosh.  Until recently, this FAQ did not provide such information,
but FSF is no longer boycotting Apple as the League for Programming
Freedom boycott has been dropped.

   Mike White (cons116@twain.oit.umass.edu) says: "Versions 1.37.1 and
2.3.3 of gcc were ported by Stan Shebs and are available at
ftp.cygnus.com under /pub/shebs.  They are both interfaced to MPW.
Shebs is apparently working on a cross compiler of 2.6.3 to create Mac
apps from Unix boxes."

   I don't know anything about more recent versions.

But I can only find g++-1.42!
=============================

   "I keep hearing people talking about g++ 2.5.8 (or some other number
starting with 2), but the latest version I can find is g++ 1.42.  Where
is it?"

   As of gcc 2.0, C, C++, and Objective-C as well are all combined into
a single distribution called gcc.  If you get gcc you already have g++.
The standard installation procedure for any gcc version 2 compiler will
install the C++ compiler as well.

   One could argue that we shouldn't even refer to "g++-2.x.y" but it's
a convention.  It means "the C++ compiler included with gcc-2.x.y."

Installation Issues and Problems
********************************

I can't build g++ 1.x.y with gcc-2.x.y!
=======================================

   "I obtained gcc-2.x.y and g++ 1.x.y and I'm trying to build it, but
I'm having major problems.  What's going on?"

   If you wish to build g++-1.42, you must obtain gcc-1.42 first.  The
installation instructions for g++ version 1 leave a lot to be desired,
unfortunately, and I would recommend that, unless you have a special
reason for needing the 1.x compiler, that C++ users use the latest
g++-2.x version, as it is the version that is being actively maintained.

   There is no template support in g++-1.x, and it is generally much
further away from the ANSI draft standard than g++-2.x is.

OK, I've obtained gcc; what else do I need?
===========================================

   First off, you'll want libg++ as you can do almost nothing without it
(unless you replace it with some other class library).

   Second, depending on your platform, you may need "GAS", the GNU
assembler, or the GNU linker (see next question).

   Finally, while it is not required, you'll almost certainly want the
GNU debugger, gdb.  The latest version is 4.14, released March 2, 1995.
Other debuggers (like dbx, for example) will normally not be able to
understand at least some of the debug information produced by g++.

Should I use the GNU linker, or should I use "collect"?
=======================================================

   First off, for novices: special measures must be taken with C++ to
arrange for the calling of constructors for global or static objects
before the execution of your program, and for the calling of
destructors at the end.  (Exception: System VR3 and System VR4 linkers,
Linux/ELF, and some other systems support user-defined segments; g++ on
these systems requires neither the GNU linker nor collect.  So if you
have such a system, the answer is that you don't need either one).

   If you have experience with AT&T's "cfront", this function is
performed there by programs named "patch" or "munch".  With GNU C++, it
is performed either by the GNU linker or by a program known as
"collect".  The collect program is part of the gcc-2.x distribution;
you can obtain the GNU linker separately as part of the "binutils"
package.  The latest version of binutils is 2.5.2, released November 2,
1994.

   (To be technical, it's "collect2"; there were originally several
alternative versions of collect, and this is the one that survived).

   There are advantages and disadvantages to either choice.

   Advantages of the GNU linker:

   It's faster than using collect - collect basically runs the standard
Unix linker on your program twice, inserting some extra code after the
first pass to call the constructors.  This is a sizable time penalty
for large programs.  The GNU linker does not require this extra pass.

   GNU ld reports undefined symbols using their true names, not the
mangled names (but as of 2.7.0 so does collect).

   If there are undefined symbols, GNU ld reports which object file(s)
refer to the undefined symbol(s).

   As of binutils version 2.2, on systems that use the so-called "a.out"
debug format (e.g. Suns running SunOS 4.x), the GNU linker compresses
the debug symbol table considerably.

   Advantages of collect:

   If your native linker supports shared libraries, you can use shared
libraries with collect.  This used to be a strong reason *not* to use
the GNU linker, but recent versions of GNU ld support linking with
shared libraries on many platforms, and creating shared libraries on a
few (such as Intel x86 systems that use ELF object format).

   Note: using existing shared libraries (X and libc, for example) works
very nicely.  Generating shared libraries from g++-compiled code is
another matter, generally requiring OS-dependent tricks if it is
possible at all.  But progress has been made recently.

   As of 2.7.0, building C++ shared libraries should work fine on
supported platforms (HPUX 9+, IRIX 5+, DEC UNIX (formerly OSF/1), SunOS
4, and all targets using SVR4-style ELF shared libraries).

   However, as of libg++ 2.6.2, the libg++ distribution contains some
patches to build libg++ as a shared library on some OSes (those listed
above).  Check the file `README.SHLIB' from that distribution.

   The GNU linker has not been ported to as many platforms as g++ has,
so you may be forced to use collect.

   If you use collect, you don't need to get something extra and figure
out how to install it; the standard gcc installation procedure will do
it for you.

   In conclusion, I don't see a clear win for either alternative at this
point.  Take your pick.

Should I use the GNU assembler, or my vendor's assembler?
=========================================================

   This depends on your platform and your decision about the GNU
linker.  For most platforms, you'll need to use GAS if you use the GNU
linker.  For some platforms, you have no choice; check the gcc
installation notes to see whether you must use GAS.  But you can
usually use the vendor's assembler if you don't use the GNU linker.

   The GNU assembler assembles faster than many native assemblers;
however, on many platforms it cannot support the local debugging format.

   If you want to build shared libraries from gcc/g++ output and you
are on a Sun, you must *not* use GNU as, as it cannot do
position-independent code correctly yet.

   On HPUX or IRIX, you must use GAS (and configure gcc with the
`--with-gnu-as' option) to debug your programs.  GAS is strongly
recommended particularly on the HP platform because of limitations in
the HP assembler.

   The GAS distribution has recently been merged with the binutils
distribution, so the GNU assembler and linker are now together in this
package (as of binutils version 2.5.1).

Should I use the GNU C library?
===============================

   At this point in time, no.  The GNU C library is still very young,
and libg++ still conflicts with it in some places.  Use your native C
library unless you know a lot about the gory details of libg++ and
gnu-libc.  This will probably change in the future.

Global constructors aren't being called
=======================================

   "I've installed gcc and it almost works, but constructors and
destructors for global objects and objects at file scope aren't being
called.  What did I do wrong?"

   It appears that you are running on a platform that requires you to
install either "collect2" or the GNU linker, and you have done neither.
For more information, see the section discussing the GNU linker (*Note
use GNU linker?::).

   On Solaris 2.x, you shouldn't need a collect program and GNU ld
doesn't run.  If your global constructors aren't being called, you may
need to install a patch, available from Sun, to fix your linker.  The
number of the "jumbo patch" that applies is 101409-03.  Thanks to
Russell Street (r.street@auckland.ac.nz) for this info.

   It appears that on IRIX, the collect2 program is not being installed
by default during the installation process, though it is required; you
can install it manually by executing

     make install-collect2

   from the gcc source directory after installing the compiler.  (I'm
not certain for which versions of gcc this problem occurs, and whether
it is still present).

Strange assembler errors when linking C++ programs
==================================================

   "I've installed gcc and it seemed to go OK, but when I attempt to
link any C++ program, I'm getting strange errors from the assembler!
How can that be?"

   The messages in question might look something like

     as: "/usr/tmp/cca14605.s", line 8: error: statement syntax
     as: "/usr/tmp/cca14605.s", line 14: error: statement syntax

   (on a Sun, different on other platforms).  The important thing is
that the errors come out at the link step, *not* when a C++ file is
being compiled.

   Here's what's going on: the collect2 program uses the Unix "nm"
program to obtain a list of symbols for the global constructors and
destructors, and it builds a little assembly language module that will
permit them all to be called.  If you're seeing this symptom, you have
an old version of GNU nm somewhere on your path.  This old version
prints out symbol names in a format that the collect2 program does not
expect, so bad assembly code is generated.

   The solution is either to remove the old version of GNU nm from your
path (and that of everyone else who uses g++), or to install a newer
version (it is part of the GNU "binutils" package).  Recent versions of
GNU nm do not have this problem.

Other problems building libg++
==============================

   "I am having trouble building libg++.  Help!"

   On some platforms (for example, Ultrix), you may see errors
complaining about being unable to open dummy.o.  On other platforms
(for example, SunOS), you may see problems having to do with the type
of size_t.  The fix for these problems is to make libg++ by saying
"make CC=gcc".  According to Per Bothner, it should no longer be
necessary to specify "CC=gcc" for libg++-2.3.1 or later.

   "I built and installed libg++, but g++ can't find it.  Help!"

   The string given to `configure' that identifies your system must be
the same when you install libg++ as it was when you installed gcc.
Also, if you used the `--prefix' option to install gcc somewhere other
than `/usr/local', you must use the same value for `--prefix' when
installing libg++, or else g++ will not be able to find libg++.

   The toplevel Makefile in the libg++ 2.6.2 distribution is broken,
which along with a bug in g++ 2.6.3 causes problems linking programs
that use the libstdc++ complex classes.  A patch for this is available
from `ftp.cygnus.com:pub/g++/libg++-2.6.2-fix.gz'.

But I'm *still* having problems with `size_t'!
==============================================

   "I did all that, and I'm *still* having problems with disagreeing
definitions of size_t, SIZE_TYPE, and the type of functions like
`strlen'."

   The problem may be that you have an old version of `_G_config.h'
lying around.  As of libg++ version 2.4, `_G_config.h', since it is
platform-specific, is inserted into a different directory; most include
files are in `$prefix/lib/g++-include', but this file now lives in
`$prefix/$arch/include'.  If, after upgrading your libg++, you find that
there is an old copy of `_G_config.h' left around, remove it, otherwise
g++ will find the old one first.

Do I need to rebuild libg++ to go with my new g++?
==================================================

   "After I upgraded g++ to the latest version, I'm seeing undefined
symbols."

   or

   "If I upgrade to a new version of g++, do I need to reinstall
libg++?"

   As a rule, the first two digits of your g++ and libg++ should be the
same.  Normally when you do an upgrade in the "minor version number"
(2.5.7 to 2.5.8, say) there isn't a need to rebuild libg++, but there
have been a couple of exceptions in the past.

User Problems
*************

How to silence "unused parameter" warnings
==========================================

   "When I use `-Wall' (or `-Wunused'), g++ warns about unused
parameters.  But the parameters have to be there, for use in derived
class functions.  How do I get g++ to stop complaining?"

   The answer is to simply omit the names of the unused parameters when
defining the function.  This makes clear, both to g++ and to readers of
your code, that the parameter is unused.  For example:

     int Foo::bar(int arg) { return 0; }

   will give a warning for the unused parameter `arg'.  To suppress the
warning write

     int Foo::bar(int) { return 0; }

g++ objects to a declaration in a case statement
================================================

   "The compiler objects to my declaring a variable in one of the
branches of a case statement.  Earlier versions used to accept this
code.  Why?"

   The draft standard does not allow a goto or a jump to a case label to
skip over an initialization of a variable or a class object.  For
example:

       switch ( i )
         {
           case 1:
             Object obj(0);
             ...
     	break;
           case 2:
     	...
     	break;
           }

   The reason is that `obj' is also in scope in the rest of the switch
statement.

   As of version 2.7.0, the compiler will object that the jump to the
second case level crosses the initialization of `obj'.  Older compiler
versions would object only if class Object has a destructor.  In either
case, the solution is to add a set of curly braces around the case
branch:

           case 1:
            {
             Object obj(0);
             ...
     	break;
            }

gcc 2.5.x broke my code!  Changes in function overloading
=========================================================

   "I have a program that worked just fine with older g++ versions, but
as of version 2.5.x it doesn't work anymore.  Help!"

   While it's always possible that a new bug has been introduced into
the compiler, it's also possible that you have been relying on bugs in
older versions of g++.  For example, version 2.5.0 was the first
version of g++ to correctly implement the "hiding rule."  That is, if
you have an overloaded function in a base class, and in a derived class
you redefine one of the names, the other names are effectively "hidden".
*All* the names from the baseclass need to be redefined in the derived
class.  See section 13.1 of the ARM: "A function member of a derived
class is *not* in the same scope as a function member of the same name
in a base class".

   Here's an example that is handled incorrectly by g++ versions before
2.5.0 and correctly by newer versions:

     class Base {
     public:
         void foo(int);
     };
     
     class Derived : public Base {
     public:
         void foo(double);  // *note that Base::foo(int) is hidden*
     };
     
     main() {
         Derived d;
         d.foo(2); // *Derived::foo(double), not Base::foo(int), is called*
     }

Where can I find a demangler?
=============================

   A g++-compatible demangler named `c++filt' can be found in the
`binutils' distribution.  This distribution (which also contains the
GNU linker) can be found at any GNU archive site.

   As of version 2.7.0, `c++filt' is included with gcc and is installed
automatically.  Even better, it is used by the `collect' linker, so you
don't see mangled symbols anymore.

Where can I find a version of etags for C++?
============================================

   The libg++ distribution contains a version of etags that works for
C++ code.  Look in `libg++/utils'.  It's not built by default when you
install libg++, but you can cd to that directory and type

     make etags

   after you've installed libg++.

Linker reports undefined symbols for static data members
========================================================

   "g++ reports undefined symbols for all my static data members when I
link, even though the program works correctly for compiler XYZ.  What's
going on?"

   The problem is almost certainly that you don't give definitions for
your static data members.  If you have

     class Foo {
     	...
     	void method();
     	static int bar;
     };

   you have only declared that there is an int named Foo::bar and a
member function named Foo::method that is defined somewhere.  You still
need to defined BOTH method() and bar in some source file.  According
to the draft ANSI standard, you must supply an initializer, such as

     int Foo::bar = 0;

in one (and only one) source file.

What does "Internal compiler error" mean?
=========================================

   It means that the compiler has detected a bug in itself.
Unfortunately, g++ still has many bugs, though it is a lot better than
it used to be.  If you see this message, please send in a complete bug
report (see next section).

I think I have found a bug in g++.
==================================

   "I think I have found a bug in g++, but I'm not sure.  How do I know,
and who should I tell?"

   First, see the excellent section on bugs and bug reports in the gcc
manual (which is included in the gcc distribution).  As a short summary
of that section: if the compiler gets a fatal signal, for any input,
it's a bug (newer versions of g++ will ask you to send in a bug report
when they detect an error in themselves).  Same thing for producing
invalid assembly code.

   When you report a bug, make sure to describe your platform (the type
of computer, and the version of the operating system it is running) and
the version of the compiler that you are running.  See the output of the
command `g++ -v' if you aren't sure.  Also provide enough code so that
the g++ maintainers can duplicate your bug.  Remember that the
maintainers won't have your header files; one possibility is to send
the output of the preprocessor (use `g++ -E' to get this).  This is
what a "complete bug report" means.

   I will add some extra notes that are C++-specific, since the notes
from the gcc documentation are generally C-specific.

   First, mail your bug report to "bug-g++@prep.ai.mit.edu".  You may
also post to gnu.g++.bug, but it's better to use mail, particularly if
you have any doubt as to whether your news software generates correct
reply addresses.  Don't mail C++ bugs to bug-gcc@prep.ai.mit.edu.

   If your bug involves libg++ rather than the compiler, mail to
bug-lib-g++@prep.ai.mit.edu.  If you're not sure, choose one, and if you
guessed wrong, the maintainers will forward it to the other list.

   Second, if your program does one thing, and you think it should do
something else, it is best to consult a good reference if in doubt.
The standard reference is the draft working paper from the ANSI/ISO C++
standardization committee, which you can get on the net.  For
PostScript and PDF (Adobe Acrobat) versions, see the archive at
ftp://research.att.com/dist/stdc++/WP.  For HTML and ASCII versions,
see ftp://ftp.cygnus.com/pub/g++.  On the World Wide Web, see
http://www.cygnus.com/~mrs/wp-draft.

   An older standard reference is "The Annotated C++ Reference Manual",
by Ellis and Stroustrup (copyright 1990, ISBN #0-201-51459-1).  This is
what they're talking about on the net when they refer to "the ARM".
But you should know that changes have been made to the language since
then.

   The ANSI/ISO C++ standards committee have adopted some changes to the
C++ language since the publication of the original ARM, and newer
versions of g++ (2.5.x and later) support some of these changes, notably
the mutable keyword (added in 2.5.0), the bool type (added in 2.6.0),
and changes in the scope of variables defined in for statements (added
in 2.7.0).  You can obtain an addendum to the ARM explaining these
changes by FTP from ftp.std.com in `/AW/stroustrup2e/new_iso.ps'.

   Note that the behavior of (any version of) AT&T's "cfront" compiler
is NOT the standard for the language.

Porting programs from other compilers to g++
============================================

   "I have a program that runs on <some other C++ compiler>, and I want
to get it running under g++.  Is there anything I should watch out for?"

   Note that g++ supports many of the newer keywords that have recently
been added to the language.  Your other C++ compiler may not support
them, so you may need to rename variables and members that conflict
with these keywords.

   There are two other reasons why a program that worked under one
compiler might fail under another: your program may depend on the order
of evaluation of side effects in an expression, or it may depend on the
lifetime of a temporary (you may be assuming that a temporary object
"lives" longer than the standard guarantees).  As an example of the
first:

     void func(int,int);
     
     int i = 3;
     func(i++,i++);

   Novice programmers think that the increments will be evaluated in
strict left-to-right order.  Neither C nor C++ guarantees this; the
second increment might happen first, for example.  func might get 3,4,
or it might get 4,3.

   The second problem often happens with classes like the libg++ String
class.  Let's say I have

     String func1();
     void func2(const char*);

   and I say

     func2(func1());

   because I know that class String has an "operator const char*".  So
what really happens is

     func2(func1().convert());

   where I'm pretending I have a convert() method that is the same as
the cast.  This is unsafe in g++ versions before 2.6.0, because the
temporary String object may be deleted after its last use (the call to
the conversion function), leaving the pointer pointing to garbage, so by
the time func2 is called, it gets an invalid argument.

   Both the cfront and the old g++ behaviors are legal according to the
ARM, but the powers that be have decided that compiler writers were
given too much freedom here.

   The ANSI C++ committee has now come to a resolution of the lifetime
of temporaries problem: they specify that temporaries should be deleted
at end-of-statement (and at a couple of other points).  This means that
g++ versions before 2.6.0 now delete temporaries too early, and cfront
deletes temporaries too late.  As of version 2.6.0, g++ does things
according to the new standard.

   For now, the safe way to write such code is to give the temporary a
name, which forces it to live until the end of the scope of the name.
For example:

     String& tmp = func1();
     func2(tmp);

   Finally, like all compilers (but especially C++ compilers, it seems),
g++ has bugs, and you may have tweaked one.  If so, please file a bug
report (after checking the above issues).

Why does g++ mangle names differently from other C++ compilers?
===============================================================

   See the answer to the next question.

Why can't g++ code link with code from other C++ compilers?
===========================================================

   "Why can't I link g++-compiled programs against libraries compiled by
some other C++ compiler?"

   Some people think that, if only the FSF and Cygnus Support folks
would stop being stubborn and mangle names the same way that, say,
cfront does, then any g++-compiled program would link successfully
against any cfront-compiled library and vice versa.  Name mangling is
the least of the problems.  Compilers differ as to how objects are laid
out, how multiple inheritance is implemented, how virtual function
calls are handled, and so on, so if the name mangling were made the
same, your programs would link against libraries provided from other
compilers but then crash when run.  For this reason, the ARM
*encourages* compiler writers to make their name mangling different
from that of other compilers for the same platform.  Incompatible
libraries are then detected at link time, rather than at run time.

What documentation exists for g++ 2.x?
======================================

   Relatively little.  While the gcc manual that comes with the
distribution has some coverage of the C++ part of the compiler, it
focuses mainly on the C compiler (though the information on the "back
end" pertains to C++ as well).  Still, there is useful information on
the command line options and the #pragma interface and #pragma
implementation directives in the manual, and there is a useful section
on template instantiation in the 2.6 version.  There is a Unix-style
manual entry, "g++.1", in the gcc-2.x distribution; the information
here is a subset of what is in the manual.

   You can buy a nicely printed and bound copy of this manual from the
FSF; see above for ordering information.

   For versions 2.6.2 and later, the gcc/g++ distribution contains the
gcc manual in PostScript.  Also, Postscript versions of GNU
documentation in U.S. letter format are available by anonymous FTP to
primus.com in /pub/gnu-ps.  The same, in A4 format, are on
liasun3.epfl.ch in /pub/gnu/ps-doc.

   A draft of a document describing the g++ internals appears in the gcc
distribution (called g++int.texi); it is still incomplete.

Problems with the template implementation
=========================================

   g++ does not implement a separate pass to instantiate template
functions and classes at this point; for this reason, it will not work,
for the most part, to declare your template functions in one file and
define them in another.  The compiler will need to see the entire
definition of the function, and will generate a static copy of the
function in each file in which it is used.

   (The experimental template repository code (see *Note repository::)
that can be added to 2.7.0 does implement a separate pass, but there is
still no searching of files that the compiler never saw).

   For version 2.6.0, however, a new switch `-fno-implicit-templates'
was added; with this switch, templates are expanded only under user
control.  I recommend that all g++ users that use templates read the
section "Template Instantiation" in the gcc manual (version 2.6.x and
newer).  g++ now supports explicit template expansion using the syntax
from the latest C++ working paper:

     template class A<int>;
     template ostream& operator << (ostream&, const A<int>&);

   As of version 2.6.3, there are still a few limitations in the
template implementation besides the above (thanks to Jason Merrill for
this info):

  1. Static data member templates are not supported.  You can work
     around this by explicitly declaring the static variable for each
     template specialization:

          template <class T> struct A {
            static T t;
          };
          
          template <class T> T A<T>::t = 0; // gets bogus error
          int A<int>::t = 0;                // OK (workaround)

     (still a limitation in 2.7.0)

  2. Template member names are not available when defining member
     function templates.

          template <class T> struct A {
            typedef T foo;
            void f (foo);
            void g (foo arg) { ... }; // this works
          };
          
          template <class T> void A<T>::f (foo) { } // gets bogus error

  3. Templates are instantiated using the parser.  This results in two
     problems:

     a) Class templates are instantiated in some situations where such
     instantiation should not occur.

          template <class T> class A { };
          A<int> *aip = 0; // should not instantiate A<int> (but does)

     b) Function templates cannot be inlined at the site of their
     instantiation.

          template <class T> inline T min (T a, T b) { return a < b ? a : b; }
          
          void f () {
            int i = min (1, 0);           // not inlined
          }
          
          void g () {
            int j = min (1, 0);           // inlined
          }

     A workaround that works in version 2.6.1 and later is to specify

          extern template int min (int, int);

     before `f()'; this will force it to be instantiated (though not
     emitted).

  4. Member function templates are always instantiated when their
     containing class is.  This is wrong.

I get undefined symbols when using templates
============================================

   (Thanks to Jason Merrill for this section).

   g++ does not automatically instantiate templates defined in other
files.  Because of this, code written for cfront will often produce
undefined symbol errors when compiled with g++.  You need to tell g++
which template instances you want, by explicitly instantiating them in
the file where they are defined.  For instance, given the files

   `templates.h':
     template <class T>
     class A {
     public:
       void f ();
       T t;
     };
     
     template <class T> void g (T a);

   `templates.cc':
     #include "templates.h"
     
     template <class T>
     void A<T>::f () { }
     
     template <class T>
     void g (T a) { }

   main.cc:
     #include "templates.h"
     
     main ()
     {
       A<int> a;
       a.f ();
       g (a);
     }

   compiling everything with `g++ main.cc templates.cc' will result in
undefined symbol errors for `A<int>::f ()' and `g (A<int>)'.  To fix
these errors, add the lines

     template class A<int>;
     template void g (A<int>);

   to the bottom of `templates.cc' and recompile.

I get multiply defined symbols using templates
==============================================

   You may be running into a bug that was introduced in version 2.6.1
(and is still present in 2.6.3) that generated external linkage for
templates even when neither `-fexternal-templates' nor
`-fno-implicit-templates' is specified.  There is a patch for this
problem at ftp.cygnus.com:pub/g++/gcc-2.6.3-template-fix.  I recommend
either applying the patch or using `-fno-implicit-templates' together
with explicit template instantiation as described in previous sections.

   This bug is fixed in 2.7.0.

Does g++ support the Standard Template Library?
===============================================

   From Per Bothner:

   The Standard Template Library (STL) uses many of the extensions that
the ANSI/ISO committee has made to templates, and g++ doesn't support
some of these yet.  So if you grab HP's free implementation of STL it
isn't going to work.  However, libg++-2.6.2 contains a hacked version
of STL, based on work by Carsten Bormann, which permits gcc-2.6.3 to
compile at least the containers.  A full implementation is going to
need improved template support, which will take a while yet.

   As of libg++-2.7.0 and gcc-2.7.0, I've succeeded in making many short
STL example programs work, though there are still a number of bugs and
limitations.

What are the differences between g++ and the ARM specification of C++?
======================================================================

   As of version 2.7.0, g++ has exception support on most but not all
platforms (no support on MIPS-based platforms yet), but it doesn't work
right if optimizaton is enabled, which means the exception
implementation is still not really ready for production use.

   Some features that the ANSI/ISO standardization committee has voted
in that don't appear in the ARM are supported, notably the `mutable'
keyword, in version 2.5.x.  2.6.x adds support for the built-in boolean
type `bool', with constants `true' and `false'.  The beginnings of
run-time type identification are present, so there are more reserved
words: `typeid', `static_cast', `reinterpret_cast', `const_cast', and
`dynamic_cast'.

   As with any beta-test compiler, there are bugs.  You can help improve
the compiler by submitting detailed bug reports.

   One of the weakest areas of g++ other than templates is the
resolution of overloaded functions and operators in complex cases.  The
usual symptom is that in a case where the ARM says that it is ambiguous
which function should be chosen, g++ chooses one (often the first one
declared).  This is usually not a problem when porting C++ code from
other compilers to g++, but shows up as errors when code developed under
g++ is ported to other compilers.  (I believe this is no longer a
significant problem in 2.7.0).

   [A full bug list would be very long indeed, so I won't put one here.
I may add a list of frequently-reported bugs and "non-bugs" like the
static class members issue mentioned above].

Will g++ compile InterViews?  The NIH class library?
====================================================

   The NIH class library uses a non-portable, compiler-dependent hack
to initialize itself, which makes life difficult for g++ users.  It
will not work without modification, and I don't know what modifications
are required or whether anyone has done them successfully.

   In short, it's not going to happen any time soon (previous FAQs
referred to patches that a new NIHCL release would hopefully contain,
but this hasn't happened).

   [ From Steinar Bang <steinarb@idt.unit.no>]

   InterViews 3.1 compiles and runs with gcc-2.3.3 and libg++-2.3,
except that the "doc" application immediately dumps core when you try
to run it.  There is also a small glitch with idraw.

   There is a patch for InterViews 3.1 from Johan Garpendahl
<garp@isy.liu.se> available for FTP from site "ugle.unit.no".  It is in
the file

   `/pub/X11/contrib/InterViews/g++/3.1-beta3-patch'.

   This fixes two things: the Doc coredump, and the pattern menu of
idraw.  Read the instructions at the start of the file.

   I think that as of version 2.5.6, the standard g++ will compile the
standard 3.1 InterViews completely successfully.  I'd appreciate a
confirmation.

Debugging on SVR4 systems
=========================

   "How do I get debugging to work on my System V Release 4 system?"

   Most systems based on System V Release 4 (except Solaris) encode
symbolic debugging information in a format known as `DWARF'.

   Although the GNU C compiler already knows how to write out symbolic
debugging information in the DWARF format, the GNU C++ compiler does
not yet have this feature, nor is it likely to in the immediate future.

   Ron Guilmette has done a great deal of work to try to get the GNU
C++ compiler to produce DWARF format symbolic debugging information
(for C++ code) but he gave up on the project because of a lack of
funding and/or interest from the g++ user community.  If you have a
strong desire to see this project completed, contact Ron at
<rfg@netcom.com>.

   In the meantime, you *can* get g++ debugging under SVR4 systems by
configuring gcc with the `--with-stabs' option.  This causes gcc to use
an alternate debugging format, one more like that used under SunOS4.
You won't need to do anything special to GDB; it will always understand
the "stabs" format.

X11 conflicts with libg++ in definition of String
=================================================

   "X11 and Motif define String, and this conflicts with the String
class in libg++.  How can I use both together?"

   One possible method is the following:

     #define String XString
     #include <X11/Intrinsic.h>
     /* include other X11 and Motif headers */
     #undef String

   and remember to use the correct `String' or `XString' when you
declare things later.

Why can't I assign one stream to another?
=========================================

   [ Thanks to Per Bothner and Jerry Schwarz for this section. ]

   Assigning one stream to another seems like a reasonable thing to do,
but it's a bad idea.  Usually, this comes up because people want to
assign to `cout'.  This is poor style, especially for libraries, and is
contrary to good object-oriented design.  (Libraries that write directly
to `cout' are less flexible, modular, and object-oriented).

   The iostream classes do not allow assigning to arbitrary streams,
because this can violate typing:

     ifstream foo ("foo");
     istrstream str(...);
     foo = str;
     foo->close ();  /* Oops! Not defined for istrstream! */

   The original cfront implementation of iostreams by Jerry Schwarz
allows you to assign to `cin', `cout', `cerr', and `clog', but this is
not part of the draft standard for iostreams and generally isn't
considered a good idea, so standard-conforming code shouldn't use this
technique.

   The GNU implementation of iostream did not support assigning to
`cin', `cout', `cerr', and `clog' for quite a while, but it now does,
for backward compatibility with cfront iostream (versions 2.6.1 and
later of libg++).

   The ANSI/ISO C++ Working Paper does provide ways of changing the
streambuf associated with a stream.  Assignment isn't allowed; there is
an explicit named member that must be used.

   However, it is not wise to do this, and the results are confusing.
For example: `fstream::rdbuf' is supposed to return the *original*
filebuf, not the one you assigned. (This is not yet implemented in GNU
iostream.)  This must be so because `fstream::rdbuf' is defined to
return a `filebuf *'.

What are the rules for shipping code built with g++ and libg++?
***************************************************************

   "Is it is possible to distribute programs for profit that are created
with g++ and use the g++ libraries?"

   I am not a lawyer, and this is not legal advice.  In any case, I have
little interest in telling people how to violate the spirit of the GNU
licenses without violating the letter.  This section tells you how to
comply with the intention of the GNU licenses as best I understand them.

   The FSF has no objection to your making money.  Its only interest is
that source code to their programs, and libraries, and to modified
versions of their programs and libraries, is always available.

   The short answer is that you do not need to release the source to
your program, but you can't just ship a stripped executable either,
unless you use only the subset of libg++ that includes the iostreams
classes (see discussion below) or the new libstdc++ library (available
in libg++ 2.6.2 and later).

   Compiling your code with a GNU compiler does not affect its
copyright; it is still yours.  However, in order to ship code that
links in a GNU library such as libg++ there are certain rules you must
follow.  The rules are described in the file COPYING.LIB that
accompanies gcc distributions; it is also included in the libg++
distribution.  See that file for the exact rules.  The agreement is
called the Library GNU Public License or LGPL.  It is much "looser"
than the GNU Public License, or GPL, that covers must GNU programs.

   Here's the deal: let's say that you use some version of libg++,
completely unchanged, in your software, and you want to ship only a
binary form of your code.  You can do this, but there are several
special requirements.  If you want to use libg++ but ship only object
code for your code, you have to ship source for libg++ (or ensure
somehow that your customer already has the source for the exact version
you are using), and ship your application in linkable form.  You cannot
forbid your customer from reverse-engineering or extending your program
by exploiting its linkable form.

   Furthermore, if you modify libg++ itself, you must provide source
for your modifications (making a derived class does not count as
modifying the library - that is "a work that uses the library").

   For certain portions of libg++ that implement required parts of the
C++ language (such as iostreams and other standard classes), the FSF has
loosened the copyright requirement still more by adding the "special
exception" clause, which reads as follows:

     As a special exception, if you link this library with files
     compiled with GCC to produce an executable, this does not cause
     the resulting executable to be covered by the GNU General Public
     License.  This exception does not however invalidate any other
     reasons why the executable file might be covered by the GNU
     General Public License.

   If your only use of libg++ uses code with this exception, you may
ship stripped executables or license your executables under different
conditions without fear of violating an FSF copyright.  It is the intent
of FSF and Cygnus that, as the other classes required by the ANSI/ISO
draft standard are developed, these will also be placed under this
"special exception" license.  The code in the new libstdc++ library,
intended to implement standard classes as defined by ANSI/ISO, is also
licensed this way.

   To avoid coming under the influence of the LGPL, you can link with
`-liostream' rather than `-lg++' (for version 2.6.x and earlier), or
`-lstdc++' now that it is available.  In version 2.7.0 all the standard
classes are in `-lstdc++'; you can do the link step with `c++' instead
of `g++' to search only the `-lstdc++' library and avoid the LGPL'ed
code in `-lg++'.

-- 
-- Joe Buck 	<jbuck@synopsys.com>	(not speaking for Synopsys, Inc)
Anagrams for "information superhighway":	Enormous hairy pig with fan
						A rough whimper of insanity

From csus.edu!uop!pacbell.com!well!nntp-ucb.barrnet.net!agate!howland.reston.ans.net!news.moneng.mei.com!bloom-beacon.mit.edu!senator-bedfellow.mit.edu!faqserv Tue Sep 19 16:09:09 1995
From: nikki@trmphrst.demon.co.uk (Nikki Locke)
Newsgroups: comp.lang.c++,comp.answers,news.answers
Subject: Available C++ libraries FAQ
Supersedes: <C++-faq/libraries_807739938@rtfm.mit.edu>
Followup-To: poster
Date: 6 Sep 1995 13:16:31 GMT
Organization: Trumphurst Ltd.
Lines: 3313
Approved: news-answers-request@MIT.Edu
Expires: 20 Oct 1995 13:13:38 GMT
Message-ID: <C++-faq/libraries_810393218@rtfm.mit.edu>
Reply-To: cpplibs@trmphrst.demon.co.uk
NNTP-Posting-Host: bloom-picayune.mit.edu
Summary: Contains a list of available C++ libraries, both PD and commercial.
X-Last-Updated: 1995/08/23
X-Mailer: cppnews $Revision: 1.43 $
Originator: faqserv@bloom-picayune.MIT.EDU
Xref: csus.edu comp.lang.c++:139242 comp.answers:14076 news.answers:52286
Status: O

Archive-name: C++-faq/libraries
Comp-lang-c++-archive-name: C++-faq/libraries

---------------------------------------------------------
CHANGES SINCE LAST SUBMISSION (July 11 1995)

ASSET entry updated
CommonPoint Application System added
Interviews European site added
C++ Data Object Library added
Liant C+++ Views entry updated
ObjectBuilder added
GALib added
XRLCAD added
ValArray added
Splash entry updated
USL C++ Components entry updated

---------------------------------------------------------

Here is the latest draft of a list of available C++ libraries I am 
compiling. I intend to post this once a month or so (unless there are any
complaints). Sorry about the long gap since the last posting.

It is also submited to news.answers, and is available for public ftp
(along with all the other Usenet FAQ lists) at rtfm.mit.edu (18.70.0.209), 
in pub/usenet-by-group/comp.lang.c++/C++_FAQ/libraries.

Rtfm.mit.edu also has a mail server - send a mail message containing 
"usenet-by-group/comp.answers/C++-faq/libraries" to mail-server@rtfm.mit.edu.
If you want to find out more about the mail server, send a message to it
containing "help". 

Marshall Cline's C++ FAQ is also available from rtfm - the files are
called _posting_#1_4, _posting_#2_4, _posting_#3_4 and _posting_#4_4, and
they are in the same directory. 

I have not included a credits list, because it would be nearly as large as
the rest of the file! Many thanks to all those who contributed, and I 
hope you won't be offended that I haven't mentioned you. 

Entries are in the order I received them, i.e. totally random. Some future
version might have the entries in alphabetical order, but don't hold your 
breath :-)

If your library isn't mentioned, or you wish to update your entry in this 
list, feel free to mail me the new entry.  Please note that entries will 
be restricted to a couple of paragraphs - if you send me a 100k text file 
giving minute details, I will have to summarise it. It is much easier for 
me if you just send me an entry which is the right size to start with.

Suggested points to include in your entry are ...

Name of package.
Brief summary of purpose.
Short list of features.
Supported compilers, operating systems etc.
Licence restrictions. Vendors may care to give an idea of prices.
E-mail addresses for more details.
Ftp site(s).
Postal address/telephone/FAX numbers.

Please mail comments, criticisms, additions and amendments to me at
cpplibs@trmphrst.demon.co.uk. However, please DO NOT mail me with requests
for assistance in finding files mentioned in the list. I am unable to 
provide such a service. Definite information such as "file xyz is no 
longer at site xxx" IS welcome - even better if you can tell me an 
alternative site where it can be found. If you are new to the Internet, 
try to find out about tools such as archie, whois, www, gopher etc. I 
recommend the newsgroups "news.announce.newusers" and "news.answers" 
for starters.

*** *** *** *** *** NOTE TO VENDORS *** *** *** *** ***
This FAQ contains details of both free and commercial libraries. Vendors
who have sent me details of their libraries for inclusion in the FAQ have
been pleasantly surprised by the level of interest generated. Please
remember, I only allow 2 or 3 paragraphs describing the product, and no
advertising hype ! 

Libraries available via ftp
~~~~~~~~~~~~~~~~~~~~~~~~~~~

---------------------------------------------------------
valarray<Troy> (versions 1.0, 1.1, 2.0)
[ Author is David Vandevoorde ]

Attempts at providing the functionality described in Chapter 26 of
the draft C++ standard. None of the releases stick perfectly to the
specifications of the proposed standard. Version 2.0 is a very
deliberate step away from the draft as released in April 1995 for
public comments in the USA: it is used as a proof of concept to
support a revision of the original specs.

Some characteristics:
	. heavy usage of templates and their automatic instantiation;
	. avoidance of temporary arrays in array expressions;
	. production of fast compact loops, but some overhead
	  before entering those loops.
Release 2.0 has been lightly tested with the following compilers:
	. various EDG based compilers 
	    (Apogee CC 3.0 on Sun, NCC on SGI and a few experimental
	     compilers on other platforms)
	. Borland C++ 4.5
	. Sun CC 4.x
	. Sun CC 3.x (cfront-based)
	. CRI C++ on Cray (cfront based)
	. IBM xlC
It will probably not work with g++ 2.7.0 or earlier.

Free usage, copy and distribution if not commercial.

Downloadable from: ftp://ftp.cs.rpi.edu/pub/vandevod/Valarray
Contact: David Vandevoorde (vandevod@cs.rpi.edu)
	Department of Computer Science
	Rensselaer Polytechnic Institute
	Troy, NY12180
	USA
---------------------------------------------------------
XRLCAD -- CXrL CAD toolset

This package contains a C++ class library to manipulate Structure (as in
Calma/CIF) hierarchies. There is also loaders for CIF and Calma, as well
as output drivers for these formats. A bunch of demo programs are included
which I wrote when I was testing the library, and these programs turned
out be quite useful tools.

The library is still in its infancy, but it's reasonably solid; in a 
few months I'll take another look at it and probably overhaul it. 

I've successfully built a recent snapshot on the following platforms:

    sparc-sunos-4.1.3: SC2.0.1, Cfront-3.0.1, GCC-2.6.3
    sparc-sunos-5: SC2.0.1, GCC-2.6.3
    rs6000-aix-3.2: Cfront-3.0.1, GCC-2.6.3
    decstation-ultrix4.2: Cfront-3.0.1, GCC-2.6.3 (and I think it worked!)
    hppa1.1-hpux9.05: gcc-2.6.3

This code is copyrighted (read: NOT in the public domain), so please 
respect the copyrights when modifying/redistributing this code. If you 
make modifications/bug-fixes, please let me know so I can incorporate
it into the main release.

WARRANTY: None whatsoever. Use at your own risk.
AUTHOR: Mumit Khan <khan@xraylith.wisc.edu>
FTP SITE: http://www.xraylith.wisc.edu/~khan/software/xrlcad/xrlcad.html

Mumit Khan				khan@xraylith.wisc.edu
Research Staff				Phone: +1 608 265 6075
Center for X-ray Lithography		FAX:   +1 608 265 3811
University of Wisconsin-Madison		http://www.xraylith.wisc.edu/~khan/
---------------------------------------------------------
Matthew's GAlib: A C++ Genetic Algorithm Library
Copyright 1994-5 Massachusetts Institute of Technology
mbwall@mit.edu 7jul95

GAlib is a C++ library that contains a set of genetic algorithm objects.
With GAlib you can add genetic algorithm optimization techniques to your
program using any data representation and many different genetic
algorithm operators. The library includes genomes based upon binary
string, array, tree, and list data structures, and you can create your
own genomes by simply deriving a new class from the base genome and any
data structure that you may be using already. Many scaling, selection,
termination, initialization, mutation, and crossover methods are included
in the library, and you can override any of the defaults with operators
of your own design. 

Free for non-profit use.

GAlib has been used on the following systems:

        SGI IRIX 4.0.x          Cfront
        SGI IRIX 5.x            DCC 1.0, g++ 2.6.8, 2.7.0
        IBM RSAIX 3.2           g++ 2.6.8, 2.7.0
        DEC MIPS ultrix 4.2     g++ 2.6.8, 2.7.0
        SUN SOLARIS 5.3         g++ 2.6.8, 2.7.0
        HP-UX                   g++
        MacOS                   MetroWerks CodeWarrior 5
        MacOS                   Symantec THINK C++ 7.0
        DOS/Windows             Borland Turbo C++ 3.0

    ftp://lancet.mit.edu/pub/ga/
    http://lancet.mit.edu/ga/
---------------------------------------------------------
SIMEX - Provides classes that help a user develop discrete-event simulation
models, with an emphasis on epidemiology and biology.

Classes for random number generation, event and process management, user
interface (commandline arguments, TTY, or Tcl/TK), aggregate statistics,
basic data structures (list, strings, weighted ordered sets).  Many
examples.

Known to work with g++ 2.6.x  SunOS.
Some problems with HP.

Freely available via ftp. Copyrighted.

email: michael@simvax.labmed.umn.edu
       jan@simvax.labmed.umn.edu

ftp://ftp.nmsr.labmed.umn.edu
http://www.nmsr.labmed.umn.edu

Box 511 UMHC
Div of Health Computer Sciences
U Minn
MPLS, MN 55455
phone: (612) 625-3241 (Jan Marie Lundgren)
fax:   (612) 625-7166
---------------------------------------------------------
FFTPACK++
VERSION: 1.0

FFT_Pack is a C++ wrapper for FFTPACK complex routines using LAPACK++
Matrix and Vector classes. FFTPACK routines were converted to C using
f2c and also modified to use double precision complex using -r8 to f2c.

Most of this code was lifted directly from GNU OCTAVE v1.1.0, hence the
copyright notice at the top.

the forward FFT takes you to freq domain (ala direction == -1), and
backward the other way.

Passing LaVectorComplex/Double or LaGenMatComplex/Double with one
dimension set to 1 will implicitly perform 1D FFT on the data.

The members of the FFT_Pack class are declared static, since they really
need no private member storage. There are two types of transform routines:
ones that return a new complex matrix and the ones that change the matrix
in place.
For example:
    
    LaGenMatComplex cmat;
    // ...
    // initialize cmat.
    // ...

    // the following computes the forward FFT of Matrix cmat and returns
    // a new matrix which then initializes a new matrix cmat2. 
    LaGenMatComplex cmat2 = FFT_Pack::forward(cmat);

    // The following simply overwrites itself by reinitializing with the
    // anonymous matrix returned by FFT_Pack::forward.
    cmat = FFT_Pack::forward(cmat);

    // in-place example. In case of large matrices, it is best to try to
    // optimize memory usage using IP (in-place) routines. Note that you
    // can only use Complex matrices in this case.
    FFT_Pack::forward_IP(cmat);

Prerequites/Installation:

    compiler: you'd need a C++ compiler (I've used both cfront 3.0.1 
    and gcc-2.6.3) on a variety of platforms.

    LaMatrix++: You'd need LaMatrix++ class library from LAPACK++. Check
    out ftp://netlib.att.com/netlib/c++ if you don't have it. 

    FFTPACK: you can use the f2c'd fftpack routines I've provided with
    the package, or you can use the original FORTRAN version from netlib.

    F2C: If your system does not have F77 compiler environment installed,
    then you would need libf2c.a (ie., libF77.a + libI77.a), also available 
    from netlib. 

LICENSE AND COPYRIGHT:

FFTPACK++ is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.

FFTPACK++ is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the file COPYING for more
details.

SITE: http://www.xraylith.wisc.edu/~khan/software/fftpack/
AUTHOR: Mumit Khan <khan@xraylith.wisc.edu>
    Center for X-ray Lithography
    University of Wisconsin - Madison
    Voice: 608 265 6075
    FAX: 608 265 3811
---------------------------------------------------------
Types 1.0

Types is a Shareware library used to support the creation of reusable
software components in C++.

Full source code and documentation and examples are included.

Types provides:Garbage Collector,recursive data estructures,encode and decode
of polymorfic objects,encode and decoding to and from files or memory using 
external or local data representation, exceptions,...

Types also include some classes implemented using types a double linked 
list, stack, btree, storage class, string and others.

You can use and XDR representation for encode and decode objects this feature
enable your data to be ported to other plataforms.

This version is for Borland C++ 4.0  but it can be ported to
other C++ compilers that fully implement templates and exceptions.

	E-mail: malpica@mailer.main.conacyt.mx

	ftp://oak.oakland.edu/SimTel/msdos/cpluspls/typesc10.zip
---------------------------------------------------------
Diffpack is a large and comprehensive C++ package aiming at quick
prototyping of simulators solving partial differential equations by FEM.
Under development at SINTEF Applied Mathematics and the University of
Oslo, Norway. 

Version 1.0 of Diffpack is released for free non-commerical use and is
distributed by netlib. For further details refer to the Diffpack WWW
home page 

	http://www.oslo.sintef.no/avd/33/3340/diffpack

---------------------------------------------------------
YACL - Yet Another Class Library

YACL includes data type classes (String, Date, TimeOfDay), container classes
(Sequence, Set, Map, Tree, BTree), data storage and retrieval classes,
and GUI classes based on the Model-View-Controller  paradigm. The data type,
container and storage classes do not rely on any particular platform, and have
been tested under DOS/Windows, OS/2 and several flavors of Unix. The GUI
classes are available under Microsoft Windows and X windows with the Motif
toolkit.

	ftp from ftp.cs.scarolina.edu (129.252.131.11)
	in directory /pub/sridhar

Contact:
	M. A. Sridhar
	Department of Computer Science
	University of South Carolina
	Columbia, SC 29208
	USA
	e-mail: sridhar@usceast.cs.scarolina.edu
	Phone: (803) 777-2427
	Fax: (803) 777-3767
---------------------------------------------------------
CBMT - Collaborative BioMolecular Tools

	CBMT provides a number of easy-to-use fundamental classes for
biologists, chemists and crystallographers.  They include:  Molecular
Structure, Sequence, Standard Formats (PDB, CIF, GCG, etc), Geometry,
Statistics, TextParsing, and a single container class (a dynamic 
Array).  All documentation is in HTML, and member functions have *.c
examples.  I hope that the system can be extended as a communal effort and
am piloting this idea in the C++ course at the Globewide Network Academy
(http://info.desy.de/gna/html/cc/index.html)
	Version 1.3 will be posted shortly including an experimental
script language (generated automatically from the *.h files) providing
support for persistent objects manipulatable by other languages such as
tcl or csh. 

Free, but not resellable.

	email: Peter Murray-Rust (pmr1716@ggr.co.uk or mbglx@seqnet.dl.ac.uk)

	Extensive WWW documentation: http://www.dl.ac.uk/CBMT/HOME.html

	ftp from s-ind2.dl.ac.uk
	in /cbmt/democ12.tar.Z
---------------------------------------------------------
ISC366.ZIP -- Interrupt Service Class (v. 3.66)

Allows hooking of interrupts (software and hardware) into classes, comes
with classes for staying resident, for serial communication (interrupt
driven), and like-wise classes. Comes with full source code! Is DOS
specific (current version works only under BC++ 3.0 and higher). 

This class in PD, current version for registered users is version 4.

	ftp from oak.oakland.edu
	in /pub/msdos/cplusplus
	or /pub/msdos/cluspls ?
---------------------------------------------------------
Objtran and Objdce

Objtran is a set of C++ class libraries that provide a higher-level
abstraction for programmers developing applications using OSF's DCE
and Transarc's Encina. Objtran actually consists of two separate
libraries -- Objdce and Objtran.

Objdce makes it easier to write DCE applications by abstracting some
of the more complex aspects of DCE. A class is included that can
manage an RPC server, interacting with the DCE Name Service and
Security Service as desired. Another class manages a client's binding
to a server and encapsulates Name Service lookups.  Other classes
allow the programmer to use threads and various forms of
mutual-exclusion locks, report errors consistently, utilize Access
Control Lists, handle timestamps from the DCE Time Service, and
perform UUID manipulation.

Objtran is built on top of Objdce, and adds support for the Encina
distributed transaction service. It is intended to be used with C++
programs instead of the "Transactional C" macro package. It fully
encapsulates the Encina TRAN and TRPC facilities with a few
easy-to-use classes. It also provides an efficient recovery service
for proper control of distributed transactions, and has support for
the TM/XA service, allowing interoperability with XA-compliant
databases. Support for the Encina Monitor is being implemented so
programs may, with very few code changes, use either the smaller and
more efficient bare Objtran environment or the more sophisticated
Monitor.

This software is Copyright 1993-1994 by Citibank, N.A. Permission is
granted to use, copy, modify and distribute the software and its
documentation without fee. The software is distributed with no
warranty of any kind.

	mail: objtran-comment@fig.citib.com

	ftp from wilma.cs.brown.edu
	in /pub/Objtran.tar.Z
---------------------------------------------------------
RTTI library

Till RTTI becomes a part of regular compilers (BC 4.0 is the sole implementor
I think) these RTTI libraries provide an excellent tool for the same purpose. 

The library is claimed to be portable. No licence restrictions.

	Arindam Banerji

	(219)-631-5273 (Voice)
	(219)-631-9260 (FAX)

	mail: axb@defender.dcrl.nd.edu
	      axb@cse.nd.edu

	ftp from invaders.dcrl.nd.edu
	in /pub/software/rtti.tar.Z
---------------------------------------------------------
Aisearch - a package to make writing problem solving programs easier.

Offers the programmer a set of search algorithms that may be used to
solve all kind of different problems. The following search algorithms
have been implemented: 

    - depth-first tree and graph search.
    - breadth-first tree and graph search.
    - uniform-cost tree and graph search.
    - best-first search.
    - bidirectional depth-first tree and graph search.
    - bidirectional breadth-first tree and graph search.
    - AND/OR depth tree search.
    - AND/OR breadth tree search.

Although this package is meant as a tool for developing problem solving 
software it is not meant exclusively for programmers that are familiar with
the concept of problem representation and search techniques. The document
accompanying this package first describes (though condensed) the theory of
problem solving in AI and next explains how the search class library must be
used. Furthermore, as the source code is richly commented and as also some
demo programs are included the package should also prove useful to people that
want to get acquainted with the subject.

	ftp from obelix.icce.rug.nl
	in /pub/peter/aisearch.zip
	or /pub/peter/aisearch.tar.Z
---------------------------------------------------------
DOSTmUit - DOS Text Mode User Interface Toolkit

Enables C++ programmers to add a CUA-compliant user interface to their
DOS programs without getting involved in screen coordinates and other
messy details. The programmer merely states which interface objects are
required, and how they are to be placed on the screen in relation to each
other. Those familiar with the ET++ toolkit for the X windows system
under Unix will get the general idea. 

Includes a class documentation facility (DocClass) which will generate a
large text file from the source code giving details of every class,
structure, enum and extern in the toolkit. This program will also work on
your own C++ source code. Source is provided. 

Supported compilers are Zortech C++ 3.0r4, Borland C++ 3.1.

The toolkit is free for non-commercial use. Commercial licences may be 
obtained from the author.

	mail: uit@trmphrst.demon.co.uk

	ftp from ftp.demon.co.uk[158.152.1.65]
	in pub/trumphurst/dosuit??.zip
	Also uitbor??.zip for Borland C++ users
---------------------------------------------------------
Lapack++

Description : C++ version of some of lapack fortran code.
Author      : J. Dongarra, R. Pozo, D. Walker
Version     : 0.9 beta
Comments    : Developmental version of proposed C++ version of lapack.
              Contains blas.h++ etc, but needs Fortran library to link.
Documents   : Overview paper (9 pages postscript), release notes (7 page ps)

	ftp from netlib2.cs.utk.edu
	in lapack++/*
---------------------------------------------------------
MatClass

Description : a C++ class for numerical computation
Author      : Chris Birchenhall (chris.birchenhall@mailhost.mcc.ac.uk}
Comments    : Very complete.
              *  Offers a general purpose dense, real matrix class
              *  Has a family of decomposition classes based on
                 LU, Cholesky, Householder QR and SVD
              *  Has a family of OLS regression classes based on
                 above decompositons
              *  A family of special function classes
              *  Random number class
              *  Has a simplified I/O structure
Documents   : Very thorough tex manual, with discussion of design philosophy.
              Currently the manual does not cover all the features of the I/O.

	ftp from ftp.mcc.ac.uk
	pub/matclass/pc and pub/matclass/unix
---------------------------------------------------------
Blas.cpp.shar.z

Author      : Damian McGuckin (damianm@eram.esi.com.au)
Description : a BLAS in C++

	ftp from usc.edu
	in pub/C-numanal
---------------------------------------------------------
Texas Persistant Store

Paul R. Wilson and Sheetal V. Kakkad
Object-Oriented Programming Systems research group (oops@cs.utexas.edu)
Computer Sciences Dept., University of Texas at Austin

Texas is a free persistent store that can be used with standard C++ compilers,
and works efficiently with very little modification to most C++ programs.
It runs on several varieties of UNIX and should be very easy to port to most
modern operating systems, such as OS/2, Windows NT, Mach, Windows 4.0, etc.
(If things we hear are correct, Linux will provide the necessary virtual
memory features soon, too, and Texas will be ported about fifteen minutes 
later. :-)

Texas uses "pointer swizzling at page fault time", an address translation
techique that converts pointers from an abstract format to actual virtual
memory addresses when pages are first touched and brought into memory.
(A similar technique, invented independently, is used in the market-leading
persistent store/OODB, ObjectStore from Object Design Inc.)  This allows
Texas to be highly portable, avoiding any assumptions about where a page
of data will be an a process' virtual memory address space; it can also
support very large addresses spaces efficiently on stock 32-bit hardware.
(It could also be used to efficiently provide shared address spaces across
networked heterogenous machines with different hardware address sizes, e.g.,
across 32- and 64-bit machines.)

mailing list : oops@cs.utexas.edu

	ftp from cs.utexas.edu
	in pub/garbage/texas
	More info in pub/garbage/swizz.ps
	and pub/garbage/texaspstore.ps
---------------------------------------------------------
wxWindows is a C++ class library for building Motif, Open Look,
Windows 3.1 and NT applications from the same source code. One simple
API is provided for all platforms. wxWindows supports objects such as
frames, subwindows, buttons, list boxes, icons, and bitmaps, and
supports drawing into canvases, PostScript files, Windows printers,
metafiles and bitmaps using the same drawing primitives.

wxWindows provides a hypertext help facility, and a utility for
maintaining documentation in printed and three hypertext formats. It
also provides an interprocess communication API based on DDE, that
works under both Windows 3.1 and UNIX. Documentation is available in
PostScript, RTF, Windows Help, wxHelp and HTML formats.

	Julian Smart
	Artificial Intelligence Applications Institute
	University of Edinburgh
	80 South Bridge
	Edinburgh
	Scotland
	EH1 1HN
	EMAIL: J.Smart@ed.ac.uk
	TEL:   031 650 2746

	ftp from ftp.aiai.ed.ac.uk
	in directory pub/packages/wxwin
---------------------------------------------------------
CNCL

Universal classes:
	* Tree structured class hierarchy, similar to NIHCL.
	* Classes for general purposes such as arrays, linked lists,
	  strings.
	* Interface classes for UNIX system calls: pipes, select.
Simulation:
	* Event driven simulation.
	* Statistical evaluation.
	* Random number generators and distributions.
Fuzzy logic:
	* Fuzzy sets, fuzzy variables, fuzzy rules and inference
	  engine for building fuzzy controllers and expert systems.
EZD:
	* Interface classes for DEC's ezd graphics server.

This version of CNCL is known to compile and run on the following
systems:
	* SUN SPARCstation, SUNOS 4.1.3, GNU g++ 2.3.3/2.4.5,
	  libg++ 2.3/2.4
	* SUN 3/60, SUNOS 4.1.3, GNU g++ 2.3.3/2.4.5,
	  libg++ 2.3/2.4
	* LINUX 0.99.13, GNU g++ 2.4.5, libc 4.4.1, libc 4.4.4 +
	  libg++ 2.4

Distributed under the GNU Library General Public License.

	Communication Networks
	Aachen University of Technology
	D-52056 Aachen
	Germany
	Email: mj@dfv.rwth-aachen.de (Martin Junius)

	ftp from ftp.dfv.rwth-aachen.de  (137.226.4.111)
	in directory pub/CNCL
---------------------------------------------------------
RTTI implementation

	ftp from invaders.dcrl.nd.edu (129.74.18.54)
	in /pub/software/rtti.tar.Z

	Arindam Banerji 
	axb@cse.nd.edu 

	384 FitzPatrick Hall
	Dept. of Computer Science & Engg. 
	University of Notre Dame
	Notre Dame, IN 46556
	(219)-631-5273
	(219)-631-5772
---------------------------------------------------------
Lily (LIsp LibrarY) C++ class library which gives C++ programmers the
capability to write LISP-style code. 

I think Lily will be useful in academia for instructors who
want to teach artificial intelligence techniques with C++.  The
garbage collection mechanism employed by Lily is slow which will make it
unattractive for commercial use.

Documentation is minimal.  The "Lily User's Guide" (in file lily.txt) provides
a good overview of the architecture of Lily -- the document is unfinished.  
All of the example programs are from Winston's book "LISP Second Edition" so
you will be much better off if you have a copy.  Steele's "Common LISP" 
describes the behavior of the LISP functions.  

Lily uses the GNU Library General Public License.

Lily works well with GNU g++ version 2.4.5 (and probably earlier releases).

Lily works with Turbo C++ for Windows but not with Turbo C++ (though the
current version hasn't been tested with Turbo C++ for Windows).

Lily does *not* work with AT&T's cfront because cfront does not handle 
temporary objects very well.

	ftp from sunsite.unc.edu (152.2.22.81)
	in /pub/packages/development/libraries/lily-0.1.tar.gz 
---------------------------------------------------------
DiamondBase is a library of C++ routines and utilities that allow you 
to add Relational Database functionality to your C++ programs. It
is written entirely in C++, and great pains have been taken to
ensure it compiles under a variety of compilers including gcc,
cfront and Borland's C++ compiler for OS/2. It runs on a wide
variety of Unix platforms and OS/2. There are no plans to support
DOS or Windows at the moment. It comes with a 47 page manual.

Contact:
	darrenp@dibbler.cs.monash.edu.au
	kevinl@bruce.cs.monash.edu.au
	davison@molly.cs.monash.edu.au

	ftp from pippin.cs.monash.edu.au
	in pub/export/?
---------------------------------------------------------
GINA++ - An O-O application framework for C++, X11R5, and OSF/Motif

Requires:  AT&T 3.0 based C++ compiler (Sun C++ 2.0.1), X11R5, Motif 1.2
Platforms supported:    Sun Sparc, HP

GINA++ (The Generic INteractive Application for C++) is an object-
oriented application framework that facilitates the development of
applications with a graphical user interface. It is written in C++ and
uses OSF/Motif and X for the user interface parts. GINA++ comes as a
library of C++ classes, 10 small to medium demo applications, and it is
fully documented. 

Components of GINA++ are: (1) A C++ encapsulation of OSF/Motif providing
easy-to-use mechanisms for deriving new widget classes completely in C++,
(2) Support for object-oriented graphics (rectangles, arrows, circle,
etc), (3) An unlimited undo/redo history mechanism, (4) supporting
classes for data structures (list, arrays, etc), run-time type
information, and a notification mechanism. 

The classes of GINA++ constitute an executable program - the generic
application - which possesses the basic functionality and the user
interface components common to all interactive graphical applications,
but lacks any application-specific behavior. The predefined functionality
and behavior is inherited by deriving subclasses from the existing GINA++
classes. Application specific behavior is implemented by adding new
classes and member functions. Differences to the standard application are
coded by refining virtual member functions inherited from GINA++. 

Author: Andreas Baecker (baecker@gmd.de), 
	GMD, 
	P.O. Box 1316, 
	D-53731 Sankt Augustin

	ftp from ftp.gmd.de:
	in /gmd/ginaplus
	or ftp.x.org:
	in /contrib
---------------------------------------------------------
Motif++ - Ronald van Loon.
A wrapper-library, that encapsulates Motif widgets in C++ classes. All
resources of these Widgets can now be set through member-functions, while
objects can be used in callback-functions. 

The July 93 release offers:
- Easy configuration (even for non-imake-gurus)
- Full support for X11R4 as well as X11R5
- Full support for Motif 1.1 and Motif 1.2 (including Drag and Drop)
- Support for Xbae widgetset 
- Support for the xpm library
- Percentage widgets
- Generic Widget
- Support for WCL Table Widget
- A library for easy manipulation of Visuals 
- A library that reads PBMPLUS files, as well as providing an extension to 3D
  of the format.
- Lots of demos and testfiles (even somewhat useful programs)
- An article I wrote on the usage of Motif, X and C++, previously posted
  on Usenet.
- all filenames smaller than 14 characters

Requires:
	X11R4 or any later version
	Motif 1.1 or any later version
	C++ compiler, compatible with cfront 2.0 or later
	imake
	a bourne shell (sh, bash, ksh ...) that supports shellfunctions.
	sed

	mail "rvloon@motif.hacktic.nl".
	Tel: +31 33 758 293 (if desparate !)

	mailing list : motif++@motif.hacktic.nl
	subscriptions : motif++-request@motif.hacktic.nl

	ftp from decuac.dec.com: 
	in /pub/X11/motif++.28.jul.93.tar.gz
	or from nrcnet0.nrc.ca (132.246.160.2): 
	in /pub/motif++/motif++.28.jul.93.tar.gz
	or from ftp.wg.omron.co.jp: 
	in /pub/X11/misc/MOTIF.AND.WIDGETS/Motif++.tar.Z 
	or from src.doc.ic.ac.uk:
	in /packages/motif++/motif++.28.jul.93.tar.gz
---------------------------------------------------------
OATH (Object-oriented Abstract Type Hierarchy) was designed
as an experiment in increasing object-oriented reuse.
It has a fairly high learning curve, but potentially 
higher gains if you are looking for a more flexible and
robust abstraction.  It is completely unsupported.

	ftp from csc.ti.com (192.94.94.1)
	in pub/oath.tar.Z
---------------------------------------------------------
NIHCL (National Institute of Health's C++ Library) is
essentially a mapping of part of Smalltalk's library
into C++.  It lies somewhere between OATH and COOL.
It is a little better supported and there is a textbook
by the author, Keith Gorlen, that is fairly good documentation.
However, the Smalltalk hierarchy is not completely 
consistent (IMO) with the C++ strong typing nature.
It is weakly supported.

	ftp from alw.nih.gov (198.231.128.251)
	in pub/nihcl.tar.Z
---------------------------------------------------------
libg++ (GNU's C++ library) is probably only relevant if
you are using g++; and if so, you already know about it.
It does have some good implementations of bignum's and
of regular expressions and strings.

	ftp from aeneas.mit.edu (18.71.0.38)
	in pub/gnu/libg++-*
---------------------------------------------------------
InterViews is an excellent GUI class library developed by Stanford
University. Make sure you get v3.1 or later. This library contains
excellent examples of multiple inheritance used profitably. I understand
that InterViews development will not continue past the current version;
author Mark Linton is concentrating his efforts on the X Consortium
Fresco project, which should show up in X11R6. 

	ftp from interviews.stanford.edu
        Also available from:
        ftp://ftp.informatik.uni-kiel.de/pub/graphics/X/InterViews
---------------------------------------------------------
Unidraw is a graphical editor building library based on top
of InterViews.

	ftp from interviews.stanford.edu
---------------------------------------------------------
ET++ is a large GUI library and other C++ tools developed
in Europe.

The Authors of the Library are Andre Weinand and Erich Gamma both with
Taligent now.

	ftp from ftp.inria.fr
	in gnu/et++-2.0.tar.Z
	or from ftp.ubilab.ubs.ch
---------------------------------------------------------
LEDA, A Library of Efficient Data Types and Algorithms, by Stefan N"aher
from Germany. It is available for educatioal purposes but its NOT in the
public domain. 

Provides basic data-types like lists, stacks, queues, trees, sets,
partitions, priority queues and a few others. These are parameterizable
classes, you may add your own datatype and have a priority queue ...
An important datatype is a graph, these are also parameterizable and there
are useful algorithms for them like shortest path, transitive closure,
matching, maximum flow, spanning tree and others, we have implemented a few
algorithms for dealing with perfect graphs, but these ar not part of the
standard library. The latest part deals with computational geometry.

It can be used with C++ compilers which understand templates, such as 
cfront 3.0 and g++ 2.4.5.

	Stefan Naeher
	Max-Planck-Institut fuer Informatik
	Im Stadtwald, 
	6600 Saarbruecken, 
	Germany
	(stefan@mpi-sb.mpg.de)

	ftp from ftp.mpi-sb.mpg.de
	in /pub/LEDA/LEDA-<version>.tar.Z
---------------------------------------------------------
Brent's univariate minimizer and zero finder.
by      Oleg Kiselyov <oleg@ponder.csci.unt.edu, oleg@unt.edu>
ref     G.Forsythe, M.Malcolm, C.Moler, Computer methods for
        mathematical computations.
prec    double
see     c++/serv_cc.shar

	ftp from netlib@research.att.com
	in c++/brent_cc.shar
---------------------------------------------------------
Radix-2 Fast Fourier Transform
by      Oleg Kiselyov <oleg@ponder.csci.unt.edu, oleg@unt.edu>
prec    single/double
see     c++/lin_alg.shar, c++/serv_cc.shar

	ftp from netlib@research.att.com
	in c++/fft.shar
---------------------------------------------------------
High level vector operations
        Contains the Aitken-Lagrange interpolation over the table of uniform or
        arbitrary mesh, and the Hook-Jeevse multidimensional minimizer.
by      Oleg Kiselyov <oleg@ponder.csci.unt.edu, oleg@unt.edu>
prec    single/double
see     c++/lin_alg.shar, c++/serv_cc.shar

	ftp from netlib@research.att.com
	in c++/hl_vector.shar
---------------------------------------------------------
basic linear algebra classes
by      Oleg Kiselyov <oleg@ponder.csci.unt.edu, oleg@unt.edu>
prec    single/double
see     c++/serv_cc.shar

	ftp from netlib@research.att.com
	in c++/lin_alg.shar
---------------------------------------------------------
A couple of functions that ought to be in the standard
C++ environment;
- Updated G++ class File that allows now for the file name to
  include pipes, say,
    File in_file("zcat aaa.Z |","r");
- Resource facility, or managing global "private" parameters
  that specify various program "options". It helps keep
  reasonable number of arguments in function calls.
by      Oleg Kiselyov <oleg@ponder.csci.unt.edu, oleg@unt.edu>

	ftp from netlib@research.att.com
	in c++/serv_cc.shar
---------------------------------------------------------
C++ implementation of differential algebra
by      Leo Michelotti <michelotti@adcalc.fnal.gov>
This is temporarily unavailable while we resolve the question of whether
inclusion of codes from Numerical Recipes makes distribution illegal. 

	ftp from netlib@research.att.com
	in c++/mxyzptlk.shar
---------------------------------------------------------
ParLib++, Parallel Programming Classes for C++:

	David Greco
	David.Greco@crs4.it
---------------------------------------------------------
P++, Parallel Programming Classes for C++:

	Dan Quinlan
	danq@lemond.colorado.edu
---------------------------------------------------------
"C* in C++", Parallel Programming Classes for C++:

	Terry Bossomaier
	terry@arp.anu.edu.au
---------------------------------------------------------
pC++ is a preprocessor for C++ that implements a data parallel
extension. Machines currently supported are CM5, paragon, KSR-1,
sequent, BBNTC2000 (and soon ibm sp1, and cray t3d), as well as in
uniprocessor mode on most workstations.

	gannon@cs.indiana.edu
---------------------------------------------------------
DoPVM - a class built on PVM, for message passing environments.

	Skip Hartley
	skip@mathcs.emory.edu
---------------------------------------------------------
The SPLASH c++ class library

(Small Perl-like List And String Handling class library)

SPLASH is a c++ class library that implements many of the Perl
constructs and data types, including extensive regex regular
expression pattern matching.

For those not familiar with Perl, it is an excellent scripting
language by Larry Wall and is available for most platforms.

This Class library provides List, String, Regular Expression, and text
manipulation handling capabilities based on those provided in Perl.

This is available as a compressed tar file for Unix, or .zip format
for MSDOS compatible names.

contact: morris@netcom.com

        ftp from ftp.netcom.com
        in pub/mo/morris/splashxxx.tar.Z
        and pub/mo/morris/splashxxx.zip

where xxx is the version number, currently 190 (for version 1.90)
---------------------------------------------------------
OSE is a collection of programming tools and class libraries for C++. The
core of the environment is the C++ class libraries, of which three are
provided. These are:

  OTCLIB - A library of generic components, including support for error
  handling, error message logging, error recovery, program debugging,
  memory management, resource management, generic collections, text
  manipulation, date/time, operating system interfacing and event driven 
  systems.

  OUXLIB - A library of components which primarily extends classes in the
  OTCLIB library to support features specific to the UNIX operating
  system.

  OTKLIB - A library of components which builds on the OTCLIB and OUXLIB
  libraries to allow integration of the TCL/TK library into applications
  using the event driven systems framework provided by the OTCLIB
  library.

The C++ libraries are portable to a wide range of C++ compilers on the
UNIX platform. Supported C++ compilers include those from ATT/USL (CFRONT),
CenterLine, DEC, HP, IBM, Lucid, ObjectStore, SGI (CFRONT), SGI (DELTA),
Sun (CFRONT) and Sun (NATIVE), as well as the freely available GNU C++
compiler. If your C++ compiler does not support templates, it is possible
to use a template preprocessor which is supplied with OSE. If your C++
compiler support exceptions, they will be used. Portability to all the
major variants of UNIX has been achieved. Supported platforms include AIX,
BSD, HPUX, IRIX, Linux, NeXT, OSF, SCO, Solaris, SunOS, SYSV and Ultrix. In
addition to being available under UNIX, the OTCLIB library has been ported
to DOS, OS/2 and Windows NT using Borland, Watcom and Microsoft C++
compilers.

The C++ libraries have been fully integrated with the ObjectStore OODBMS,
allowing instances of classes from the C++ libraries to be made persistent.
The C++ libraries can also be used in conjunction with applications using
Versant, although in this case instances of classes from the C++ libraries
cannot be made persistent.

In addition to the C++ libraries, a build environment is provided. The
build environment greatly simplifies the writing of makefiles, making the
the task of building applications, as well as the generation and
installation of both static and shared libraries easy. The details of
template instantiation for many of the C++ compilers is also hidden, making
it possible to write makefiles which are portable between different C++
compilers as well as different platforms. The build environment also
supports tasks such as schema generation for the ObjectStore and Versant
OODBMS, and testing of applications using tools such as Purify, Quantify,
PureCoverage, TestCenter and Sentinel.

Comprehensive documentation for the C++ libraries and build environment is
provided. Documentation for the C++ libraries comes in the form of a UNIX
style manual page for each class and higher level documentation giving
examples of how to use the classes. The UNIX style manual pages are
generated from the class header files using documentation extraction tools.
These tools are provided with OSE and are capable of generating both UNIX
style manual pages and Frame documents.

Development of OSE commenced in 1990, being made freely available via the
Internet in 1993. OSE was winner of CODA'94, the ComputerWorld Object
Developer Awards, held in conjunction with ObjectWorld in Sydney,
Australia. The category in which OSE was a winner was "Best implementation
of a reusable development environment for company deployment".

OSE (source code and documentation) can be obtained via anonymous ftp from:

  Europe:

    ftp.th-darmstadt.de [130.83.55.75]
    directory pub/programming/languages/C++/class-libraries/OSE

  United States

    ftp.odi.com [198.3.16.26]
    directory pub/OSE

  Australia:

    csis.dit.csiro.au [192.41.146.1]
    directory pub/SEG/ose

Documentation for OSE is also available online via WWW at:

  http://www.telstra.com.au/docs/ose/doc/ose-home.html

Questions about OSE can be directed to the author (Graham Dumpleton) at:

  ose@nms.otc.com.au

A mailing list for discussion of OSE, and a mail server providing a list of
known problems and fixes also exists.

OSE is made freely available by Dumpleton Software Consulting Pty Limited.
OSE contains licensed program materials which are the copyright of Telstra
Corporation Limited and which are licensed to Dumpleton Software Consulting
Pty Limited by Telstra Corporation Limited.
---------------------------------------------------------
COOL - Texas Instrument's "C++ Object Oriented Library".

COOL includes classes like AVL_Tree, Association, Bignum, Binary_Tree,
Bit_Set, Complex, Date_Time, Envelope, Gen_String, Handle, Hash_Table,
Iterator, List, M_Vector, Matrix, N_Tree, Pair, Quaternion, Queue, Random,
Range, Rational, Regexp, Set, Shared, Stack, String, Timer, Value, Vector.

COOL uses a special "template" syntax which is preprocessed by a special 
cpp (distributed with COOL). This enables it to be used with compilers 
which do not support templates.


	fto from csc.ti.com
	in ~ftp/pub/COOL.tar.Z
---------------------------------------------------------
GECOOL 2.1 is a reworking and enhancement of Texas Instrument's "C++
Object Oriented Library" (at csc.ti.com in ~ftp/pub/COOL.tar.Z) by some
programmers at General Electric. 

Also available is JCOOL. Its main difference from COOL and GECOOL is that
it uses real C++ templates instead of a similar syntax that is
preprocessed by a special 'cpp' distributed with COOL and GECOOL. 

	ftp from cs.utexas.edu
	in pub/COOL
---------------------------------------------------------
SOCKET++

C++ iostream like library for sockets and pipes.

	ftp from from uvaarpa.virginia.edu:
	in /public_access/socket++-XX.tar.gz (XX - version no)
	or from cs.ucl.ac.uk [128.16.5.31]
	in coside/gnu/sockets++.tar.z
---------------------------------------------------------
PDBlib is a class library written in C++ for modeling a macromolecular
structure at the level of detail (excluding symmetry information) found
in a Protein Data Back (PDB) file. A class is supplied to read a PDB file
into a PDBlib representation. This class is independent of the actual
representation and other forms of input, for example from a relational
database like SESAM, are possible. 

The library is made extensible by a close coupling between intrinsic and
external classes. By writing only to the external classes you will remain
compliant with future versions of the library. 

You don't get source code. This is a temporary situation while we attempt
to centralize bug fixes and additions to the library. If you find this
situation unworkable source code is available by signing a copyright
agreement which is available with the distribution. 

Platforms:

PDBLib.1.0.SGI.tar.Z    Compressed tar file of PDB object classes library
                        and header files for SGI.  AT&T C++ release 2.1 & 3.0
                        compatible.

PDBLib.1.0.Sun.tar.Z    Compressed tar file of PDB object classes library
                        and header files for Sun Sparc station.  AT&T C++
                        release 2.1 & 3.0 compatible.

PDBLib.1.0.Cvx.tar.Z    Compressed tar file of PDB object classes library
                        and header files for Convex.  AT&T C++ release 2.1
                        compatible.

PDBLib.1.0.Alpha.tar.Z  Compressed tar file of PDB object classes library
                        and header files for Dec 3000 (Alpha AXP) with OSF1.
                        Dec C++ (cxx) release 1.2 compatible.

Address specific programming questions on PDBlib to Weider Chang, the
author of most of the code (weider@cuhhca.hhmi.columbia.edu). 

Address questions concerning PDBview to Ilya Shindyalov
(shindyal@cuhhca.hhmi.columbia.edu)

Address general comments, criticisms, questions about future directions
etc. to Phil Bourne (system@cuhhca.hhmi.columbia.edu). 

	ftp from cuhhca.hhmi.columbia.edu (128.59.98.1)
	in pub/programs/PDB/PDBlib
---------------------------------------------------------
molbio++ is a C++ library for molecular biosequence analysis.  Major 
features include:

classes and services for
  reading and writing sequence data in the following formats:
    Genbank Flatfile
    EMBL / SwissProt
    GCG / Wisconsin
    Fasta / Pearson
    PIR
    NCBI Retrieve Server (read-only)
  limited parsing of fields and features in biosequence files
  storing amino acid or nucleic acid sequences
  iterating over a biosequence
  calculating and storing counts or frequencies of amino acids
    or nucleotides
  device-independent graphics, via GCG's FIGURE program
  translating nucleotide sequences into proteins using
    the universal genetic code or modifications thereof.
  parsing BLAST output
  calculating pI and molecular weight of proteins
  amino acid hydropathy values of Kyte & Doolittle

	ftp from golgi.harvard.edu  (128.103.161.55)
	pub/CONTRIBUTIONS/molbio++
---------------------------------------------------------
SESAME, by C. Tietz, Neural net software ?

	ftp from ftp.gmd.de
	in /gmd/as/sesame.
---------------------------------------------------------
TOLKIEN (TOoLKIt for gENetics-based applications).

The tool contains objects for both GA and classifier system applications."
It's in some kind of alpha-status.

	tang028@cs.cuhk.hk
---------------------------------------------------------
GAME - Parallel Genetic Algorithms Theory and Applications

Edited by: J. Stender
Publisher: IOS Press
Frontiers in Artificial Intelligence and Applications series
1993, 225 pp; hard cover; w/ disk
ISBN: 90 5199 087 1
Price: $85, 59 pounds sterling

The first version of the GAME Virtual Machine software and two examples
that come with the book can be obtained also by ftp.

	ftp from bells.cs.ucl.ac.uk
	in papagena/game/version1 directory
---------------------------------------------------------
The Generic Linked List Package is a package to define, create, update
query and delete one or more (nodes of) linked lists, to sort linked
lists, and so on. The user doesn't have to take care of allocating a
number of bytes for a node, inserting on the right place, deleting and
freeing a node and so on.

	ftp from ftp.tno.nl or hermes.bouw.tno.nl
	in /pub/TNO/BOUW/Bouwinf/linkedlist0.10.shar
---------------------------------------------------------
Newmat : a very thorough matrix class

Author      : Robert Davies (robertd@kauri.vuw.ac.nz)

This library supports classes Matrix, UpperTriangularMatrix,
LowerTriangularMatrix, DiagonalMatrix, SymmetricMatrix, BandMatrix,
UpperBandMatrix, LowerBandMatrix, SymmetricBandMatrix, RowVector,
ColumnVector. Only one element type is supported. It includes the
operations *, +, -, concatenation, elementwise product, inverse,
transpose, conversion between types, submatrix, determinant, Cholesky
decomposition, QR triangularisation, singular value decomposition,
symmetric eigenvalue analysis, fast Fourier transform, sort, print, an
interface to "Numerical Recipes in C" programs, and an emulation of
exceptions.  It works with Borland, Watcom, Microsoft and Gnu C++
compilers.

	ftp oak.oakland.edu (or any Simtel mirror)
	in /SimTel/msdos/cpluspls/newmat08.zip
---------------------------------------------------------
nlmdl : a library for estimation of nonlinear models

Nonlinear maximisation, estimation, includes a real matrix class

Systems     : Unix, MS-DOS (Turbo C++)
Author      : A. Ronald Gallant, arg@ccvr1.cc.ncsu.edu

	ftp from ftp.uu.net
	in /usenet/comp.sources.misc/volume16/nlmdl
	or from ccvr1.cc.ncsu.edu (128.109.212.20)
	in pub/arg/nlmdl
---------------------------------------------------------
Octave : Matlab-like interactive system for numerical computations

Includes C++ classes for matrix manipulation, numerical integration, and
the solution of systems of nonlinear equations, ODEs and DAEs.
Distributed under the GPL. 

Systems     : Compiles and runs on SPARC, RS/6000, DEC/Ultrix,
              i386/Linux and probably most Unix-like systems that have
              a working g++/libg++.
Author      : John W. Eaton <jwe@che.utexas.edu>

	ftp from ftp.che.utexas.edu
	in /pub/octave/octave-M.N.tar.Z
---------------------------------------------------------
Andy Register <andy@cerl.gatech.edu> has a matrix library ...

It is still under development so there is no documentatin and some
functions have not been throughly tested. It is a departure from most
matrix libs in that it includes things like UpperTriangular different
>from Diagonal, from Row, from Col, etc. 

	ftp from ftp.cerl.gatech.edu
	in pub/c++/gtmatrix
---------------------------------------------------------
Awesime : a C++ task library explicitly designed for simulation.

Author      : Dirk Grunwald (grunwald@foobar.cs.colorado.edu)

	ftp from ftp.cs.colorado.edu
	in pub/cs/misc/Awesime
---------------------------------------------------------
BLAS in C++

Author      : Damian McGuckin (damianm@eram.esi.com.au)

	ftp from usc.edu
	in pub/C-numanal/blas.cpp.shar.z
---------------------------------------------------------
Cvmath.cc
An include file to make complex math look like regular math.

Author      : Leonard Kamlet, lik@engin.umich.edu
Comments    : The file uses a lot of operator overloading, so that
              if x=a+ib and y=c+id, the code for multiplying the two
              together looks like z = x*y;  Also, the file includes nrutil
              from Numerical Recipes, and adds the complex versions for
              vectors and matrices.

	ftp from usc.edu
	in pub/C-numanal/cvmath.cc
---------------------------------------------------------
Gnans : Simulation of stochastic and deterministic dynamical systems

System      : SunOS 4.1.x, IRIX, AIX; X11 Release 4-5 incl. Athena Widgets
Author      : Bengt Martensson <bengt@mathematik.uni-Bremen.de>
Comments    : A program (and language) for dynamical systems. Includes
              simple scripting language. Graphical user interface. Copyleft.

	ftp from ftp.mathematik.uni-Bremen.de
	in /pub/gnans
---------------------------------------------------------
Kalman : A class library for Kalman filtering

Author      : Skip Carter (skip@taygeta.oc.nps.navy.mil)
Description : A class library for Kalman filtering
Comments    : Contains lumatrix.c++ etc.
Language    : g++ 2.4.2 tested OK.

	ftp from usc.edu
	in pub/C-numanal/kalman.tar.gz
---------------------------------------------------------
Matrix

A C++ Matrix class, including a matrix implementation of the backward
error propagation (backprop) algorithm for training multi-layer, feed-
forward artificial neural networks 
Author      : E. Robert (Bob) Tisdale, edwin@cs.ucla.edu
Comments    : A C++ interface to existing C and FORTRAN matrix libraries.
Documents   : LaTeX manual.

	ftp from ftp.cs.ucla.edu
	in pub/Matrix.tar.Z
---------------------------------------------------------
Presto : C++ routines for fine-grained parallel programming (lightweight
threads) on multiprocessors. Tuned for the Sequent machines, but highly
adaptable and customizable. 

Systems : Unix-like OS on (moderate) multiprocessor machines 
Author : Brian N. Bershad, Edward D. Lazowska, Henry M. Levy 

	frp from cs.washington.edu
	in pub/presto1.0.tar.Z 
---------------------------------------------------------
Range : C++ class for range arithmetic. 

Associated with article in TOMS, Dec 1992 title "Precise computation
using range arithmetic, via C++" 
Author      : Oliver Aberth and Mark J. Schaefer

	ftp from math.tamu.edu
	in pub/range/range.tar.Z
---------------------------------------------------------
SA : library for simulated annealing

Author      : Skip Carter (skip@taygeta.oc.nps.navy.mil)

	ftp from usc.edu
	in pub/C-numanal/sa.zoo
---------------------------------------------------------
Sdeint

A Runge-Kutta like class for integrating systems of Stochastic
Differential Equations 

Author      : Skip Carter, skip@taygeta.oc.nps.navy.mil

	ftp from usc.edu
	in pub/C-numanal/sdeint.tar.z
---------------------------------------------------------
Simpack : tools for writing simulations with a EECS bias

Author      : Paul A. Fishwick, fishwick@cis.ufl.edu

	ftp from bikini.cis.ufl.edu
	in pub/simdigest/tools/simpack
	See also cis/tech-reports/tr92/tr92-022.ps.Z
---------------------------------------------------------
PARODY : C++ DATABASE LIBRARY

Al Stevens has written a book on the subject called
`Database programming in C++' or something. An article
on the subject was printed in Doctor Dobbs Journal
some time ago.

The nice thing is that Stevens also wrote a C++ library
adding persistence to C++, and the source is available.
The library is called PARODY and compiles under most
DOS-based C++ compilers. A slight rewrite of the GUI-
routines has to be done to make it compile under GNU C.

	ftp from ftp.mv.com
	in pub/ddj/1992.12/parody.zip 
	   pub/ddj/1992.12/parody.dir (directory of zip)
---------------------------------------------------------
SMURPH : A C++ library which could be useful for building a network
simulator.It comes withextensive documentation and examples.

	ftp from menaik.cs.ualberta.ca (129.128.4.241)
	in /pub/smurph*
---------------------------------------------------------
C++ FEM (Finite Element Method) Library 

In addition to FEM related classes, this library also has:

        1) Some simple garbage collection stuff
        2) An automatic differentiation library
        3) A sparse matrix library

This is an initial release and people should *expect* to have to do some
work to get it running on their system. If you have gcc-2.3.3, libg++-2.
3[.1], Gnu make and makedepend you shouldn't have too much difficulty
however. The code is unsupported, and is distributed under the terms of
the GNU Public License. 

	Michael Tiller
	University of Illinois (Urbana-Champaign)
	(tiller@solace.me.uiuc.edu)

	ftp from usc.edu
	int /pub/C-numanal/femlib-1.1.tar.gz
---------------------------------------------------------
Ode Object database v2.0

Ode is an object-oriented database based on the C++ database model.
The primary interface to Ode is the database programming language O++
which is based on C++.

Ode is now available to Universities. The current version of Ode runs on
Sun (Sparc) workstations and users must have C++ release 2.0 or a later
release. If you are interested in using Ode and giving us feedback on
your experience with Ode, please send mail to nhg@research.att.com with
the appropriate information. 

	Narain Gehani
	AT&T Bell Labs 3D-414
	600 Mountain Ave
	Murray Hill, NJ 07974

	ftp from research.att.com.
	in dist/ode2.0/2.0.oppbin.tar.Z
---------------------------------------------------------
C++SIM 1.0  - a simulation package written in C++. 

C++SIM provides discrete process based simulation similar to that
provided by the simulation class and libraries of SIMULA. The linked list
manipulation facilities provided by SIMSET are also included in the
package. 

The simulation package requires the use of a threads package and
currently only works with Sun's lightweight process library or the Gnu
thread package (which *is* included in the distribution). The package has
been used on Sun workstations, and, with the exception of the thread
library requirement, contains no system specific code which should make
porting to other systems relatively easy. The code has been compiled
with Cfront 2.1 and Cfront 3.0.1 and g++ 2.3.3

	ftp from arjuna.ncl.ac.uk
---------------------------------------------------------
ADAPTIVE Communication Environment (ACE) C++ IPC wrappers (C++Wrapper).

This release contains contains the source code, documentation, and
example test drivers for a number of C++ wrapper libraries and higher-
level distributed application frameworks developed as part of the
ADAPTIVE project at the University of Calfornia, Irvine. 

The C++ wrappers encapsulate many of the user-level BSD and System V
Release 4 IPC facilities such as sockets, TLI, select and poll, named
pipes and STREAM pipes, the mmap family of memory-mapped file commands,
System V IPC (i.e., shared memory, semaphores, message queues), and
explicit dynamic linking (e.g., dlopen/dlsym/dlclose) using type-secure,
object-oriented interfaces. 

The higher-level distributed application frameworks integrate and enhance
the lower-level C++ wrappers to support the configuration of concurrent
network daemons composed of monolithic and/or stackable services 

A relatively complete set of documentation and extensive examples are
included in the release. A mailing list is available for discussing bug
fixes, enhancements, and porting issues regarding ACE. Please send mail
to ace-users-request@ics.uci.edu if you'd like to become part of the
mailing list. 

	ftp from ics.uci.edu (128.195.1.1) 
	in gnu/C++_wrappers.tar.Z
---------------------------------------------------------
CB++ (CommonBase Database Access Library for C/C++)

This library was written in 1989 as a basis for storing C++ objects in
a relational database. The development of such a system was stopped in
1990 because of problems with the MS-DOS environment used in this time.
My involvement in various user interface projects here in the institute
and otherwhere made it sleep until last week.

Okay, here is it. It is only the database access layer of the projected
object storage system but it has some useful features which are provided
by commercial tools out there:

* Builds on the C language interface of a database, there is no need
  for a precompiler (like embedded SQL - which is totally unusable in
  combination with C++, at least it was three years ago...)
* Very simple to use. Unlike the native C interfaces of the databases
  it is as simple as embedded SQL or some 4th generation languages.
* Makes applications portable among different SQL databases. The library
  itself is relatively easy to port as the database vendor specific code


	ftp from ftp.x.org 
	in /contrib/CB++.0.1.*
---------------------------------------------------------
OBST - persistent object management system 

The persistent object management system OBST was developed by
Forschungszentrum Informatik (FZI) as a contribution to the STONE
project. 

Sites interested in getting information about new OBST developments
are welcome to register in their mailing list by sending a mail with
subject "obst-mailing-list" to stone@fzi.de.

	Forschungszentrum Informatik FZI
	STONE Projekt
	Haid-und-Neu-Strasse 10-14
	D-7500 Karlsruhe 1
	Germany
	Tel : ++49-721-9654-601
	Fax : ++49-721-9654-609
	Teletex : 721 190 fziKA
	email : stone@fzi.de

	ftp from gate.fzi.de [141.21.4.3]. 
	in /pub/OBST.
---------------------------------------------------------
GRAS - A Graph-Oriented Database System for SE Applications
Copyright (C) 1987-1992  Lehrstuhl Informatik III, RWTH Aachen
This library is free software under the terms of the GNU Library 
General Public License.

The system GRAS with interfaces for the programming languages Modula-2
and C is available as public domain software for Sun3/Sun4 workstations
(the GRAS system itself is implemented in Modula-2 and consists of many
layers which might be reusable for the implementation of other systems): 

  There are several files contain documentation, sources, binaries,
  and libraries. All binaries are for Sun/4 machines. Sun/3 binaries
  are shipped only if explicitly requested.

	Lehrstuhl f"ur Informatik III
	University of Technology Aachen (RWTH Aachen),
	Ahornstr. 55,
	D-5100 Aachen
	Contact : Dr. Andy Sch"urr (or Richard Breuer),
	andy@rwthi3.informatik.rwth-aachen.de
	ricki@rwthi3.informatik.rwth-aachen.de (for technical support)

	ftp from tupac-amaru.informatik.rwth-aachen.de (137.226.112.31) 
	in /pub/unix/GRAS522_3
---------------------------------------------------------
MTL110JE.ZIP -- multithreading class library

DOS PC/Borland C++ specific.

	ftp from oak.oakland.edu
	in /pub/msdos/cplusplus
	or garbo.uwasa.fi
	in /pc/c-lang
---------------------------------------------------------
CCL110JE.ZIP -- coroutine class library

DOS PC/Borland C++ specific.

	ftp from oak.oakland.edu
	in /pub/msdos/cplusplus
	or garbo.uwasa.fi
	in /pc/c-lang
---------------------------------------------------------
TSR100JE.ZIP -- TSR class library

DOS PC/Borland C++ specific.

	ftp from oak.oakland.edu
	in /pub/msdos/cplusplus
	or garbo.uwasa.fi
	in /pc/c-lang
---------------------------------------------------------
XMS200JE.ZIP -- XMS array class library

Wrapper classes to access XMS, UMBs and the HMA, as well as a templated
XMS array class. Test suites and timing programs provided for each class.
Source included. Free. DOS PC/Borland C++ specific. 

	ftp from oak.oakland.edu
	in /pub/msdos/cplusplus
	or garbo.uwasa.fi
	in /pc/c-lang
---------------------------------------------------------

Source code from books available for ftp
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
---------------------------------------------------------
Thinking in C++ by Bruce Eckel

eckelt03.zip contains the source code for Bruce Eckel's book "Thinking in
C++" (Prentice-Hall 1995, ISBN: 0-13-917709-4).  This is the complete set
of source code files from the book, including corrections after the book
was published.  The package only contains ASCII text files.  They were
prepared and tested with a number of compilers under DOS/Windows, and are
intended to represent the correct language implementation at the time of
their creation, rather than a particular compiler.  However, please be
aware that the C++ language is still a draft standard, and some language
elements are still subject to small changes.  The package is distributed
as copyrighted freeware (you can use the code, and redistribute the
package, but you cannot distribute modified versions of the package or
portions of the package).

Special requirements: Compressed from the original DOS directory
structure using PKZIP 2.04g.  When you unzip the package, use the -d
flag to create directories and maintain the directory structure.

Changes: Includes errata sheets for the first printing of the book
(corrected in the second printing).

eckelt03.zip has replaced eckelt01.zip (distributed on CIS & AOL).

Copyrighted FreeWare.  Uploaded by the author, Bruce Eckel <eckel@aol.com>.

ftp://oak.oakland.edu/SimTel/msdos/cpluspls/eckelt03.zip
or other Simtel mirrors.

---------------------------------------------------------
Code from Hansen's C++ Answers book
by      Tony L. Hansen
ref     "The C++ Answer Book", Addison-Wesley, 1990, ISBN 0-302-11497-6

	ftp://netlib.att.com/netlib/c++/answerbook
---------------------------------------------------------
Code from Coplien's, "Advanced C++ Programming Styles and Idioms"
by      James O. Coplien
ref     "Advanced C++ Programming Styles and Idioms", Addison-Wesley, 1992, ISBN

	ftp://netlib.att.com/netlib/c++/idioms
---------------------------------------------------------
Source to the Book: Object-Oriented Software in C++

by      Michael A. Smith  (mas@unix.brighton.ac.uk)
ref    "Object-Oriented Software in C++", Chapman & Hall,
        London. 1993. ISBN 0 412 55380 5.

	ftp from unix.brighton.ac.uk
	in /pub/mas
---------------------------------------------------------


Useful ftp sites
~~~~~~~~~~~~~~~~
If you don't have ftp access, send email to ftpmail@decwrl.dec.com
saying "help".  You will get instructions on how to do ftp via email.

European users might like to try ftpmail@grasp.insa-lyon.fr instead.
---------------------------------------------------------
ftp.th-darmstadt.de

A major repository of C++ stuff, mostly under the directory tree starting 
at /pub/programming/languages/C++. Includes a product list (from which
some of the information in this document was taken) in various formats in 
sub-directory c++-products.

	/pub/programming/languages/C++/...
---------------------------------------------------------
ftp.luth.se

	/pub/languages/c++/ClassLibs/...
---------------------------------------------------------
netlib@research.att.com.

send mail with the text "send index" or "send index from C++"
---------------------------------------------------------
Simtel

The primary Simtel site is oak.oakland.edu, but there are many mirror 
sites all over the world.

	msdos/cplusplus
---------------------------------------------------------
Current CUG Library Catalog

The CUG CD-ROM file listing offers the most comprehensive look at the
programming tools and utilities available from CUG. The complete
annotated listing (about 1 megabyte) is available through anonymous ftp
as follows: 

	ftp from cdrom.com
	in /pub/cdrom/cdroms/cug/capsule.txt
---------------------------------------------------------
source-code newsgroups:
        ftp.uu.net  (e.g. usenet/comp.sources.reviewed archives the
        comp.sources.reviewed newsgroup).
---------------------------------------------------------
Netlib:
        research.att.com     email, ftp
        ornl.gov             email, xnetlib
        nac.no               email, xnetlib for Europe
           (e.g. send email to netlib@ornl.gov to access by email)
        unix.hensa.ac.uk is a mail server useful for Europe.
        ci.cs.uow.edu.au (130.130.64.3) in Australia
---------------------------------------------------------

Libraries for which I don't know an ftp site
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
---------------------------------------------------------
DCE++: A C++ API for Programming Distributed Systems

William Leddy, Arjun Khanna (arjun@hal.com)
HaL Computer Systems, Austin, Texas.

DCE++ is a set of ANSI C++ classes that enable the rapid prototyping of
distributed programs. The goal of DCE++ is to provide a platform
independent C++ API to the significant components used in distributed
computing. Namely: RPC, threads, Security and Naming across the widely
used distributed computing platforms such as DCE, ONC and WNT. 

It is expected that by encapsulating platform dependencies inherent in
setting up rpcs, security etc. in DCE++ base classes, program development
time can be drastically reduced. Moreover, a foundation can be provided
for developing *portable* distributed program development tools. 

The second *evaluation* version of DCE++, version 0.4, has been released
on Dec 2'93. The release includes C++ bindings for remote procedure calls
over DCE and ONC. A C++ threads api for programming DCE threads. A C++
threads api for programming DCE distributed Time Service. The release is
available free of charge upon signing a very liberal license agreement. 

The license agreement is obtainable by anonymous ftp from hal.com. It is
in the directory dce++. The same directory also contains the release
notes for the 0.4 version and plans for 0.5 features. To obtain the code,
please send the signed license agreement to: 

Arjun Khanna, FAX (U.S country code) 512-794-8737
---------------------------------------------------------
GenTools: A Computational Genomic Tool Suite

The University of Texas System CHPC and collaborators are addressing the
problems of high performance platforms by developing GenTools, an
interactive, distributed, loosely integrated, set of tools for DNA and
protein sequence data analysis, phylogenetic analysis, and restriction
mapping which combines different algorithm implementations, machines, and
databases through a "bio-user" friendly set of graphical user interfaces.

	Sarah Barron
	GenTools Project Leader
	Computational Molecular Biology and Genetics Group
	University of Texas System Center for High Performance Computing
	Balcones Research Center, CMS 1.154
	10100 Burnet Road
	Austin, TX 78758-4497

	Internet:  sarah@chpc.utexas.edu
	Bitnet:    s.barron@uthermes
	Voice:     (512)471-2434
	FAX:       (512)471-2445
---------------------------------------------------------

Commercial libraries
~~~~~~~~~~~~~~~~~~~~

---------------------------------------------------------
ObjectBuilder includes the Object Interface (OI) class library which is a
C++ object-oriented implementation of both Motif and Openlook interfaces.
Note that interested parties can read more about the OI library in the
1300 page "OI Programmer's Guide" by Gary Aitken and Amber Bensen
published by Prentice-Hall. 

ObjectBuilder is a GUI that offers developers a complete C++
implementation of Motif. ObjectBuilder allows developers to rapidly
design, test, modify and implement sophisticated object-oriented
graphical user interfaces by using ObjectBuilder to manipulate C++
objects found in its Object Interface (OI) C++ class library. 

ObjectBuilder features a drag-and-drop user interface that allows
developers to immediately visualize the results of their user interface
design. 

ObjectBuilder is owned and supported by Openware Technologies, Inc..
Formerly owned by ParcPlace Systems, Openware recently acquired
ObjectBuilder. 

ObjectBuilder is currently available on Sun/Solaris, HP 9000/700 and IBM
AIX RS6000. We will also be supporting SGI, DEC Alpha, Sco UNIX, Unysis
Unixware and NCR SVR4.

Contact:
Kris Gottschalk
Openware Technologies, Inc.
Object Technologies Business Unit
1-800-933-5558  x4224
---------------------------------------------------------
C++ Data Object Library has a wide variety of data structures combined
with automatic persistence (storage to disk). In many applications, using
the library is like building your own OO database. The emphasis is on
high performance and protection against allocation and pointer errors.
The library can help practically any C++ project, but is especially
useful for large and complex software projects designs such as VLSI CAD.

Uses a code generator. Data relations are represented as objects.
Protection against pointer errors is achieved by using rings
instead of NULL ending lists. Smart iterators permit to delete
objects while travering lists.
Several methods of storing data to disk, including memory
blasting (storing entire pages of memory). 
Portable programs and data, schema migration.
Data organizations: lists, collections, aggregates, trees, graphs,
dynamic arrays, hash tables, pointer links, reference counting,
many-to-many relation, dynamic properties (like in LISP), virtual
(disk access is if a large array), run-time access to
type tables.

The library is build on ideas described in "Taming C++: Pattern
Classes and Persistence for Large Projects", by Jiri Soukup,
Addison-Wesley 1994.
    
Sells in full source, and runs with all major compilers, just
to name a few: Sun, HP, AT&T, Borland, Microsoft, Zortech, Watcom,
Digital, GNU, UNIX, Windows, OS2, Macintosh System 7.
A C version with similar features but with a less
elegant interface is also available.

No licence restrictions and no marketing tricks. You can ship
the source of the library with your programs, except for the code generator.
A complete regression test, documentation and support comes with the
basic price. We are one of the oldest class libraries in business,
and we stand behind our software. Prices in US$:
        $299 DOS,WINDOWS, or MAC
        $599 UNIX workstations
        Postage included in North America, $25 for overseas.

    email: jiri@debra.dgbt.doc.ca

    Code Farms Inc
    7214 Jock Trail, Richmond, Ont., K0A 2Z0, Canada
    tel 613-838-4829,  fax 613-838-3316
---------------------------------------------------------
CommonPoint Application System is a comprehensive C++ class library for
writing portable GUI applications. It includes a GUI builder, a
development environment, full international language support, full 2D and
3D graphics, multi-media, collection classes, customizable text and
graphics editors, a compound document architecture, a workspace/finder,
etc.. It is fully supported. 

CommonPoint is currently available for IBM AIX RS6000 workstations. Future
versions will run on additional platforms.

Company: Taligent, Inc., Cupertino, CA

URL: http://www.taligent.com/
---------------------------------------------------------
Memory Tuning System (MTS) - Fast, efficient memory allocator
specifically designed to minimize paging and data fragmentation 

Improves run-time performance by:
--  Minimizing virtual memory paging
--  Providing faster malloc/free calls
--  Minimizing memory fragmentation

Improves programmer productivity with:
--  Standard C library malloc interface
--  Works with C, C++, FORTRAN
--  Availability on Unix, OS/2, Win32s and Windows NT
--  Consistent performance across multiple machines
--  MTS shipped as portable C source code

Corporate Headquarters:
	1.800.NEWCODE (1.800.639.2633)
	E-mail:	info@newcode.com

Eastern Office:
	NewCode Technology, Inc.    Tel:    508.454.7255
	650 Suffolk Street          Fax:    508.454.7559
	Lowell, MA 01854            Email:  zeev@newcode.com

Western Office:

	NewCode Technology, Inc.    Tel:    303.416.0784
	2406 Newport Court          Fax:    303.416.0753
	Fort Collins, CO 80526      Email:  al@newcode.com
---------------------------------------------------------
Warne's Garbage Collector (WGC)

WGC is a full-featured high-performance C++ memory manager that includes:
    - an incredibly fast explicit memory manager (drop-in new/delete)
    - a parallel incremental generational non-copying collector    
    - a transparent just-in-time heap-checker

WGC's fast explicit memory manager provides a drop-in accelerated new/delete.
Using a multi-tiered parallel algorithm with the first tier inline, WGC
can allocate most objects inline in less than 10 instructions!  To enhance
space efficiency WGC uses address-aligned storage algorithms with no 
per-object overhead (no linked lists!).  To reduce fragmentation, WGC 
maintains a single process free store for all threads, modules, and DLLs.

WGC's collector implements both conservative and accurate scanning and
fully supports C++ code.  Classes, arrays, scalars, interior pointers,
unions, cross-heap pointers, anonymous unions (really!), large objects, 
library code you have no control over, etc. are all supported.  Plus, you 
can incrementally deploy automatic memory management in existing or new 
applications, making some classes or objects collected and some not.  

WGC's just-in-time heap-checker stays active during the entire development
cycle, transparently checking every new and delete.  If a check fails,
WGC will spawn your debugger and take you live to the line in question.
To complement the live access to the line that failed a delete check, WGC 
provides detailed pointer/object info (allocating thread/line/file/pass 
count, object allocation time in microseconds, etc.)  Debugging extensions
allow interactive display/logging of object/pointer status and process stats.

WGC is currently available for all major C++ compilers under Windows NT, 
Windows 95, and OS/2.  WGC is priced at $895 per developer for all platforms, 
with no royalties.  Team & Volume discounts apply.  Source available.  Ports
to other platforms in progress.

        Reflective Software Corp
        2660 Estevan Ave.
        Victoria, BC, CANADA, V8R 2T4
        (800) 707-7171
        (604) 683-0977
        (604) 598-9546 (fax)
        Contact: Kevin Warne (kevinw@reflective.com)
---------------------------------------------------------
The fACTs++ Class Library (financial Application Construction Tools in C++)
is a homogeneous tool-box of more than 300 C++ classes and templates. 
fACTs++ provides programmers with design patterns for distributed
client-server applications supporting multi-currency securities and
transactions, along with associated international conventions. The library
includes a complete set of foundation classes, parallel processing and 
communication classes, extendible financial instrument hierarchy and 
financial modeling classes.
 
fACTs++ features include:
 
    -   Dynamic Object Type Identification with Smart Pointers
    -   Streams Interface
    -   Container Templates
    -   Time, Date, Calendar and Timer classes
    -   String and Regexp Classes
    -   Mathematics and Financial Modeling Classes
    -   Internationalization Support
    -   Interface To Persistence Storage and Extendible Objects
    -   Application Configuration Framework
    -   Human-Computer Interface Tools, including Model-Viewer
        Controller Classes
    -   Distributed Processing Primitives and Client-Server Framework
    -   CashValue, CashFlow, Payment, Yield and DayCount, Market classes
    -   Comprehensive and extendible set of instrument definitions, 
        such as Swap, Bond, Basket and Derivative
    -   Portfolio, Position and Transaction Classes
    -   Yield Curve, Volatility and Time Series Classes
 
fACTs++ is available, on a per-project basis, as part of Objective 
Edge's custom software engineering service. The company's training program   
allows clients to quickly "ramp-up" their object-oriented development 
projects, providing early, visible results while reducing development costs.
Upon project completion, clients are left with a technology base and  
application architecture which they are able to leverage in future development
activities. 
 
fACTs++ is currently supported on Solaris 2.X and x86, and may be ported
to any POSIX compliant platform on a custom development basis. 
 
fACTs++ is a trademarks of Objective Edge Inc.  
Copyright(c) 1994, 1995 Objective Edge Inc. All rights Reserved.

For more information, please contact:
 
    Objective Edge Inc.
    Suite 401, 194 Merton Street
    Toronto, Canada
    M4S 1A1
 
    Telephone: 416-485-7186
    Facsimile: 416-485-6473
 
    e-mail: info@objectiveEdge.com
---------------------------------------------------------
WinSockets++ 1.1: A C++ class library for WinSockets.

The poster sent me the following paragraph. It has a little too much hype 
for my taste. (S)he also included a complete copy of the Programmers Guide
- I am afraid I don't have time to read and summarise it here.

This is more than just a wrapper for the WinSockets calls. It provides
higher-level functions that make reading/writing to sockets very easy.
Additionally, the Async aspect of the library makes using the
asynchronous functionality of WinSockets *very* easy and your code *very*
clean. 

It costs $50 which includes full source.

	email: troy@cais.com.
---------------------------------------------------------
Distinct TCP/IP for Windows Software Development Kit

C++ Class Libraries for FTP, Telnet and Windows Sockets.

Allows developers to develop TCP/IP applications without making calls
directly to a C Dynamic Link Library (DLL). Applications are created
using the Distinct C++ Class Libraries, which take care of establishing
the connection between the client and server side of the application. All
functionality normally associated with calling a TCP/IP application is
taken care of by setting data members and by handling upcall events.
Applications are notified of errors, connection changes and incoming data
by an upcall posted by the library to the applications window, by
providing a callback function to the library or by making polling calls
to the library at frequent intervals. 

Supported compilers: Microsoft C++ version 7 and Visual C++ 1.0 and 1.5.

Standard Edition:$495.00
Professional Edition:$695.00
Distinct TCP/IP Run Time: $100.00

	Distinct Corporation
	12901 Saratoga Avenue, #4
	Saratoga, CA 95070

	Tel: (408) 366-8933
	Fax: (408) 366-0153
	Fastfacts: (408) 366-2101
	email: mktg@distinct.com
---------------------------------------------------------
Generic++

Class library with container classes and basic data types for the 
development of portable, object-oriented applications

This C++ library is completely new. It is aimed at commercial users 
and implements a generous selection of application-independent 
basic classes. Its use frees the user from error-prone and time-con-
suming specific tasks (e.g. main memory management). 
All libraries previously available on the market are targeted more or 
less specifically on a particular system environment. However, it is 
becoming more and more urgent to make as many application mod-
ules as possible independent of a specific target platform. What 
gives Generic++ its competitive edge is the portability of its com-
ponents and the way it takes account of other software engineering 
aspects.

Advantages: * Implementation of the most important application-
independent basic classes * Availability on all standard operating 
systems and platforms * Accommodation of the latest C++ exten-
sions such as templates and exception handling * Co-existence with 
other libraries * High degree of runtime efficiency and low resource 
consumption * Integrated debugging support * Template-based, 
typesafe container classes with interchangeable implementation 
data structures * Suitability for use in the development of client/
server applications in heterogeneous networks. 
Unix (cfront, IBM xlC), WindowsNT, OS/2 (Watcom, IBM CSet++), Windows/DOS
(Borland, Watcom, Symantec)

(Price: 782 DM)
Contact:
	Paul.Micke@mch.sni.de

	Paul Micke
	SNI SU AP 443 MchP/Lz
	Siemens Nixdorf Informationssysteme AG
	Otto-Hahn-Ring 6
	D-81739 Muenchen
	Tel.: (49) 89 636-42756
	Fax.: (49) 89 636-43461
---------------------------------------------------------
DiaViews++

Class library for the development of graphical user interfaces 
(GUI) in OSF/Motif and C++

This library combines the power of the OSF/Motif toolkit with the 
advantages of the C++ language by means of completely encapsu-
lating the Motif objects (widgets/gadgets). This means there is a 
C++ class for every Motif object. 
DiaViews supports the structured, object-oriented development of 
Motif interfaces. 
C++ features such as rigorous type checks and virtual functions, etc. 
enhance the efficiency of the development process. 

Advantages: * Uniform C++ interface with OSF/Motif * Frame-
work for generating reusable UI components * Use of callback 
objects * Interface with Dialog Builder, the interactive tool from 
Siemens Nixdorf for OSF/Motif user interfaces * Simple and relia-
ble handling of Motif resources * Automatic generation of make-
files * Minimal training overhead.
(Price: 1750 DM)

Contact:
	Paul.Micke@mch.sni.de

	Paul Micke
	SNI SU AP 443 MchP/Lz
	Siemens Nixdorf Informationssysteme AG
	Otto-Hahn-Ring 6
	D-81739 Muenchen
	Tel.: (49) 89 636-42756
	Fax.: (49) 89 636-43461
---------------------------------------------------------
BCM

Class library for the support of inter-process communication (IPC)

The class library BCM (Base Communication Module) supports 
both general communication (local and network-wide) and an inte-
grated name service. BCM implementation is based on Internet 
Sockets, which use the TCP/IP protocol. This means that the C++ 
input/output streams can be made transparent for use in inter-proc-
ess communication. 

Advantages: * The user does not have to bother about platform-spe-
cific details * Classes are available for transport, the dispatcher, 
data representation, the message header and the name service.
(690 DM)

Contact:
	Paul.Micke@mch.sni.de

	Paul Micke
	SNI SU AP 443 MchP/Lz
	Siemens Nixdorf Informationssysteme AG
	Otto-Hahn-Ring 6
	D-81739 Muenchen
	Tel.: (49) 89 636-42756
	Fax.: (49) 89 636-43461
---------------------------------------------------------
OSQLIF

Class library for the development of SQL database applications

This library connects an SQL database with an application written 
in C++. The new options offered by the object-oriented language 
make it possible to implement a considerably more efficient user 
interface than is possible with the traditional `embedded' SQL. The 
aim is to set up a simple and efficient connection between an SQL 
database and an application developed in C++. SQL data types and 
both dynamic and static SQL are supported. This means that all the 
features of an SQL database can be accessed from a C++ applica-
tion.

Advantages: * The user can forget about a large number of data-
base-specific details with regard to communication * Secure inte-
gration in object-oriented C++ applications * When ANSI-SQL is 
used, the application can be ported between various databases.

Contact:
	Paul.Micke@mch.sni.de

	Paul Micke
	SNI SU AP 443 MchP/Lz
	Siemens Nixdorf Informationssysteme AG
	Otto-Hahn-Ring 6
	D-81739 Muenchen
	Tel.: (49) 89 636-42756
	Fax.: (49) 89 636-43461
---------------------------------------------------------
Extended C++ Standard Components

Foundation class library for the development of object-oriented 
software

This standard library for C++ programming consists of C++ Stand-
ard Components Rel. 3.0 (UNIX System Laboratories) and SNI 
Extensions. It contains universal classes that can be used under 
UNIX by any C++ programmer. 

Advantages: * The generic container classes were implemented 
using templates * Systematic approach: "you get what you need" * 
Efficient memory managementu The generated code is fast and 
concise and can be compiled 
quickly.

Contact:
	Paul.Micke@mch.sni.de

	Paul Micke
	SNI SU AP 443 MchP/Lz
	Siemens Nixdorf Informationssysteme AG
	Otto-Hahn-Ring 6
	D-81739 Muenchen
	Tel.: (49) 89 636-42756
	Fax.: (49) 89 636-43461
---------------------------------------------------------
SOFTPRO TOUCH-GUI C++ class library for OS/2:

SOFTPRO GmbH has announced its new 32bit C++ class library TOUCH-GUI 2.1
for OS/2 2.x. The product contains more than 140 classes which support
windows, menu bars, multi-threading, controls (including all OS/2 2.x
controls: slider, value set, notebook, container), dialog boxes, graphics,
printer control, MDI, DDE, Drag and Drop, loadable resources, and
management of profiles (.INI files). Other features include auxiliary
classes for data manipulation and storage management. Additionally, TOUCH-
GUI 2.1 contains high-level classes like formatted entry fields, tables,
and complete NLS. Furthermore, TOUCH-GUI 2.1 is fully integrated in STAR
CASE++, an OOA/OOD case tool (method: Coad/Yourdon), and Intersolv's PVCS
(a version control system).  

Supported C++ compilers are: Borland, GNU (emx), IBM, and WATCOM

The product includes online (.INF) and printed documentation, a demo
program, and samples. 

Planned availability: April, 1994

TOUCH-GUI 2.1 costs DM 1.720,00 excl. VAT (ca. US $990), the runtime
DLL's may be distributed royalty free. For upgrade prices and special
project licenses (including source code of TOUCH-GUI) contact the
supplier. NOTE: TOUCH-GUI 2.1 single license will be available at a
special price of DM 199,00 excl. VAT (ca. US $120) during 04/01/94 -
06/30/94. Printed documentation is not shipped with the special price
product, it is available for another DM 99,00 excl. VAT (ca. US $60).
However, full online documentation is included. 

	SOFTPRO GmbH, Stadtgrabenstr. 21, 
	D-71032 Boeblingen, 
	Germany,
	Tel.: +49 7031 6606-0 Mr. Frank Fuchs (extension -50)
	Fax: +49 7031 6606-66,

email:
	ffu@softpro.de,
	IBMMAIL (IEA): DEJP9SK9
---------------------------------------------------------
Persistence is supposed to give access to a relational database from 
a C++ object model.

	Persistence Software Inc
	1700 Sourth Amphlett Blvd, Suite 250
	San Mateo, Ca 94402
	415.341.7733
---------------------------------------------------------
Tools.h++ is the basic Rogue Wave tools library.

Tools.h++ consists mostly of a large and rich set of concrete classes
that are usable in isolation and do not depend on other classes for their
implementation or semantics. 

Components include Collections, String processing, Time & date handling, File space
manager, B-Tree disk retrieval, bit vectors, virtual I/O streams, caching
managers, virtual arrays, etc. 

email:	info@roguewave.com

	Rogue Wave Software, Inc., 
	1325 NW 9th Street
	Corvallis
	OR, 97330
	(503) 754-2311
	Fax: (503) 757-6650
---------------------------------------------------------
Matrix.h++ includes all the functionality of Math.h++.  For example:
general matrices, vectors, statistics, complex numbers, Fast Forier
Transformation (FFT's), etc.  Matrix.h++ adds specialized matrix classes
such as banded, symmetric, positive-definite, Hermitian, tridiagonal, etc.
Because Matrix.h++ includes Math.h++, it can take advantage of
Math.h++'s highly optimized low-level assembly routines, making it fast
as well as graceful.

Prices range from $199 to $995

email:	info@roguewave.com

	Rogue Wave Software, Inc., 
	1325 NW 9th Street
	Corvallis
	OR, 97330
	(503) 754-2311
	Fax: (503) 757-6650
---------------------------------------------------------
Linpack.h++ is the jewel of C++ math classes.  Linpack.h++ includes all
of Matrix.h++, plus all of the functionality in the original and well-
established Fortran version; including solutions of systems of equations
for a variety of matrix types, solutions of over- and under-determined
systems of equations, incremental least squares solvers, etc.  But,
Linpack.h++ is a tru object-oriented library, not just a C version that
compiles under C++:  the traditional messiness of the Fortran version has
been replaced with high-level, yet efficient, objects that make code far
easier to write and maintain.

Prices range from $299 to $1195

email:	info@roguewave.com

	Rogue Wave Software, Inc., 
	1325 NW 9th Street
	Corvallis
	OR, 97330
	(503) 754-2311
	Fax: (503) 757-6650
---------------------------------------------------------
Classix

In addition to Rogue Wave, Empathy offers a good general-purpose
library called Classix.  

I do not have confirmed information, but I have been told that this 
library is no longer available.

	Empathy
---------------------------------------------------------
USL C++ Standard Components

Formerly developed and marketed by AT&T Bell Laboratories and UNIX System
Laboratories, these are now developed and licensed by Novell Systems
Group.  A binary version is bundled with the UnixWare SDK (UnixWare 2 and up);
this version is currently at Release 3.1.  A source version is available for 
all other platforms (primarily UNIX-based); this version is currently at 
Release 3.0, and no new releases are planned.

C++ Standard Components include :
 
Args - argc/argv command line parser.
Bits - bit manipulation to arbitrary-length bitstrings.
Block - dynamic arrays.
Array_alg - efficient algorithms for searching, sorting, inserting etc.
Fsm - finite state machines.
G2++ - message formatting for inter-process communication. 
Graph - maintain arbitrary relationships between arbitrary entities.
Graph_alg - including searching, cycle and component detection.
ipcstream - inter-process streams.
List - doubly-linked lists.
Map - like arrays, except that the subscripts can be non-integral.
Objection - like UNIX software signals.
Path - facilities for manipulating UNIX path names and UNIX search paths.
Pool - optimise memory allocation.
Regex - regular expressions.
Set - including Sets, Bags, and pointer sets.
Stopwatch - for timing critical sections of code
String - variable-length character strings.
Strstream - iostreams for Strings.
Symbol - efficient symbol table handling & sorting.
Time - Time, Duration (time difference) and Place (geographical location).

Also included are the following tools :

c++filt  - demangles C++ names in standard input.
dem  - demangles C++ names in an argument list.
demangle  - demangles C++ names in a.out for easier debugging.
fs  - a tool and library to help find freestore bugs.
g2++comp  - compiles G2++ record definitions.
hier  - displays the inheritance hierarchy in a program.
incl  - displays the hierarchy of include files used in a program.
publik  - displays the public interface of a class.

For product, sales, and licensing information about the source version
of C++ Standard Components:

        Novell, Inc.
	2180 Fortune Drive
	San Jose, CA  95131

	attn:	Larry Bouffard
	phone:	408-577-7983
	e-mail:	larry_bouffard@novell.com
---------------------------------------------------------
Booch Components

Rational markets the C++ Booch objects which are a somewhat bizarre,
but possibly quite innovative, set of library objects.

It appears quite complete (unless you have some specific, uncommon
needs); Booch may have an edge in supporting concurrency. USL may have
more installations and greater maturity.

	Rational OO products
	408-496-3700
---------------------------------------------------------
StarView - A Portable C++ Class Library for Graphical User Interfaces

StarView is a portable C++ Class Library for Graphical User Interfaces.
StarView is one of the major parts of our total Object Oriented
programming environment (we call it SOLAR system). 

-   portability between the operating systems MS-DOS, OS/2, Macintosh
    and different UNIX flavours
-   at  least portable between  the  GUI's MS-WINDOWS, MS-Presentation
    Manager, MacApp and OSF/Motif
-   fulfillment of the requirements of the different GUI Style
    Guide's
-   data  exchange and direct communication between the applications in
    homogeneous and heterogeneous networks (groupware approach)

StarView will support the following GUI's / Compilers:

Windows 3.x
        Borland C++
        Zortech C++

Presentation Manager
        Zortech C++

OSF Motif
        Sun C++
        Zortech C++
        Glockenspiel C++

Macintosh
        MPW C++

Author:     Andreas Meyer, STAR DIVISION

	STAR DIVISION GmbH
	Andreas Jahnke
	Sachsenfeld 4
	D-20097 Hamburg
	Germany

	Phone: ++49 40 23646 500
	Fax:   ++49 40 23646 550
	Email: svinfo@stardiv.de

	Star Division
	2180 Sand Hill Road, Suite 320
	Menlo Park, CA 94025
	(800) 888-8527
	(415) 233-0142 (fax)

	svinfo@starlab.uucp
---------------------------------------------------------
Open Dialogue

	HP/Apollo
---------------------------------------------------------
MacApp (application development toolkit)

	Apple
---------------------------------------------------------
ICpak101, ICpak201

	Stepstone
---------------------------------------------------------
NeXTStep (application development toolkit)

	NeXT
---------------------------------------------------------
CommonView (Iconic user interface)

	Glockenspiel
---------------------------------------------------------
CommonView Glockenspiel

This is a C++ UI library. In addition, it comes with container classes.
The down-side is that some of the features are not supported across all
platforms. 

	Computer Associates International
	One CA Plaza
	Islandia, NY 11788
	(516) 342-2308
	(516) 342-6947 (fax)
---------------------------------------------------------
Galaxy

This is a C UI library, but it's written in an object-oriented style and
is type safe for C++ use. The package includes a WYSIWYG GUI builder. 

The tools are, reportedly, pretty full-featured. User-interface items
have extensive abstraction (for example, they have a confirmation-type
dialog that resolves to a push-pin and 'apply' button under openlook, but
'ok', 'apply', 'cancel' buttons under motif). Objects can be positioned
relative to each other (rather than merely absolute position on the
screen). Also, errors are handled with an abstract exception handling
framework. They support internationalization of fonts (at least Japanese),
money, and data formatting. 

Some extra-cool features include memory leak detection and C-language
objects for text (multi-styled, multi-font text with embedded graphics),
list (spreadsheet-like for handling up to 2^31 x 2^31 cells with
customizable displays), and graphics processing. 

	Visix
	11440 Commerce Park Drive
	Reston, Virginia 22091
	(800) 832-8668
	(703) 758-2711
	galaxy@visix.com
---------------------------------------------------------
Guild

This is a C-language UI library, but they're type-safe for C++
compatibility. The package includes a GUI builder and an event occurrence
monitor. 

Additional features in the library includes support for international
character sets, portable file system support and nifty C-language classes
for pie-charts, 3d bars, x-y plots, and the like. 

OPTIONS:
    Graphic Modeling        $995
    Oracle Database Bridge  $395
    ODBC Database Access    $495

	Guild
	1710 S. Amphlett
	2nd Fl.
	San Mateo, California 94402
	(415) 513-6650
	(415) 349-4908 (fax)
---------------------------------------------------------
MainWin

	Machine Independent Software
---------------------------------------------------------
ObjectViews

I believe this is a commercial version of InterViews.

	Quest Windows
---------------------------------------------------------
Open Interface Version 3.0

This is a C-based UI library, but type-safe for C++ compatibility. The
software also comes with a WYSIWYG GUI builder. 

They include tons of extra widgets like business graphics (bar, pie, and
line charts), images (all standard formats), and hypertext help. 

Other software in Open Interface includes international character support,
multi-font support, full printer support, memory management, file I/O
support as well as Windows DDE support (the latter is, of course, non-
portable). 

They also have a product called Nexpertobject, which is an expert systems
tool intended for GUI development. 

	Neuron Data
	156 University Avenue,
	Palo Alto, California 94301
	(800) 876-4900
	(415) 321-4488
---------------------------------------------------------
Wind/U-MFC

Wind/U-MFC - A Unix version of the popular Microsoft Foundation
Classes shipped with Visual C++ (a 16-bit MFC 2.5 and a 32-bit MFC 2.1).

	Bristol Technology Inc.
	241 Ethan Allen Highway
	Ridgefield, CT 06877 USA
	phone: (203) 438-6969
	fax:   (203) 438-5013
	email: info@bristol.com
	URL: http://www.bristol.com
---------------------------------------------------------
WNDX

	WNDX
	1550 8th Street S.W. Suite 305
	Calgary, Alberta Canada T2R 1K1
	(403) 244-0995
---------------------------------------------------------
XVT Portability Toolkit

This is a C-language library of functions (although, you can pay extra
for C++). They have a WYSIWYG GUI builder, but they charge for that, too.


OPTIONS:
    C++ capability                      $200
    XVT-Design (a WYSIWYG GUI builder)  $1200 ($2900 for non-PC UNIX)
    Source Code                         (call)

	XVT Software Incorporated
	4900 Pearl East Circle
	Box 18750
	Boulder, CO 80308
	(800) 678-7988
	(303) 443-4223 (phone)
	(303) 443-0969 (fax)

	info@xvt.com
---------------------------------------------------------
zApp Developer's Suite V2.2

The zApp Developer's Suite is a set of libraries and a designer 
containing over 300 object classes that provide GUI and other 
capabilities. It is the single solution to the problem of quickly 
writing commercial quality applications that run on multiple 
platforms. The zApp Developer's Suite consists of zApp, the industry 
leading C++ application framework; zApp Factory, a visual designer and 
code generator for the zApp environment; and the zApp Interface Pack, 
a set of powerful custom controls for zApp. Applications generated 
using the zApp Developer's Suite are single source portable to 
Windows, Win32 (Windows NT, NT on the DEC Alpha, and Chicago), DOS 
Text, DOS Graphics, OS/2 and X/Motif (Sun Solaris 2.x, Sun SunOS 
4.1.x, IBM RS/6000 AIX, HP HPUX 9.x, SCO UNIX, SGI IRIX 5.2, Unixware 
and Sun Solaris x86.)

The software comes with about 2500 pages of documentation and complete 
on-line help. It costs between $1,000 and $5,000 per developer, 
depending on the platforms needed.

	Inmark
	2065 Landings Drive, 
	Mountainview, CA 94043 
	(800) 3-inmark 
	(415) 691-9000 
	(415) 691-9099 (fax) 
	sales@inmark.com 
---------------------------------------------------------
Zinc V3.5

This is a full C++ class library that comes with the Zinc Designer (a
WYSIWYG GUI builder). Their classes include some graphic capabilities, a
rather nice error system, and a portable, if rudimentary, help system.
Also included is the source for the library (and for the Designer!). 

In addition to the usual GUI stuff, Zinc also provides international
character support (an extended version, for extra bux, is in the works),
some container classes, and filesystem portability. They also allow you
to incorporate platform-specific stuff (e.g., system messages) into their
API; but, of course, you're on your own when it comes to porting any
additions. 


	ZINC Software Incorporated
	405 South 100 East 2nd Floor
	Pleasant Grove, UT 84062
	(800) 638 8665
	(801) 785-8900
	(801) 785-8996 (fax)
	(801) 785-8997 (bbs)

	tech@zinc.com
---------------------------------------------------------
OpenUI is another GUI builder

This interface supports C, Pascal, and (ish) COBOL.

	Open Software Associates
	P.O. Box 3599
	Sunnyvale, CA 94088-3599
	(408) 730-2626
---------------------------------------------------------
NetClasses++, C++ classes for message passing environments:

NetClasses is a set of C++ class libraries that is organized as an object-
oriented software toolkit for distributed, message-passing based
programming. 

Facilities include :

Transporting objects over a network. NetClasses can transport: Arbitrary
C++ objects derived from PostModern's TransObject class, arbitrary NIH-
derived objects, and NetClasses Typed Objects. 

NetClasses Typed Objects provide an object-oriented data transport in
which the structure and organization of objects is specified externally
in configurable files using a simple, programming language independent
abstract syntax notation, the NetClasses Abstract Syntax Notation (NASN).

Remote method invocations (RMI). Using RMI, an application on machine B
can invoke a method on machine A. RMI makes fault tolerance and
connection management transparent to the application programmer. The RMI
layer is built on top of the distributed services package that is
described below. 

Reading and writeing all three varieties of NetClasses-transportable
objects on streams using machine-independent external representations. 

Currently available on Sun SPARC; currently testing on HP workstations.

NetClasses Development License          $1995
NetClasses Runtime License               $495
NetClasses Source Code License          $7995
(includes 3 runtime licenses)
NetClasses training class               $2000
NetClasses consulting and porting services (ask for quote)

	Qualix Group
	1900 S. Norfolk St. Suite 224
	San Mateo, CA 94403
	info@qualix.com
	1-800-245-UNIX (voice)
	(415) 572-1300 (fax)
	(415) 572-0200 (voice)
---------------------------------------------------------
Aspect

This is a C library, though they're type safe for C++ compatibility. A
GUI builder is provided with the library. They're coming out with a C++
class library soon. 

	OPEN Inc.
	655 Southpointe Court, Suite 200
	Colorado Springs, CO 80906
	(719)527-9700 (sales, customer service, tech support)
	(719)576-3835 (fax)
---------------------------------------------------------
C++/Views

This is a C++ library based on the smalltalk model (all classes come from
one superclass, and they have a smalltalk-like class browser). They do
not have a WYSIWYG GUI builder. 

Note - recently bought by Intersolv (of PVCS fame).

Additional features include various container classes.

	Liant Software Corp.
	959 Concord St.,
	Framingham, MA 01701 USA
	(800) 237-1873
	(508) 875-2246.
	support@lpi.liant.com
---------------------------------------------------------
Presentation Services Manager UI library

No WYSIWYG GUI builder exists, but they do include a script language. 

	Lancorp Pty Ltd
	33 Nott St
	Port Melbourne 3207
	Australia
	+61 3 646 7100 (phone)
	+61 3 646 8610 (fax)
---------------------------------------------------------
ILOG C++ Software Components

ILOG VIEWS 2:C++ library and editor to design Very Graphical User Interfaces

ILOG VIEWS 2 high-level C++ class library is fully extensible and 
portable across Windows, OS/2, and Unix platforms.  It includes:
- portable resources, event management, and PostScript support
- a portable multi-look gadget library
- extensive 2D graphic object library including charts and gauges
- PowerObjects such as graph layout, spreadsheet, and Gantt chart  
- management of multiple views & layers (for cartographic applications)
- double buffering, infinite undo, zooming, and other editing operations
  
The development of portable VGUI applications is accelerated through 
ILOG PowerEdit, an extensible VGUI builder that generates standard C++ 
code.  PowerEdit reusable components are provided with ILOG VIEWS 2 so 
that developers can create and distribute their own custom editors.  

ILOG VIEWS 2 Dynamic Variable mechanism offer an interpretor for 
writing C formulae between variables to control the attributes of 
objects.  This allows for code-free animation and control of graphics 
objects.

ILOG VIEWS 2 provides a message translation mechanism so that messages 
used in the interfaces may be translated dynamically. The look and feel 
of ILOG VIEWS 2 applications can be changed dynamically from Motif to 
Windows on all platforms.

Platforms: DEC OSF/1, HP, IBM, Silicon Graphics, and Sun workstations
(both SunOS and Solaris) as well as on PCs running Microsoft Windows 3.1,
Windows NT, and OS/2 Presentation Manager. Demonstration CD-ROM available
upon request. 

ILOG BUILDER:
  is a GUI builder that generates OSF/Motif interfaces in C and C++.  It
  offers UIL read/write capabilities and tight integration with ILOG
  VIEWS.

ILOG DB LINK:
  is a C++ library to connect RDBMS such as Sybase, Oracle, Ingres,
  Informix, or SQLBase to C++ applications.

ILOG SERVER: C++ object server implementing real-time groupware applications

ILOG SERVER is a C++ library and preprocessor for building reactive
servers of C++ objects. It offers a client-independent external
abstraction of the data, which ensures the coherence of the shared
objects. Each client: 
- has its own API (Application Programming Interface) 
- only has to be concerned with the objects it manipulates
- does not have to worry about other clients sharing the same objects 

ILOG SERVER is an extension of the SmallTalk Model View Controller (MVC)
architecture to manipulate custom C++ objects instead of fundamental data
types. Developers describe object models by annotating their header files
using about 15 predefined keywords. Once the header files have been
annotated, ILOG SERVER's C++ preprocessor automatically generates the
appropriate C++ code. 

By extending the notion of a C++ pointer as a data member, ILOG SERVER
makes it possible to easily build relationships with cardinalities 
between C++ classes that will automatically be maintained.  This 
extension to C++ supports inheritance and relationships based on smart 
pointers.

Platforms: DEC OSF/1, HP, IBM, Silicon Graphics, and Sun workstations
(both SunOS and Solaris) 

Cost: $5,000 per Unix-based development license. Preferred university
rates available upon request. Demonstration CD-ROM available 

ILOG BROKER: C++ library and preprocessor that extend the C++ language 
to transparently support Distributed Object Computing environments.  

Developers can make any existing linked C++ application distributed, by
minimally changing their header files. A set of about 15 keywords enable
ILOG BROKER's preprocessor to generate standard C++ code. 

Once the header files have been annotated, the preprocessor automatically
generates the C++ source code to build the distributed application.
Communication between objects is performed through the use of local
surrogates calling methods on the real implementation objects across a
network. The current implementation relies on RPC for the transportation
layer. ILOG BROKER annotations have also been designed to generate IDL
code for CORBA 2 specifications. 

ILOG BROKER does not impose the use of a dedicated server.  Each object 
in the distributed application can be both a client and a server to and 
for other objects, therefore providing a true peer-to-peer programming 
tool.

Platforms: DEC OSF/1, HP, IBM, Silicon Graphics,
and Sun workstations (both SunOS and Solaris)

Cost: $5,000 per Unix-based development license. Preferred university
rates available upon request. 

ILOG SOLVER: 
  is a C++ constraint reasoning library for solving complex resource
  management problems such as scheduling, configuration, and planning.

ILOG SCHEDULE:
  is an add-on library to ILOG SOLVER dedicated to solving scheduling
  problems.

ILOG RULES: 
  is a C++ tool for data monitoring in real-time environments.  ILOG
  RULES embeddable inference engine applies rules directly on native C++
  application objets.

ILOG TALK: 
  is an object-oriented dynamic language offering a seamless integration
  with C++ class libraries.

Contact:
	ILOG, Inc., 
	2105 Landings Drive, 
	Mountain View, 
	CA 94043, USA
	tel: +1 415-390-9000, 
	fax: +1 415-390-0946, 
	net: info@ilog.com.  
	url: http://www.ilog.fr

Europe:
	ILOG SA, 
	12 avenue Raspail
	BP 7  94251 Gentilly Cedex
	France
	tel: +33 1 47 40 80 00
	fax: +33 1 47 40 04 44
	net: info@ilog.fr.

Asia:
	ILOG ASIAN HEADQUARTERS
	02-05 Cintech Building
	73 Science Park Drive
	SINGAPORE 0511
	tel: +65 773 06 26
	fax: +65 773 04 39
	net: ilogsin@solomon.technet.sg
---------------------------------------------------------
ImageSoft's Object/Engineering C++ class library supports simulation.

The library provides a natural approach to solving discrete-event
simulation problems. Modularity is reinforced by implementing the
process objects as concurrent tasks. Support is provided for dynamic
systems; transaction operators; transaction messages; as well as
queuing network thread with polymorphic scheduler (timer for
discrete-event simulation; tracer for simulation run; processes
in discrete-event simulation with services delay;
conventional/unconditional blocking, pre-emption, etc.;
shared queues/links in network with LIFO, FIFO & arbitrary
queuing discipline; producing node and source; consuming node
and sink; generic queuing network nodes and servers.

And full source code is provided together with extensive
documentation, examples and tutorial. There are also an
enourmous number of other class libraries included with
source that are of interest to the scientific and engineering community.

	ImageSoft Inc.
	2 Haven Avenue
	Port Washington, NY 11050
	(516) 767-2233
	(516) 767-9067 (Fax)
	(516) 767-9074 (BBS)
	email: mcdhup!image!object
---------------------------------------------------------
POET : Object Oriented Database

POET runs on the SPARC, NeXT, DOS, MS-Windows, Novell, OS/2, and
Macintosh. Other ports are in the works. Pricing starts at about $500. 00
for the DOS version, to a little over $1000.00 for the Unix versions. 

	BKS Software
	One Kendall Square
	Suite 2200
	Cambridge, MA 02139
	Phone: 617 / 621 7047
	Fax:   617 / 621 7097

In Germany : BKS Software
             Guerickestr. 27 
             1000 Berlin 10
             Germany
             Phone: +49 30 / 342 3066
             Fax:   +49 30 / 342 8413

	BKS Software
	4633 Old Ironsides Drive
	Suite 110
	Santa Clara, CA 95054
	Tel:	408 / 748 - 3403
	Fax:	408 / 748 - 9060

European Office:
	BKS Software
	Fo_redder 12
	2000 Hamburg 67
	Germany
	Tel:	+49 40 / 60 99 011
	Fax:	+49 40 / 60 39 851
	Internet: poet@bks.de

UK Office:
	Silicon River, Ltd.
	106-108 Powis Street
	London, SE18 6LU
	England
	Tel:	+44 81 / 317 7777
	Fax:	+44 81 / 316 7778
	BBS:	+44 81 / 317 2310
	Internet:  acourt@cix.compulink.co.uk
---------------------------------------------------------
ORION/ITASCA - Object Oriented Database

	Itasca Systems, Inc.  
	2850 Metro Drive
	Suite 300
	Minneapolis, MN  55425
	Tel: 612-851-3158
	Fax: 612 851 3157

A slightly different address from another poster ...

	Itasca Systems, Inc.
	7850 Metro Parkway
	Minneapolis, Minn 55425 
	Tel: (612) 851-3155
	Technical Contact : Doug Barry (doug@itasc.com)
---------------------------------------------------------
OS Object Oriented Database

	O2 technology
	Suite 2200
	1 Kendall Square
	Cambridge MA 02139
	U.S.A.
	Tel: +1 617 621 7041
	Fax: +1 617 577 1209

France : 
	O2 Technology
	7, Rue du Parc de Clagny
	78035 Versailles Cedex
	France
	Tel: +33 1 30 84 77 91
	Fax: +33 1 30 84 77 90
	Email: o2@o2tech.fr
	Contact: Didier Plateau
	Email: didier@o2tech.fr
---------------------------------------------------------
G-BASE/GTX (MATISSE) Object Oriented Database

	ODB, an Intellitic Intl Co.
	238 Broadway
	Cambridge, MA 02139
	phone: 	(617) 354-4220
	fax:	(617) 547-5420
	e-mail: info@odb.com
	Contact: Christina Bernard, Marketing and Communications
---------------------------------------------------------
OBJECTSTORE Object Oriented Database

email address for their distributor in France: bchavonnet@elsa.fr

	Object Design
	Main office	 		 California address
	One New England Executive Park	 101 El Camino Real, Suite 300
	Burlington, MA  01803		 Menlo Park, CA 94025
	Tel: 617-270-9797              (415) 327 - 5191
	Fax: 617-270-3509

UK Office:
	Object Design (UK) Ltd.
	604 Delta Business Park
	Welton Road
	Swindon
	Wiltshire SN5 7XP
	44-793-486111
	44-793-491177 (fax)
---------------------------------------------------------
Objectivity/DB Object Oriented Database

Objectivity/DB runs on the SPARC, as well as all sun platforms, all dec
platorms (and operating systems), hp 9000 series (68k and risc), ibm risc,
sgi, and some others, all in a mixed fully distributed and heterogeneous
environment.

Objectivity Inc.
	West coast                      East coast
	800 El Camino Real		67 South Bedford Street
	Fourth Floor			Suite 400W
	Menlo Park, CA  94025		Burlington, MA 01803
	Tel: 415-688-8000		Tel: 617 229 5817
	Fax: 415-325-0939		Fax: 617 272 0558

	11050 Strathmore Dr., #316/300B
	Los Angeles, CA  90024
	(310) 208-6117
	(310) 208-5677 fax

	email: info@objy.com
	European General Manager : Remy Malan (remy@objy.com)

For Germany:
	Dr. Matthias Frei
	Micram Microelectronic GmbH & Co. KG
	Universitatsstrabe 142
	4630  Bochum
	Germany
	ph:	+49  234  97 08-304
	fax:	+49  234  97 08-301
	e-mail:	frei@micram.de

For Sweden, Norway, Finland and Denmark:
	Mr. Kjell Hegerin
	Norsys Technology AB
	Finlandsgatan 12
	Box 1239
	S-164 28 Kista
	Sweden
	phone:	+46 8 750 75 75
	fax:	+46 8 703 92 72

For The United Kingdom:

	Valbecc Object Technology Ltd.
	115 Wilmslow Road
	Handforth, Wilmslow
	Cheshire  SK9 3ER
	United Kingdom
	contact:	Fred Peel
	ph:	+44  625  539903
	fax:	+44  625  539905
---------------------------------------------------------
ONTOS Object Oriented Database

	Ontologic, Inc.
	Three Burlington Woods
	Burlington, MA  01803
	Tel: 617-272-7110
	Fax: 617-272-8101 

UK distributor:
	VALBECC SOFTWARE
	Mr. Fred Peel
	115 Wilmslow Road
	Handforth,
	Wilmslow, SK9 3ER 
	U.K.
	tel +44 625 539 903
	fax +44 625 539 905
---------------------------------------------------------
KALA Object Oriented Database

Kala(tm) is a Persistent Data Server managing distributed, shared,
arbitrarily complex and evolving persistent data. Kala is highly
efficient and secure. Kala manages the visibility of persistent data
elements to its clients, thus supporting any types of transactions,
versions, access control, security, configurations. Kala does not
restrict you to any particular model. Kala provides the mechanism, but
imposes no policy.

o Kala is available now on Sun platforms (SunOS / 68K & SPARC). A
  80x86/DOS version is now available to alpha and early beta sites.
  Ports to Windows and MacOS are also likely in the near future. Any
  port is possible as NRE.
o Kala's interface is ANSI C, also callable from C++.

	Penobscot Development Corporation
	50 Princeton Road
	Arlington, MA 02174-8253
	USA
	Tel: +1-617-646-7935
	Fax: +1-617-646-5753
	Contact: Sergiu S. Simmel
	Email: sss@world.std.com 
	Information: kala-request@world.std.com
---------------------------------------------------------
IDB Object Databases

	Persistent Data Systems
	P.O. box 38415
	Pittsburgh, PA 15238-9929
	Tel: 412-963-1846
	Fax: 412-963-1843
---------------------------------------------------------
GEMSTONE Object Oriented Database

Briefly, GemStone is a full featured OODBMS with transaction control,
multiple users, multiple platforms supported, client server architecture,
active objects (ie, behavior can occur in the database as well as in the 
application using it), multiple language support, etc.

GemStone is actually quite a bit more than just a data repository - it is a
full-fledged DBMS that is pure OO. You can access the same database just as
easily from C, C++, or SmallTalk, or you can build entire database
applications inside the database server, because it is an active server
that runs methods written in our DML, OPAL, which is a dialect of
SmallTalk. There are also high-level tools to aid application building.

	Servio Corporation
	950 Marina Village Parkway
	Suite 110
	Alameda CA 94501
	Tel: 510-814-6200
	Tel: 800-243-9369
	Fax: 510-814-6227
	Contact : marcs@slc.com

UK Office:
	Servio-UK Ltd
	Criterion House
	Beauchamp Court
	Victors Way
	Barnet
	EN5 5TZ
	England
	Tel: (81) 447-0800
---------------------------------------------------------
VERSANT Object Oriented Database

Versant markets a full-function OODBMS together with associated DBA and
application developer tools. Versant is currently available on Sun-3, Sun-4, 
IBM RS/6000, HP 9000/400,700, DEC Ultrix, SGI, NCR, NeXT and Sequent platforms. 
An OS/2 port has just been released. Other platforms will be announced soon.
A Windows/NT port is in progress.

Interfaces to 'C', 'C++' and Smalltalk-80 are supported.

	Versant Object Technology
	4500 Bohannon Drive
	Suite 200
	Menlo Park, CA  94025
	Attn: Mike Mooney
	Tel: 1-800-VERSANT
	Tel: (415) 329-7500
	Fax: (415) 325-2380
	Tel: 415-325-2300
	Fax: 415-325-2380
	Contact: Mary Foussourier
	Email:info@versant.com, 
	Email:info@osc.com
	Email:aflynn@osc.com

European Office:
	Versant Europe
	Siriusdreet 2
	P.O. Box 333
	2130 All Hoofddrop
	The Netherlands
	Tel: (31) 2503-66373
	Tel: +31 - (0)2503 - 66851
	Fax: +31 - (0)2503 - 66855

UK Distributor:
	Admiral Software Ltd
	Admiral House
	193-199 London Road
	CAMBERLEY
	Surrey GU15 3JT.
	Tel: 0276 692269
	Contact: Kevin Adams
	Contact: Clive Harris
---------------------------------------------------------
M++

M++ isn't as well known as the RogueWave math.h++ libraries, but it has
been around for many years. It has a number of features that distinguish
it from the RogueWave classes, notably improved handling of temporaries. 

M++ was explicitly designed to provide the functionality of an array
language like Matlab or Gauss and it contains the Linpack, Eispack stuff
found in RogueWave's Linpack.h++. 

Dyad Software, also sell modules written in M++ for doing statistical
work, including linear and nonlinear least squares estimation, as well as
optimization, numerical integration, and differential equations. 

	Dyad Software
	6947 Coal Creek Pkwy, Suite 361
	Renton, WA 98059-3159
	206-637-9426 (voice)
	206-637-9428 (fax)
	206-271-9486 (bbs)
---------------------------------------------------------
Financial and other class libraries

I have no product details at present)

	Greenleaf Software, Inc.
	16479 Dallas Parkway, Suite 570
	Dallas, 
	Texas 75248
---------------------------------------------------------


Other Commercial sources of C++ code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
---------------------------------------------------------
The USL UNIX Toolchest is an electronic catalog for browsing and ordering
source software. This catalog provides unsupported software products,
developed within AT&T, for the commercial UNIX world. As you browse
through the online catalog, you'll find descriptions of all the tools,
complete with information on memory and disk requirements, documentation,
and license fees. 

United States and Canada, may access the Toolchest by dialing 1-908-522-
6900(e-7-1) and logging in as "guest". 

Note : The USL UNIX Toolchest is no longer marketed by USL or Novell; it
has reverted back to AT&T. The only contact info I have for it is the US
number 800-462-8146, option #2. 
---------------------------------------------------------
Checkout the ISCL CD ROM from ImageSoft, it contains the largest
collection of C++ source code ever compiled in one place. It's available
from ImageSoft ... 

	ImageSoft Inc.
	2 Haven Avenue
	Port Washington, NY 11050
	(516) 767-2233
	(516) 767-9067 (fax)
	(516) 767-9074 (bbs)
	email: mcdhup!image!iscl
---------------------------------------------------------
This is not a code CD but it has many libraries & some code (all msdos)
brought together into a CD. 

	EMS Professional Software, Specialized Software Libraries
	Baker Enterprises
	20 Ferro Drive
	Sewell, NJ 08080
	Fax: 609-582-9204
	Internet: rbakerpc@aol.com
---------------------------------------------------------

Other places to look for details of C++ libraries
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The index of resources for numerical computation in C or C++.
ftp from usc.edu in pub/C-numanal/numcomp-free-c.gz
---------------------------------------------------------
comp.object FAQ
---------------------------------------------------------
comp.windows.misc portable-GUI-software FAQ
---------------------------------------------------------
ftp.th-darmstadt.de /pub/programming/languages/C++/c++-products/*
---------------------------------------------------------
ASSET is currently populating a library of reusable components and
systems, and documents on software reuse, called the Worldwide
Software Reuse Discovery library (WSRD, pronounced "wizard"). Included
are assets in numerous languages including C++, C, and Ada. Visit our
on-line catalog at http://source.asset.com/

For more information on supplying products and advertisements for the
WSRD, please contact:

        ASSET
        Attn: Patrick A. Theeke
        P.O. Box 3305
        1350 Earl L. Core Rd.
        Morgantown, WV 26505
        e-mail: theeke@source.asset.com
        voice: (304) 284-9000

For more information on obtaining an ASSET account or accessing the
WSRD library, please contact:

        ASSET
        Attn: Account Administrator
        P.O. Box 3305
        1350 Earl L. Core Rd.
        Morgantown, WV 26505
        e-mail: info@source.asset.com
        voice: (304) 284-9000
---------------------------------------------------------

Tools for C++ Programmers
~~~~~~~~~~~~~~~~~~~~~~~~~

This section is just here because there isn't a separate Tools FAQ yet. 
I'm hoping someone will volunteer to maintain one. If you don't know how 
to maintain a FAQ, I'm willing to help get you started.

---------------------------------------------------------
Cback - Optimizes C source from the cfront C++ translator to create easy
to read, smaller, faster and portable C source, while maintaining or
improving compile times 

Improves run-time performance by:
--  Minimizing object code size (especially in debug)
--  Minimizing cfront output code size
--  Simplifying cfront data structures and expressions

Improves programmer productivity with:
--  Easier to read C source from cfront output
--  Portable C source from cfront output
--  Faster link times, reducing the debug cycle
--  Seamless integration into existing compile paths
--  Availability on a broad range of Unix platforms

Corporate Headquarters:
	1.800.NEWCODE (1.800.639.2633)
	E-mail:	info@newcode.com

Eastern Office:
	NewCode Technology, Inc.    Tel:    508.454.7255
	650 Suffolk Street          Fax:    508.454.7559
	Lowell, MA 01854            Email:  zeev@newcode.com

Western Office:

	NewCode Technology, Inc.    Tel:    303.416.0784
	2406 Newport Court          Fax:    303.416.0753
	Fort Collins, CO 80526      Email:  al@newcode.com

---------------------------------------------------------

From csus.edu!csulb.edu!nic-nac.CSU.net!charnel.ecst.csuchico.edu!olivea!spool.mu.edu!howland.reston.ans.net!newsfeed.internetmci.com!news.sprintlink.net!malgudi.oar.net!hyperion.wright.edu!valhalla.cs.wright.edu!not-for-mail Tue Sep 19 16:09:11 1995
From: pedwards@valhalla.cs.wright.edu (Phil Edwards)
Newsgroups: comp.lang.c++
Subject: FAQ ERROR: tgrind ain't there
Date: 17 Sep 1995 21:15:00 GMT
Organization: the top of Solsbury Hill.
Lines: 32
Approved: I couldn't find five dentists to ask.  Sorry.
Message-ID: <43i34k$vfm@valhalla.cs.wright.edu>
NNTP-Posting-Host: gamma.cs.wright.edu
X-Newsreader: TIN [UNIX 1.3 950824BETA PL0]
Status: O


The following is from the c.l.c++ FAQ obtained from rtfm:

==============================================================================
Q132: Where can I access "tgrind," a pretty printer for C++/C/etc
source?

"tgrind" reads a C++ source file, and spits out something that looks pretty on
most Unix printers.  It usually comes with the public distribution of TeX and
LaTeX; look in the directory: "...tex82/contrib/van/tgrind".  A more up-to-date
version of tgrind by Jerry Leichter can be found on: venus.ycc.yale.edu in
[.TGRIND].
==============================================================================

When I went to venus, it didn't recognize "ftp" nor "anonymous" as
valid usernames.

I'm going to try an archie on "tgrind" and if I find anything I'll
post it here.  In the meantime, would some person in charge of the
FAQ make some temporary note (in their heads at least) that the info
is out of date?


Luck++;
Phil


-- 
#include<std/disclaimer.h>                       The gods do not protect fools.
Phil Edwards, pedwards@cs.wright.edu                        Fools are protected
http://www.cs.wright.edu/people/students/pedwards/       by more capable fools.
Finger pedwards@gamma.cs.wright.edu                                -Larry Niven

From csus.edu!csusac!zimmer!waldorf.csc.calpoly.edu!charnel.ecst.csuchico.edu!psgrain!usenet.eel.ufl.edu!news.mathworks.com!tank.news.pipex.net!pipex!howland.reston.ans.net!cs.utexas.edu!not-for-mail Fri Sep 29 09:55:46 1995
From: easchwei@eos.ncsu.edu
Newsgroups: comp.lang.c++
Subject: FAQ: Read BEFORE you post
Date: 28 Sep 1995 18:45:30 -0500
Organization: UTexas Mail-to-News Gateway
Lines: 24
Sender: nobody@cs.utexas.edu
Message-ID: <9509282345.AA19075@styx.csc.ncsu.edu.eos.ncsu.edu>
NNTP-Posting-Host: news.cs.utexas.edu
Status: O

            The mini-FAQ on POSTING to comp.lang.c++.

  The comp.lang.c++ newsgroup is for the discussion of the language C++.  
  This definition is at best inexact however, and does not mean the same 
  thing to everyone.  But it does mean that posts to the comp.lang.c++
  newsgroup should have some direct relevance to the C++ language.

*****************************************************************************

  BEFORE POSTING TO COMP.LANG.C++

   - Please read the full FAQ. (ftp://rtfm.mit.edu/pub/usenet/comp.lang.c++/)
   - Ask yourself if your post is of some general interest to the 
        worldwide C++ community.
   - Double check that a more appropriate newsgroup does not exist for 
        your post. (eg. comp.unix.*, comp.os.ms-windows.*, comp.graphics,
        comp.os.msdos.*, comp.sys.mac.*, comp.sys.ibm.pc.*, etc.)
   - Your code/compiler not working right?  See the FAQ for suggestions on
        writing your question so it will be answered quickly and correctly.
   - Still confused? See news.announce.newusers.

*****************************************************************************



From csus.edu!csusac!charnel.ecst.csuchico.edu!IntGame!internetMCI!newsfeed.internetmci.com!news.sprintlink.net!howland.reston.ans.net!news-e1a.megaweb.com!newstf01.news.aol.com!newsbf02.news.aol.com!not-for-mail Sun Oct 15 13:08:16 1995
From: scotwi@aol.com (ScotWi)
Newsgroups: comp.lang.c++
Subject: Pointer to Visual C++/MFC FAQ...
Date: 7 Oct 1995 14:25:08 -0400
Organization: America Online, Inc. (1-800-827-6364)
Lines: 130
Sender: root@newsbf02.news.aol.com
Message-ID: <456gm4$g04@newsbf02.news.aol.com>
Reply-To: scotwi@aol.com (ScotWi)
NNTP-Posting-Host: newsbf02.mail.aol.com
Status: O


       Pointer to the World Famous VC++/MFC FAQ!
			

Getting the latest and greatest
-------------------------------

The latest version of the MFC FAQ is 1.3-->
(keep reading for information about the next release...)

   * The latest version can be downloaded from:
       ftp://www.unx.com/pub/mfc_faq/mfc_faqXX.txt
     or for you ZIP lovers:
       ftp://www.unx.com/pub/mfc_faq/mfc_faqXX.zip
     Where XX represents the latest version.

   * This FAQ is also available on the World Wide Web.
     http://www.unx.com/~scot/mfc_faq.html

   * The FAQ also is on CompuServe in the MSMFC forum, Developer
     exchange download section, and the file name is MFC_FAQXX.TXT and
     MFC_FAQXX.ZIP. Where XX is the version number 

   * Sadly, I can not email the FAQ to you because of my current workload.
 
     Don't despair, even if you do not have ftp access, you can get the
     FAQ automatically emailed by following these directions:

     1. Send the following email to: ftpmail@decwrl.dec.com:

        connect landru.unx.com
        chdir pub/mfc_faq
        ascii
        get mfc_faq13.txt
        quit

     2. The subject does not matter.
  
     3. Wait a couple of hours and Viola!  The FAQ should be waiting
        in your mailbox. 

     If you send me an email asking for the FAQ, I'll just put you on
     Instant-FAQ(tm) and you'll get the next version instead.


   * "Instant-FAQ (TM)" - If you'd like to have a copy of any new MFC FAQ
     releases emailed right to your front door, just send me an email via
     scot_wingo@msn.com and I'll add you to the 'subscription'.  No cost
     or anything, just another FAQ service.

     "Why wait for the announcements and then go get the FAQ yourself,
     use "Instant-FAQ (TM)"

     "Instant-FAQ(TM) changed my life!!!  I no longer have to wait for
     months for the latest FAQ.  It's just waiting in my email box the
     second it's released, no fuss no muss! Thanks Instant-FAQ(TM)"
     -Anonymous Instant-FAQ(TM) participant. 

     [All restrictions apply in states that do not allow Instant-FAQ
      service, please see your local MFC FAQ dealer for details.]


MFC FAQ 1.4?!
-------------
There will *NOT* be a version 1.4 of the MFC FAQ.  But don't despair,
version 4.0 of the MFC FAQ (hey if MS can do it, why can't I?) will be
released simultaneously with VC++/MFC 4.0.  It will be mostly focused
on covering the latest and greatest 4.0 information.  We expect it to
go out sometime in early November.   


MFC FAQ book?
------------
A publisher is pseudo-interested in a MFC FAQ book, but I'm having a
hard time convincing them that people would buy it.  What do you
think?  Would you pay $30-$40 for a MFC FAQ Book that had a sample for
each FAQ about 2X the number of FAQs in the on-line version and a
CD-ROM chock full of MFC samples?  Let me know what you think at
scot_wingo@msn.com and I'll send a summary to the publisher..


VC++/MFC 4.0 Info!
------------------
If you haven't visited http://www.microsoft.com/visualc lately, check
it out, there's lots of great pre-release information about 4.0.
Looks RED HOT!  Much of this information is also available on the
Compuserve forum: GO MSMFC.


NEW MFC Newsgroup!!
-------------------
Also, if you didn't know already, the MFC-only (yeah!) newsgroup was
approved and is online at most sites:

comp.os.ms-windows.programmer.tools.mfc

If you can't access it through your service, send them an email!


MFC mailing list
----------------
The MFC mailing list (see FAQ for details) in my opinion is still one
of the *best* places to learn about MFC.  There's no digest mode yet,
but it has been moderated so you don't see 100 postings about "when
will VC++ be released?".  Much more meaty now.


Stingray Web goes online 
------------------------
Stingray Software, the MFC extension company that I've co-founded, has
put white papers, pricing, etc.. on the web:
http://www.unx.com/~stingray.  All of this information is also
available on the CompuServe forum, GO STINGRAY.
We have two products, Objective Grid(tm) and MFC++(tm), both will be
released this month.


Adios
-----
That's all the news from MFC FAQ headquarters, stay tuned for release
4.0 of the FAQ and as always, if you want to subscribe to the FAQ or
have suggestions/comments, please send email to scot_wingo@msn.com.


Thanks,

Scot Wingo
MFC FAQ Maintainer
Stingray Software, Inc.
http://www.unx.com/~scot

From csus.edu!news.ucdavis.edu!agate!tcsi.tcs.com!uunet!eskimo!scs Thu Apr  6 20:27:10 1995
Newsgroups: comp.lang.c,comp.answers,news.answers
From: scs@eskimo.com (Steve Summit)
Subject: comp.lang.c Changes to Answers to Frequently Asked Questions (FAQ)
X-Nntp-Posting-Host: eskimo.com
Message-ID: <1995Apr01.1511.scs.0001@eskimo.com>
Followup-To: poster
Originator: scs@eskimo.com
Sender: usenet@eskimo.com (News User Id)
Reply-To: scs@eskimo.com
X-Archive-Name: C-faq/diff
Organization: only when absolutely necessary
Date: Sat, 1 Apr 1995 23:11:49 GMT
Approved: news-answers-request@MIT.Edu
Lines: 69
Xref: csus.edu comp.lang.c:102219 comp.answers:10963 news.answers:41074

Archive-name: C-faq/diff
Comp-lang-c-archive-name: C-FAQ-list.diff

This article contains a massaged diff list comparing the previous
revision of the comp.lang.c frequently-asked questions list (last
modified April 16, 1994, lightly patched December 31, 1994, last
posted March 1, 1995) and the current one.  Due to the massaging
(which is intended to make the changes easier to see), this list
is not suitable for input to a patch program.

I have been apologizing for some time about the number of changes
"in the works" but not reflected in the posted list; unfortunately,
I'm neither done apologizing nor updating.  A huge revision is
underway, which I do hope will hit this list Real Soon Now (and
which will also be hitting bookstores in September or October) but
which I still haven't had time to reformat and polish up for
posting.  In the meantime, the diffs here reflect only a few
miscellaneous changes which for various reasons I've patched in
by hand.

==========
< [Last modified April 16, 1994 by scs.]
---
> [Last modified April 1, 1995 by scs.]
---
> This article was last modified on December 31, 1994, and its travels may
> have taken it far from its original home on Usenet.  It may now be
> out-of-date, particularly if you are looking at a printed copy or one
> retrieved from a tertiary archive site or CD-ROM.  You can always obtain
> the most up-to-date copy by anonymous ftp from sites ftp.eskimo.com,
> rtfm.mit.edu, or ftp.uu.net (see questions 17.12 and 17.33), or by
> sending the e-mail message "help" to mail-server@rtfm.mit.edu .
> (Also, this article was produced for free redistribution.
> You should not need to pay anyone for a copy of it.)
> 
> Other versions of this document are also available.  Posted along with
> it are an abridged version and (when there are changes) a list of
> differences with respect to the previous version.  A few preliminary
> hypertext versions are available on the world-wide web (WWW); see URL's
> <http://www.cis.ohio-state.edu/hypertext/faq/usenet/FAQ-List.html> and
> <http://www.lysator.liu.se/c/c-faq/index.html>.  Finally, for those who
> might prefer a bound, hardcopy version (and even longer answers to even
> more questions!), a book-length version will be published by
> Addison-Wesley in Fall of 1995 (ISBN 0-201-84519-9).
==========
  	The mistitled _Annotated ANSI C Standard_, with annotations by
< 	Herbert Schildt, contains the full text of ISO 9899; it is
---
> 	Herbert Schildt, contains all but a few pages of ISO 9899; it is
==========
  		Gimpel Software
  		3207 Hogarth Lane
  		Collegeville, PA  19426  USA
< 		(+1) 215 584 4261
---
> 		(+1) 610 584 4261
> 		gimpel@netaxs.com
==========
> 	Another ANSI-compatible lint (which can also perform higher-
> 	level formal verification) is LCLint, available via anonymous
> 	ftp from larch.lcs.mit.edu://pub/Larch/lclint/ .
==========
< This article is Copyright 1988, 1990-1994 by Steve Summit.
---
> This article is Copyright 1988, 1990-1995 by Steve Summit.
==========

					Steve Summit
					scs@eskimo.com

From csus.edu!news.ucdavis.edu!agate!tcsi.tcs.com!uunet!eskimo!scs Thu Apr  6 20:27:13 1995
Newsgroups: comp.lang.c,comp.answers,news.answers
From: scs@eskimo.com (Steve Summit)
Subject: comp.lang.c Answers to Frequently Asked Questions (FAQ List)
X-Nntp-Posting-Host: eskimo.com
Message-ID: <1995Apr01.1511.scs.0002@eskimo.com>
Followup-To: poster
Originator: scs@eskimo.com
Sender: usenet@eskimo.com (News User Id)
Supersedes: <1995Mar01.0302.scs.0001@eskimo.com>
Reply-To: scs@eskimo.com
X-Pgp-Signature: Version: 2.6
	iQCSAwUBL33Tvt6sm4I1rmP1AQF+MgPoq92JkOXhIk59yt4ZGJbMHzLw+zJYneZ1
	AQ3umcMa5hvRooJ6xI5KinxzbnEvfupEO2Mb0EHln9/RAXegiJQblMQPVtvPWJXj
	/qS7c9UV7zshbyAhoJTC+sxrInS09UOLhQmNr9eLbJxbaNaeq8vVdtY42xOMX4eu
	LWmTsMo=
	=ReLk
X-Archive-Name: C-faq/faq
Organization: only when absolutely necessary
X-Version: 2.4
Date: Sat, 1 Apr 1995 23:12:24 GMT
X-Last-Modified: April 1, 1995
Approved: news-answers-request@MIT.Edu
Expires: Wed, 3 May 1995 00:00:00 GMT
Lines: 3835
Xref: csus.edu comp.lang.c:102221 comp.answers:10964 news.answers:41075

Archive-name: C-faq/faq
Comp-lang-c-archive-name: C-FAQ-list

[Last modified April 1, 1995 by scs.]

Certain topics come up again and again on this newsgroup.  They are good
questions, and the answers may not be immediately obvious, but each time
they recur, much net bandwidth and reader time is wasted on repetitive
responses, and on tedious corrections to the incorrect answers which are
inevitably posted.

This article, which is posted monthly, attempts to answer these common
questions definitively and succinctly, so that net discussion can move
on to more constructive topics without continual regression to first
principles.

No mere newsgroup article can substitute for thoughtful perusal of a
full-length tutorial or language reference manual.  Anyone interested
enough in C to be following this newsgroup should also be interested
enough to read and study one or more such manuals, preferably several
times.  Some C books and compiler manuals are unfortunately inadequate;
a few even perpetuate some of the myths which this article attempts to
refute.  Several noteworthy books on C are listed in this article's
bibliography.  Many of the questions and answers are cross-referenced to
these books, for further study by the interested and dedicated reader
(but beware of ANSI vs. ISO C Standard section numbers; see question
5.1).

If you have a question about C which is not answered in this article,
first try to answer it by checking a few of the referenced books, or by
asking knowledgeable colleagues, before posing your question to the net
at large.  There are many people on the net who are happy to answer
questions, but the volume of repetitive answers posted to one question,
as well as the growing number of questions as the net attracts more
readers, can become oppressive.  If you have questions or comments
prompted by this article, please reply by mail rather than following up
-- this article is meant to decrease net traffic, not increase it.

Besides listing frequently-asked questions, this article also summarizes
frequently-posted answers.  Even if you know all the answers, it's worth
skimming through this list once in a while, so that when you see one of
its questions unwittingly posted, you won't have to waste time
answering.

This article was last modified on April 1, 1995, and its travels may
have taken it far from its original home on Usenet.  It may now be
out-of-date, particularly if you are looking at a printed copy or one
retrieved from a tertiary archive site or CD-ROM.  You can always obtain
the most up-to-date copy by anonymous ftp from sites ftp.eskimo.com,
rtfm.mit.edu, or ftp.uu.net (see questions 17.12 and 17.33), or by
sending the e-mail message "help" to mail-server@rtfm.mit.edu .
(Also, this article was produced for free redistribution.
You should not need to pay anyone for a copy of it.)

Other versions of this document are also available.  Posted along with
it are an abridged version and (when there are changes) a list of
differences with respect to the previous version.  A few preliminary
hypertext versions are available on the world-wide web (WWW); see URL's
<http://www.cis.ohio-state.edu/hypertext/faq/usenet/FAQ-List.html> and
<http://www.lysator.liu.se/c/c-faq/index.html>.  Finally, for those who
might prefer a bound, hardcopy version (and even longer answers to even
more questions!), a book-length version will be published by
Addison-Wesley in Fall of 1995 (ISBN 0-201-84519-9).

This article is always being improved.  Your input is welcomed.  Send
your comments to scs@eskimo.com .

The questions answered here are divided into several categories:

	 1. Null Pointers
	 2. Arrays and Pointers
	 3. Memory Allocation
	 4. Expressions
	 5. ANSI C
	 6. C Preprocessor
	 7. Variable-Length Argument Lists
	 8. Boolean Expressions and Variables
	 9. Structs, Enums, and Unions
	10. Declarations
	11. Stdio
	12. Library Subroutines
	13. Lint
	14. Style
	15. Floating Point
	16. System Dependencies
	17. Miscellaneous (Fortran to C converters, YACC grammars, etc.)

Herewith, some frequently-asked questions and their answers:


Section 1. Null Pointers

1.1:	What is this infamous null pointer, anyway?

A:	The language definition states that for each pointer type, there
	is a special value -- the "null pointer" -- which is
	distinguishable from all other pointer values and which is not
	the address of any object or function.  That is, the address-of
	operator & will never yield a null pointer, nor will a
	successful call to malloc.  (malloc returns a null pointer when
	it fails, and this is a typical use of null pointers: as a
	"special" pointer value with some other meaning, usually "not
	allocated" or "not pointing anywhere yet.")

	A null pointer is conceptually different from an uninitialized
	pointer.  A null pointer is known not to point to any object; an
	uninitialized pointer might point anywhere.  See also questions
	3.1, 3.13, and 17.1.

	As mentioned in the definition above, there is a null pointer
	for each pointer type, and the internal values of null pointers
	for different types may be different.  Although programmers need
	not know the internal values, the compiler must always be
	informed which type of null pointer is required, so it can make
	the distinction if necessary (see below).

	References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
	Sec. 5.3 p. 91; ANSI Sec. 3.2.2.3 p. 38.

1.2:	How do I "get" a null pointer in my programs?

A:	According to the language definition, a constant 0 in a pointer
	context is converted into a null pointer at compile time.  That
	is, in an initialization, assignment, or comparison when one
	side is a variable or expression of pointer type, the compiler
	can tell that a constant 0 on the other side requests a null
	pointer, and generate the correctly-typed null pointer value.
	Therefore, the following fragments are perfectly legal:

		char *p = 0;
		if(p != 0)

	However, an argument being passed to a function is not
	necessarily recognizable as a pointer context, and the compiler
	may not be able to tell that an unadorned 0 "means" a null
	pointer.  For instance, the Unix system call "execl" takes a
	variable-length, null-pointer-terminated list of character
	pointer arguments.  To generate a null pointer in a function
	call context, an explicit cast is typically required, to force
	the 0 to be in a pointer context:

		execl("/bin/sh", "sh", "-c", "ls", (char *)0);

	If the (char *) cast were omitted, the compiler would not know
	to pass a null pointer, and would pass an integer 0 instead.
	(Note that many Unix manuals get this example wrong.)

	When function prototypes are in scope, argument passing becomes
	an "assignment context," and most casts may safely be omitted,
	since the prototype tells the compiler that a pointer is
	required, and of which type, enabling it to correctly convert
	unadorned 0's.  Function prototypes cannot provide the types for
	variable arguments in variable-length argument lists, however,
	so explicit casts are still required for those arguments.  It is
	safest always to cast null pointer function arguments, to guard
	against varargs functions or those without prototypes, to allow
	interim use of non-ANSI compilers, and to demonstrate that you
	know what you are doing.  (Incidentally, it's also a simpler
	rule to remember.)

	Summary:

		Unadorned 0 okay:	Explicit cast required:

		initialization		function call,
					no prototype in scope
		assignment
					variable argument in
		comparison		varargs function call

		function call,
		prototype in scope,
		fixed argument

	References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II
	Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI
	Sec. 3.2.2.3 .

1.3:	What is NULL and how is it #defined?

A:	As a matter of style, many people prefer not to have unadorned
	0's scattered throughout their programs.  For this reason, the
	preprocessor macro NULL is #defined (by <stdio.h> or
	<stddef.h>), with value 0 (or (void *)0, about which more
	later).  A programmer who wishes to make explicit the
	distinction between 0 the integer and 0 the null pointer can
	then use NULL whenever a null pointer is required.  This is a
	stylistic convention only; the preprocessor turns NULL back to 0
	which is then recognized by the compiler (in pointer contexts)
	as before.  In particular, a cast may still be necessary before
	NULL (as before 0) in a function call argument.  (The table
	under question 1.2 above applies for NULL as well as 0.)

	NULL should _only_ be used for pointers; see question 1.8.

	References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
	Sec. 13.1 p. 283; ANSI Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38,
	Rationale Sec. 4.1.5 p. 74.

1.4:	How should NULL be #defined on a machine which uses a nonzero
	bit pattern as the internal representation of a null pointer?

A:	Programmers should never need to know the internal
	representation(s) of null pointers, because they are normally
	taken care of by the compiler.  If a machine uses a nonzero bit
	pattern for null pointers, it is the compiler's responsibility
	to generate it when the programmer requests, by writing "0" or
	"NULL," a null pointer.  Therefore, #defining NULL as 0 on a
	machine for which internal null pointers are nonzero is as valid
	as on any other, because the compiler must (and can) still
	generate the machine's correct null pointers in response to
	unadorned 0's seen in pointer contexts.

1.5:	If NULL were defined as follows:

		#define NULL ((char *)0)

	wouldn't that make function calls which pass an uncast NULL
	work?

A:	Not in general.  The problem is that there are machines which
	use different internal representations for pointers to different
	types of data.  The suggested #definition would make uncast NULL
	arguments to functions expecting pointers to characters to work
	correctly, but pointer arguments to other types would still be
	problematical, and legal constructions such as

		FILE *fp = NULL;

	could fail.

	Nevertheless, ANSI C allows the alternate

		#define NULL ((void *)0)

	definition for NULL.  Besides helping incorrect programs to work
	(but only on machines with homogeneous pointers, thus
	questionably valid assistance) this definition may catch
	programs which use NULL incorrectly (e.g. when the ASCII  NUL
	character was really intended; see question 1.8).

	References: ANSI Rationale Sec. 4.1.5 p. 74.

1.6:	I use the preprocessor macro

		#define Nullptr(type) (type *)0

	to help me build null pointers of the correct type.

A:	This trick, though popular in some circles, does not buy much.
	It is not needed in assignments and comparisons; see question
	1.2.  It does not even save keystrokes.  Its use suggests to the
	reader that the author is shaky on the subject of null pointers,
	and requires the reader to check the #definition of the macro,
	its invocations, and _all_ other pointer usages much more
	carefully.  See also question 8.1.

1.7:	Is the abbreviated pointer comparison "if(p)" to test for non-
	null pointers valid?  What if the internal representation for
	null pointers is nonzero?

A:	When C requires the boolean value of an expression (in the if,
	while, for, and do statements, and with the &&, ||, !, and ?:
	operators), a false value is produced when the expression
	compares equal to zero, and a true value otherwise.  That is,
	whenever one writes

		if(expr)

	where "expr" is any expression at all, the compiler essentially
	acts as if it had been written as

		if(expr != 0)

	Substituting the trivial pointer expression "p" for "expr," we
	have

		if(p)	is equivalent to		if(p != 0)

	and this is a comparison context, so the compiler can tell that
	the (implicit) 0 is a null pointer, and use the correct value.
	There is no trickery involved here; compilers do work this way,
	and generate identical code for both statements.  The internal
	representation of a pointer does _not_ matter.

	The boolean negation operator, !, can be described as follows:

		!expr	is essentially equivalent to	expr?0:1

	It is left as an exercise for the reader to show that

		if(!p)	is equivalent to		if(p == 0)

	"Abbreviations" such as if(p), though perfectly legal, are
	considered by some to be bad style.

	See also question 8.2.

	References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI
	Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and
	3.6.5 .

1.8:	If "NULL" and "0" are equivalent, which should I use?

A:	Many programmers believe that "NULL" should be used in all
	pointer contexts, as a reminder that the value is to be thought
	of as a pointer.  Others feel that the confusion surrounding
	"NULL" and "0" is only compounded by hiding "0" behind a
	#definition, and prefer to use unadorned "0" instead.  There is
	no one right answer.  C programmers must understand that "NULL"
	and "0" are interchangeable and that an uncast "0" is perfectly
	acceptable in initialization, assignment, and comparison
	contexts.  Any usage of "NULL" (as opposed to "0") should be
	considered a gentle reminder that a pointer is involved;
	programmers should not depend on it (either for their own
	understanding or the compiler's) for distinguishing pointer 0's
	from integer 0's.

	NULL should _not_ be used when another kind of 0 is required,
	even though it might work, because doing so sends the wrong
	stylistic message.  (ANSI allows the #definition of NULL to be
	(void *)0, which will not work in non-pointer contexts.)  In
	particular, do not use NULL when the ASCII null character (NUL)
	is desired.  Provide your own definition

		#define NUL '\0'

	if you must.

	References: K&R II Sec. 5.4 p. 102.

1.9:	But wouldn't it be better to use NULL (rather than 0) in case
	the value of NULL changes, perhaps on a machine with nonzero
	null pointers?

A:	No.  Although symbolic constants are often used in place of
	numbers because the numbers might change, this is _not_ the
	reason that NULL is used in place of 0.  Once again, the
	language guarantees that source-code 0's (in pointer contexts)
	generate null pointers.  NULL is used only as a stylistic
	convention.

1.10:	I'm confused.  NULL is guaranteed to be 0, but the null pointer
	is not?

A:	When the term "null" or "NULL" is casually used, one of several
	things may be meant:

	1.	The conceptual null pointer, the abstract language
		concept defined in question 1.1.  It is implemented
		with...

	2.	The internal (or run-time) representation of a null
		pointer, which may or may not be all-bits-0 and which
		may be different for different pointer types.  The
		actual values should be of concern only to compiler
		writers.  Authors of C programs never see them, since
		they use...

	3.	The source code syntax for null pointers, which is the
		single character "0".  It is often hidden behind...

	4.	The NULL macro, which is #defined to be "0" or
		"(void *)0".  Finally, as red herrings, we have...

	5.	The ASCII null character (NUL), which does have all bits
		zero, but has no necessary relation to the null pointer
		except in name; and...

	6.	The "null string," which is another name for an empty
		string ("").  The term "null string" can be confusing in
		C (and should perhaps be avoided), because it involves a
		null ('\0') character, but not a null pointer, which
		brings us full circle...

	This article always uses the phrase "null pointer" (in lower
	case) for sense 1, the character "0" for sense 3, and the
	capitalized word "NULL" for sense 4.

1.11:	Why is there so much confusion surrounding null pointers?  Why
	do these questions come up so often?

A:	C programmers traditionally like to know more than they need to
	about the underlying machine implementation.  The fact that null
	pointers are represented both in source code, and internally to
	most machines, as zero invites unwarranted assumptions.  The use
	of a preprocessor macro (NULL) suggests that the value might
	change later, or on some weird machine.  The construct
	"if(p == 0)" is easily misread as calling for conversion of p to
	an integral type, rather than 0 to a pointer type, before the
	comparison.  Finally, the distinction between the several uses
	of the term "null" (listed above) is often overlooked.

	One good way to wade out of the confusion is to imagine that C
	had a keyword (perhaps "nil", like Pascal) with which null
	pointers were requested.  The compiler could either turn "nil"
	into the correct type of null pointer, when it could determine
	the type from the source code, or complain when it could not.
	Now, in fact, in C the keyword for a null pointer is not "nil"
	but "0", which works almost as well, except that an uncast "0"
	in a non-pointer context generates an integer zero instead of an
	error message, and if that uncast 0 was supposed to be a null
	pointer, the code may not work.

1.12:	I'm still confused.  I just can't understand all this null
	pointer stuff.

A:	Follow these two simple rules:

	1.	When you want to refer to a null pointer in source code,
		use "0" or "NULL".

	2.	If the usage of "0" or "NULL" is an argument in a
		function call, cast it to the pointer type expected by
		the function being called.

	The rest of the discussion has to do with other people's
	misunderstandings, or with the internal representation of null
	pointers (which you shouldn't need to know), or with ANSI C
	refinements.  Understand questions 1.1, 1.2, and 1.3, and
	consider 1.8 and 1.11, and you'll do fine.

1.13:	Given all the confusion surrounding null pointers, wouldn't it
	be easier simply to require them to be represented internally by
	zeroes?

A:	If for no other reason, doing so would be ill-advised because it
	would unnecessarily constrain implementations which would
	otherwise naturally represent null pointers by special, nonzero
	bit patterns, particularly when those values would trigger
	automatic hardware traps for invalid accesses.

	Besides, what would this requirement really accomplish?  Proper
	understanding of null pointers does not require knowledge of the
	internal representation, whether zero or nonzero.  Assuming that
	null pointers are internally zero does not make any code easier
	to write (except for a certain ill-advised usage of calloc; see
	question 3.13).  Known-zero internal pointers would not obviate
	casts in function calls, because the _size_ of the pointer might
	still be different from that of an int.  (If "nil" were used to
	request null pointers rather than "0," as mentioned in question
	1.11, the urge to assume an internal zero representation would
	not even arise.)

1.14:	Seriously, have any actual machines really used nonzero null
	pointers, or different representations for pointers to different
	types?

A:	The Prime 50 series used segment 07777, offset 0 for the null
	pointer, at least for PL/I.  Later models used segment 0, offset
	0 for null pointers in C, necessitating new instructions such as
	TCNP (Test C Null Pointer), evidently as a sop to all the extant
	poorly-written C code which made incorrect assumptions.  Older,
	word-addressed Prime machines were also notorious for requiring
	larger byte pointers (char *'s) than word pointers (int *'s).

	The Eclipse MV series from Data General has three
	architecturally supported pointer formats (word, byte, and bit
	pointers), two of which are used by C compilers: byte pointers
	for char * and void *, and word pointers for everything else.

	Some Honeywell-Bull mainframes use the bit pattern 06000 for
	(internal) null pointers.

	The CDC Cyber 180 Series has 48-bit pointers consisting of a
	ring, segment, and offset.  Most users (in ring 11) have null
	pointers of 0xB00000000000.

	The Symbolics Lisp Machine, a tagged architecture, does not even
	have conventional numeric pointers; it uses the pair <NIL, 0>
	(basically a nonexistent <object, offset> handle) as a C null
	pointer.

	Depending on the "memory model" in use, 80*86 processors (PC's)
	may use 16 bit data pointers and 32 bit function pointers, or
	vice versa.

	The old HP 3000 series computers use a different addressing
	scheme for byte addresses than for word addresses; void and char
	pointers therefore have a different representation than an int
	(structure, etc.) pointer to the same address would have.

1.15:	What does a run-time "null pointer assignment" error mean?  How
	do I track it down?

A:	This message, which occurs only under MS-DOS (see, therefore,
	section 16) means that you've written, via an unintialized
	and/or null pointer, to location zero.

	A debugger will usually let you set a data breakpoint on
	location 0.  Alternately, you could write a bit of code to copy
	20 or so bytes from location 0 into another buffer, and
	periodically check that it hasn't changed.


Section 2. Arrays and Pointers

2.1:	I had the definition char a[6] in one source file, and in
	another I declared extern char *a.  Why didn't it work?

A:	The declaration extern char *a simply does not match the actual
	definition.  The type "pointer-to-type-T" is not the same as
	"array-of-type-T."  Use extern char a[].

	References: CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5.

2.2:	But I heard that char a[] was identical to char *a.

A:	Not at all.  (What you heard has to do with formal parameters to
	functions; see question 2.4.)  Arrays are not pointers.  The
	array declaration "char a[6];" requests that space for six
	characters be set aside, to be known by the name "a."  That is,
	there is a location named "a" at which six characters can sit.
	The pointer declaration "char *p;" on the other hand, requests a
	place which holds a pointer.  The pointer is to be known by the
	name "p," and can point to any char (or contiguous array of
	chars) anywhere.

	As usual, a picture is worth a thousand words.  The statements

		char a[] = "hello";
		char *p = "world";

	would result in data structures which could be represented like
	this:

		   +---+---+---+---+---+---+
		a: | h | e | l | l | o |\0 |
		   +---+---+---+---+---+---+

		   +-----+     +---+---+---+---+---+---+
		p: |  *======> | w | o | r | l | d |\0 |
		   +-----+     +---+---+---+---+---+---+

	It is important to realize that a reference like x[3] generates
	different code depending on whether x is an array or a pointer.
	Given the declarations above, when the compiler sees the
	expression a[3], it emits code to start at the location "a,"
	move three past it, and fetch the character there.  When it sees
	the expression p[3], it emits code to start at the location "p,"
	fetch the pointer value there, add three to the pointer, and
	finally fetch the character pointed to.  In the example above,
	both a[3] and p[3] happen to be the character 'l', but the
	compiler gets there differently.  (See also questions 17.19 and
	17.20.)

2.3:	So what is meant by the "equivalence of pointers and arrays" in
	C?

A:	Much of the confusion surrounding pointers in C can be traced to
	a misunderstanding of this statement.  Saying that arrays and
	pointers are "equivalent" neither means that they are identical
	nor even interchangeable.

	"Equivalence" refers to the following key definition:

		An lvalue [see question 2.5] of type array-of-T
		which appears in an expression decays (with
		three exceptions) into a pointer to its first
		element; the type of the resultant pointer is
		pointer-to-T.

	(The exceptions are when the array is the operand of a sizeof or
	& operator, or is a literal string initializer for a character
	array.)

	As a consequence of this definition, there is no apparent
	difference in the behavior of the "array subscripting" operator
	[] as it applies to arrays and pointers.  In an expression of
	the form a[i], the array reference "a" decays into a pointer,
	following the rule above, and is then subscripted just as would
	be a pointer variable in the expression p[i] (although the
	eventual memory accesses will be different, as explained in
	question 2.2).  In either case, the expression x[i] (where x is
	an array or a pointer) is, by definition, identical to
	*((x)+(i)).

	References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S
	Sec. 5.4.1 p. 93; ANSI Sec. 3.2.2.1, Sec. 3.3.2.1, Sec. 3.3.6 .

2.4:	Then why are array and pointer declarations interchangeable as
	function formal parameters?

A:	Since arrays decay immediately into pointers, an array is never
	actually passed to a function.  As a convenience, any parameter
	declarations which "look like" arrays, e.g.

		f(a)
		char a[];

	are treated by the compiler as if they were pointers, since that
	is what the function will receive if an array is passed:

		f(a)
		char *a;

	This conversion holds only within function formal parameter
	declarations, nowhere else.  If this conversion bothers you,
	avoid it; many people have concluded that the confusion it
	causes outweighs the small advantage of having the declaration
	"look like" the call and/or the uses within the function.

	References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II
	Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S
	Sec. 5.4.3 p. 96; ANSI Sec. 3.5.4.3, Sec. 3.7.1, CT&P Sec. 3.3
	pp. 33-4.

2.5:	How can an array be an lvalue, if you can't assign to it?

A:	The ANSI C Standard defines a "modifiable lvalue," which an
	array is not.

	References: ANSI Sec. 3.2.2.1 p. 37.

2.6:	Why doesn't sizeof properly report the size of an array which is
	a parameter to a function?

A:	The sizeof operator reports the size of the pointer parameter
	which the function actually receives (see question 2.4).

2.7:	Someone explained to me that arrays were really just constant
	pointers.

A:	This is a bit of an oversimplification.  An array name is
	"constant" in that it cannot be assigned to, but an array is
	_not_ a pointer, as the discussion and pictures in question 2.2
	should make clear.

2.8:	Practically speaking, what is the difference between arrays and
	pointers?

A:	Arrays automatically allocate space, but can't be relocated or
	resized.  Pointers must be explicitly assigned to point to
	allocated space (perhaps using malloc), but can be reassigned
	(i.e. pointed at different objects) at will, and have many other
	uses besides serving as the base of blocks of memory.

	Due to the so-called equivalence of arrays and pointers (see
	question 2.3), arrays and pointers often seem interchangeable,
	and in particular a pointer to a block of memory assigned by
	malloc is frequently treated (and can be referenced using []
	exactly) as if it were a true array.  (See question 2.14; see
	also question 17.20.)

2.9:	I came across some "joke" code containing the "expression"
	5["abcdef"] .  How can this be legal C?

A:	Yes, Virginia, array subscripting is commutative in C.  This
	curious fact follows from the pointer definition of array
	subscripting, namely that a[e] is identical to *((a)+(e)), for
	_any_ expression e and primary expression a, as long as one of
	them is a pointer expression and one is integral.  This
	unsuspected commutativity is often mentioned in C texts as if it
	were something to be proud of, but it finds no useful
	application outside of the Obfuscated C Contest (see question
	17.13).

	References: ANSI Rationale Sec. 3.3.2.1 p. 41.

2.10:	My compiler complained when I passed a two-dimensional array to
	a routine expecting a pointer to a pointer.

A:	The rule by which arrays decay into pointers is not applied
	recursively.  An array of arrays (i.e. a two-dimensional array
	in C) decays into a pointer to an array, not a pointer to a
	pointer.  Pointers to arrays can be confusing, and must be
	treated carefully.  (The confusion is heightened by the
	existence of incorrect compilers, including some versions of pcc
	and pcc-derived lint's, which improperly accept assignments of
	multi-dimensional arrays to multi-level pointers.)  If you are
	passing a two-dimensional array to a function:

		int array[NROWS][NCOLUMNS];
		f(array);

	the function's declaration should match:

		f(int a[][NCOLUMNS]) {...}
	or
		f(int (*ap)[NCOLUMNS]) {...}   /* ap is a pointer to an array */

	In the first declaration, the compiler performs the usual
	implicit parameter rewriting of "array of array" to "pointer to
	array;" in the second form the pointer declaration is explicit.
	Since the called function does not allocate space for the array,
	it does not need to know the overall size, so the number of
	"rows," NROWS, can be omitted.  The "shape" of the array is
	still important, so the "column" dimension NCOLUMNS (and, for 3-
	or more dimensional arrays, the intervening ones) must be
	included.

	If a function is already declared as accepting a pointer to a
	pointer, it is probably incorrect to pass a two-dimensional
	array directly to it.

	References: K&R I Sec. 5.10 p. 110; K&R II Sec. 5.9 p. 113.

2.11:	How do I write functions which accept 2-dimensional arrays when
	the "width" is not known at compile time?

A:	It's not easy.  One way is to pass in a pointer to the [0][0]
	element, along with the two dimensions, and simulate array
	subscripting "by hand:"

		f2(aryp, nrows, ncolumns)
		int *aryp;
		int nrows, ncolumns;
		{ ... ary[i][j] is really aryp[i * ncolumns + j] ... }

	This function could be called with the array from question 2.10
	as

		f2(&array[0][0], NROWS, NCOLUMNS);

	It must be noted, however, that a program which performs
	multidimensional array subscripting "by hand" in this way is not
	in strict conformance with the ANSI C Standard; the behavior of
	accessing (&array[0][0])[x] is not defined for x > NCOLUMNS.

	gcc allows local arrays to be declared having sizes which are
	specified by a function's arguments, but this is a nonstandard
	extension.

	See also question 2.15.

2.12:	How do I declare a pointer to an array?

A:	Usually, you don't want to.  When people speak casually of a
	pointer to an array, they usually mean a pointer to its first
	element.

	Instead of a pointer to an array, consider using a pointer to
	one of the array's elements.  Arrays of type T decay into
	pointers to type T (see question 2.3), which is convenient;
	subscripting or incrementing the resultant pointer accesses the
	individual members of the array.  True pointers to arrays, when
	subscripted or incremented, step over entire arrays, and are
	generally only useful when operating on arrays of arrays, if at
	all.  (See question 2.10 above.)

	If you really need to declare a pointer to an entire array, use
	something like "int (*ap)[N];" where N is the size of the array.
	(See also question 10.4.)  If the size of the array is unknown,
	N can be omitted, but the resulting type, "pointer to array of
	unknown size," is useless.

2.13:	Since array references decay to pointers, given

		int array[NROWS][NCOLUMNS];

	what's the difference between array and &array?

A:	Under ANSI/ISO Standard C, &array yields a pointer, of type
	pointer-to-array-of-T, to the entire array (see also question
	2.12).  Under pre-ANSI C, the & in &array generally elicited a
	warning, and was generally ignored.  Under all C compilers, an
	unadorned reference to an array yields a pointer, of type
	pointer-to-T, to the array's first element.  (See also question
	2.3.)

2.14:	How can I dynamically allocate a multidimensional array?

A:	It is usually best to allocate an array of pointers, and then
	initialize each pointer to a dynamically-allocated "row."  Here
	is a two-dimensional example:

		int **array1 = (int **)malloc(nrows * sizeof(int *));
		for(i = 0; i < nrows; i++)
			array1[i] = (int *)malloc(ncolumns * sizeof(int));

	(In "real" code, of course, malloc would be declared correctly,
	and each return value checked.)

	You can keep the array's contents contiguous, while making later
	reallocation of individual rows difficult, with a bit of
	explicit pointer arithmetic:

		int **array2 = (int **)malloc(nrows * sizeof(int *));
		array2[0] = (int *)malloc(nrows * ncolumns * sizeof(int));
		for(i = 1; i < nrows; i++)
			array2[i] = array2[0] + i * ncolumns;

	In either case, the elements of the dynamic array can be
	accessed with normal-looking array subscripts: array[i][j].

	If the double indirection implied by the above schemes is for
	some reason unacceptable, you can simulate a two-dimensional
	array with a single, dynamically-allocated one-dimensional
	array:

		int *array3 = (int *)malloc(nrows * ncolumns * sizeof(int));

	However, you must now perform subscript calculations manually,
	accessing the i,jth element with array3[i * ncolumns + j].  (A
	macro can hide the explicit calculation, but invoking it then
	requires parentheses and commas which don't look exactly like
	multidimensional array subscripts.)

	Finally, you can use pointers-to-arrays:

		int (*array4)[NCOLUMNS] =
			(int (*)[NCOLUMNS])malloc(nrows * sizeof(*array4));

	, but the syntax gets horrific and all but one dimension must be
	known at compile time.

	With all of these techniques, you may of course need to remember
	to free the arrays (which may take several steps; see question
	3.9) when they are no longer needed, and you cannot necessarily
	intermix the dynamically-allocated arrays with conventional,
	statically-allocated ones (see question 2.15 below, and also
	question 2.10).

2.15:	How can I use statically- and dynamically-allocated
	multidimensional arrays interchangeably when passing them to
	functions?

A:	There is no single perfect method.  Given the declarations

		int array[NROWS][NCOLUMNS];
		int **array1;
		int **array2;
		int *array3;
		int (*array4)[NCOLUMNS];

	as initialized in the code fragments in questions 2.10 and 2.14,
	and functions declared as

		f1(int a[][NCOLUMNS], int m, int n);
		f2(int *aryp, int nrows, int ncolumns);
		f3(int **pp, int m, int n);

	(see questions 2.10 and 2.11), the following calls should work
	as expected:

		f1(array, NROWS, NCOLUMNS);
		f1(array4, nrows, NCOLUMNS);
		f2(&array[0][0], NROWS, NCOLUMNS);
		f2(*array2, nrows, ncolumns);
		f2(array3, nrows, ncolumns);
		f2(*array4, nrows, NCOLUMNS);
		f3(array1, nrows, ncolumns);
		f3(array2, nrows, ncolumns);

	The following two calls would probably work, but involve
	questionable casts, and work only if the dynamic ncolumns
	matches the static NCOLUMNS:

		f1((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
		f1((int (*)[NCOLUMNS])array3, nrows, ncolumns);

	It must again be noted that passing &array[0][0] to f2() is not
	strictly conforming; see question 2.11.

	If you can understand why all of the above calls work and are
	written as they are, and if you understand why the combinations
	that are not listed would not work, then you have a _very_ good
	understanding of arrays and pointers (and several other areas)
	in C.

2.16:	Here's a neat trick: if I write

		int realarray[10];
		int *array = &realarray[-1];

	I can treat "array" as if it were a 1-based array.

A:	Although this technique is attractive (and was used in old
	editions of the book Numerical Recipes in C), it does not
	conform to the C standards.  Pointer arithmetic is defined only
	as long as the pointer points within the same allocated block of
	memory, or to the imaginary "terminating" element one past it;
	otherwise, the behavior is undefined, _even if the pointer is
	not dereferenced_.  The code above could fail if, while
	subtracting the offset, an illegal address were generated
	(perhaps because the address tried to "wrap around" past the
	beginning of some memory segment).

	References: ANSI Sec. 3.3.6 p. 48, Rationale Sec. 3.2.2.3 p. 38;
	K&R II Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7 pp. 205-6.

2.17:	I passed a pointer to a function which initialized it:

		...
		int *ip;
		f(ip);
		...

		void f(ip)
		int *ip;
		{
			static int dummy = 5;
			ip = &dummy;
		}

	, but the pointer in the caller was unchanged.

A:	Did the function try to initialize the pointer itself, or just
	what it pointed to?  Remember that arguments in C are passed by
	value.  The called function altered only the passed copy of the
	pointer.  You'll either want to pass the address of the pointer
	(the function will end up accepting a pointer-to-a-pointer), or
	have the function return the pointer.

2.18:	I have a char * pointer that happens to point to some ints, and
	I want to step it over them.  Why doesn't

		((int *)p)++;

	work?

A:	In C, a cast operator does not mean "pretend these bits have a
	different type, and treat them accordingly;" it is a conversion
	operator, and by definition it yields an rvalue, which cannot be
	assigned to, or incremented with ++.  (It is an anomaly in pcc-
	derived compilers, and an extension in gcc, that expressions
	such as the above are ever accepted.)  Say what you mean: use

		p = (char *)((int *)p + 1);

	, or simply

		p += sizeof(int);

	References: ANSI Sec. 3.3.4, Rationale Sec. 3.3.2.4 p. 43.

2.19:	Can I use a void ** pointer to pass a generic pointer to a
	function by reference?

A:	Not portably.  There is no generic pointer-to-pointer type in C.
	void * acts as a generic pointer only because conversions are
	applied automatically when other pointer types are assigned to
	and from void *'s; these conversions cannot be performed (the
	correct underlying pointer type is not known) if an attempt is
	made to indirect upon a void ** value which points at something
	other than a void *.


Section 3. Memory Allocation

3.1:	Why doesn't this fragment work?

		char *answer;
		printf("Type something:\n");
		gets(answer);
		printf("You typed \"%s\"\n", answer);

A:	The pointer variable "answer," which is handed to the gets
	function as the location into which the response should be
	stored, has not been set to point to any valid storage.  That
	is, we cannot say where the pointer "answer" points.  (Since
	local variables are not initialized, and typically contain
	garbage, it is not even guaranteed that "answer" starts out as a
	null pointer.  See question 17.1.)

	The simplest way to correct the question-asking program is to
	use a local array, instead of a pointer, and let the compiler
	worry about allocation:

		#include <string.h>

		char answer[100], *p;
		printf("Type something:\n");
		fgets(answer, sizeof(answer), stdin);
		if((p = strchr(answer, '\n')) != NULL)
			*p = '\0';
		printf("You typed \"%s\"\n", answer);

	Note that this example also uses fgets() instead of gets()
	(always a good idea; see question 11.6), allowing the size of
	the array to be specified, so that the end of the array will not
	be overwritten if the user types an overly-long line.
	(Unfortunately for this example, fgets() does not automatically
	delete the trailing \n, as gets() would.)  It would also be
	possible to use malloc() to allocate the answer buffer.

3.2:	I can't get strcat to work.  I tried

		char *s1 = "Hello, ";
		char *s2 = "world!";
		char *s3 = strcat(s1, s2);

	but I got strange results.

A:	Again, the problem is that space for the concatenated result is
	not properly allocated.  C does not provide an automatically-
	managed string type.  C compilers only allocate memory for
	objects explicitly mentioned in the source code (in the case of
	"strings," this includes character arrays and string literals).
	The programmer must arrange (explicitly) for sufficient space
	for the results of run-time operations such as string
	concatenation, typically by declaring arrays, or by calling
	malloc.  (See also question 17.20.)

	strcat performs no allocation; the second string is appended to
	the first one, in place.  Therefore, one fix would be to declare
	the first string as an array with sufficient space:

		char s1[20] = "Hello, ";

	Since strcat returns the value of its first argument (s1, in
	this case), the s3 variable is superfluous.

	References: CT&P Sec. 3.2 p. 32.

3.3:	But the man page for strcat says that it takes two char *'s as
	arguments.  How am I supposed to know to allocate things?

A:	In general, when using pointers you _always_ have to consider
	memory allocation, at least to make sure that the compiler is
	doing it for you.  If a library routine's documentation does not
	explicitly mention allocation, it is usually the caller's
	problem.

	The Synopsis section at the top of a Unix-style man page can be
	misleading.  The code fragments presented there are closer to
	the function definition used by the call's implementor than the
	invocation used by the caller.  In particular, many routines
	which accept pointers (e.g. to structs or strings), are usually
	called with the address of some object (a struct, or an array --
	see questions 2.3 and 2.4.)  Another common example is stat().

3.4:	I have a function that is supposed to return a string, but when
	it returns to its caller, the returned string is garbage.

A:	Make sure that the memory to which the function returns a
	pointer is correctly allocated.  The returned pointer should be
	to a statically-allocated buffer, or to a buffer passed in by
	the caller, or to memory obtained with malloc(), but _not_ to a
	local (auto) array.  In other words, never do something like

		char *f()
		{
			char buf[10];
			/* ... */
			return buf;
		}

	One fix (which is imperfect, especially if f() is called
	recursively, or if several of its return values are needed
	simultaneously) would to to declare the buffer as

			static char buf[10];

	See also question 17.5.

3.5:	Why does some code carefully cast the values returned by malloc
	to the pointer type being allocated?

A:	Before ANSI/ISO Standard C introduced the void * generic pointer
	type, these casts were typically required to silence warnings
	about assignment between incompatible pointer types.  (Under
	ANSI/ISO Standard C, these casts are not required.)

3.6:	You can't use dynamically-allocated memory after you free it,
	can you?

A:	No.  Some early documentation for malloc stated that the
	contents of freed memory was "left undisturbed;" this ill-
	advised guarantee was never universal and is not required by
	ANSI.

	Few programmers would use the contents of freed memory
	deliberately, but it is easy to do so accidentally.  Consider
	the following (correct) code for freeing a singly-linked list:

		struct list *listp, *nextp;
		for(listp = base; listp != NULL; listp = nextp) {
			nextp = listp->next;
			free((char *)listp);
		}

	and notice what would happen if the more-obvious loop iteration
	expression listp = listp->next were used, without the temporary
	nextp pointer.

	References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10
	p. 95.

3.7:	How does free() know how many bytes to free?

A:	The malloc/free package remembers the size of each block it
	allocates and returns, so it is not necessary to remind it of
	the size when freeing.

3.8:	So can I query the malloc package to find out how big an
	allocated block is?

A:	Not portably.

3.9:	I'm allocating structures which contain pointers to other
	dynamically-allocated objects.  When I free a structure, do I
	have to free each subsidiary pointer first?

A:	Yes.  In general, you must arrange that each pointer returned
	from malloc be individually passed to free, exactly once (if it
	is freed at all).

3.10:	I have a program which mallocs but then frees a lot of memory,
	but memory usage (as reported by ps) doesn't seem to go back
	down.

A:	Most implementations of malloc/free do not return freed memory
	to the operating system (if there is one), but merely make it
	available for future malloc calls within the same process.

3.11:	Must I free allocated memory before the program exits?

A:	You shouldn't have to.  A real operating system definitively
	reclaims all memory when a program exits.  Nevertheless, some
	personal computers are said not to reliably recover memory, and
	all that can be inferred from the ANSI/ISO C Standard is that it
	is a "quality of implementation issue."

	References: ANSI Sec. 4.10.3.2 .

3.12:	Is it legal to pass a null pointer as the first argument to
	realloc()?  Why would you want to?

A:	ANSI C sanctions this usage (and the related realloc(..., 0),
	which frees), but several earlier implementations do not support
	it, so it is not widely portable.  Passing an initially-null
	pointer to realloc can make it easier to write a self-starting
	incremental allocation algorithm.

	References: ANSI Sec. 4.10.3.4 .

3.13:	What is the difference between calloc and malloc?  Is it safe to
	use calloc's zero-fill guarantee for pointer and floating-point
	values?  Does free work on memory allocated with calloc, or do
	you need a cfree?

A:	calloc(m, n) is essentially equivalent to

		p = malloc(m * n);
		memset(p, 0, m * n);

	The zero fill is all-bits-zero, and does not therefore guarantee
	useful zero values for pointers (see section 1 of this list) or
	floating-point values.  free can (and should) be used to free
	the memory allocated by calloc.

	References: ANSI Secs. 4.10.3 to 4.10.3.2 .

3.14:	What is alloca and why is its use discouraged?

A:	alloca allocates memory which is automatically freed when the
	function which called alloca returns.  That is, memory allocated
	with alloca is local to a particular function's "stack frame" or
	context.

	alloca cannot be written portably, and is difficult to implement
	on machines without a stack.  Its use is problematical (and the
	obvious implementation on a stack-based machine fails) when its
	return value is passed directly to another function, as in
	fgets(alloca(100), 100, stdin).

	For these reasons, alloca cannot be used in programs which must
	be widely portable, no matter how useful it might be.

	References: ANSI Rationale Sec. 4.10.3 p. 102.


Section 4. Expressions

4.1:	Why doesn't this code:

		a[i] = i++;

	work?

A:	The subexpression i++ causes a side effect -- it modifies i's
	value -- which leads to undefined behavior if i is also
	referenced elsewhere in the same expression.  (Note that
	although the language in K&R suggests that the behavior of this
	expression is unspecified, the ANSI/ISO C Standard makes the
	stronger statement that it is undefined -- see question 5.23.)

	References: ANSI Sec. 3.3 p. 39.

4.2:	Under my compiler, the code

		int i = 7;
		printf("%d\n", i++ * i++);

	prints 49.  Regardless of the order of evaluation, shouldn't it
	print 56?

A:	Although the postincrement and postdecrement operators ++ and --
	perform the operations after yielding the former value, the
	implication of "after" is often misunderstood.  It is _not_
	guaranteed that the operation is performed immediately after
	giving up the previous value and before any other part of the
	expression is evaluated.  It is merely guaranteed that the
	update will be performed sometime before the expression is
	considered "finished" (before the next "sequence point," in ANSI
	C's terminology).  In the example, the compiler chose to
	multiply the previous value by itself and to perform both
	increments afterwards.

	The behavior of code which contains multiple, ambiguous side
	effects has always been undefined (see question 5.23).  Don't
	even try to find out how your compiler implements such things
	(contrary to the ill-advised exercises in many C textbooks); as
	K&R wisely point out, "if you don't know _how_ they are done on
	various machines, that innocence may help to protect you."

	References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI
	Sec. 3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1.
	(Ignore H&S Sec. 7.12 pp. 190-1, which is obsolete.)

4.3:	I've experimented with the code

		int i = 2;
		i = i++;

	on several compilers.  Some gave i the value 2, some gave 3, but
	one gave 4.  I know the behavior is undefined, but how could it
	give 4?

A:	Undefined behavior means _anything_ can happen.  See question
	5.23.

4.4:	People keep saying the behavior is undefined, but I just tried
	it on an ANSI-conforming compiler, and got the results I
	expected.

A:	A compiler may do anything it likes when faced with undefined
	behavior (and, within limits, with implementation-defined and
	unspecified behavior), including doing what you expect.  It's
	unwise to depend on it, though.  See also question 5.18.

4.5:	Can I use explicit parentheses to force the order of evaluation
	I want?  Even if I don't, doesn't precedence dictate it?

A:	Operator precedence and explicit parentheses impose only a
	partial ordering on the evaluation of an expression.  Consider
	the expression

		f() + g() * h()

	-- although we know that the multiplication will happen before
	the addition, there is no telling which of the three functions
	will be called first.

4.6:	But what about the &&, ||, and comma operators?
	I see code like "if((c = getchar()) == EOF || c == '\n')" ...

A:	There is a special exception for those operators, (as well as
	the ?: operator); each of them does imply a sequence point (i.e.
	left-to-right evaluation is guaranteed).  Any book on C should
	make this clear.

	References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1;
	K&R II Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI
	Secs. 3.3.13 p. 52, 3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55,
	CT&P Sec. 3.7 pp. 46-7.

4.7:	If I'm not using the value of the expression, should I use i++
	or ++i to increment a variable?

A:	Since the two forms differ only in the value yielded, they are
	entirely equivalent when only their side effect is needed.

4.8:	Why doesn't the code

		int a = 1000, b = 1000;
		long int c = a * b;

	work?

A:	Under C's integral promotion rules, the multiplication is
	carried out using int arithmetic, and the result may overflow
	and/or be truncated before being assigned to the long int left-
	hand-side.  Use an explicit cast to force long arithmetic:

		long int c = (long int)a * b;

	Note that the code (long int)(a * b) would _not_ have the
	desired effect.


Section 5. ANSI C

5.1:	What is the "ANSI C Standard?"

A:	In 1983, the American National Standards Institute (ANSI)
	commissioned a committee, X3J11, to standardize the C language.
	After a long, arduous process, including several widespread
	public reviews, the committee's work was finally ratified as ANS
	X3.159-1989, on December 14, 1989, and published in the spring
	of 1990.  For the most part, ANSI C standardizes existing
	practice, with a few additions from C++ (most notably function
	prototypes) and support for multinational character sets
	(including the much-lambasted trigraph sequences).  The ANSI C
	standard also formalizes the C run-time library support
	routines.

	The published Standard includes a "Rationale," which explains
	many of its decisions, and discusses a number of subtle points,
	including several of those covered here.  (The Rationale is "not
	part of ANSI Standard X3.159-1989, but is included for
	information only.")

	The Standard has been adopted as an international standard,
	ISO/IEC 9899:1990, although the sections are numbered
	differently (briefly, ANSI sections 2 through 4 correspond
	roughly to ISO sections 5 through 7), and the Rationale is
	currently not included.

5.2:	How can I get a copy of the Standard?

A:	ANSI X3.159 has been officially superseded by ISO 9899.  Copies
	are available in the United States from

		American National Standards Institute
		11 W. 42nd St., 13th floor
		New York, NY  10036  USA
		(+1) 212 642 4900

	or

		Global Engineering Documents
		2805 McGaw Avenue
		Irvine, CA  92714  USA
		(+1) 714 261 1455
		(800) 854 7179  (U.S. & Canada)

	In other countries, contact the appropriate national standards
	body, or ISO in Geneva at:

		ISO Sales
		Case Postale 56
		CH-1211 Geneve 20
		Switzerland

	The cost is $130.00 from ANSI or $162.50 from Global.  Copies of
	the original X3.159 (including the Rationale) are still
	available at $205.00 from ANSI or $200.50 from Global.  Note
	that ANSI derives revenues to support its operations from the
	sale of printed standards, so electronic copies are _not_
	available.

	The mistitled _Annotated ANSI C Standard_, with annotations by
	Herbert Schildt, contains all but a few pages of ISO 9899; it is
	published by Osborne/McGraw-Hill, ISBN 0-07-881952-0, and sells
	in the U.S. for approximately $40.  (It has been suggested that
	the price differential between this work and the official
	standard reflects the value of the annotations.)

	The text of the Rationale (not the full Standard) is now
	available for anonymous ftp from ftp.uu.net (see question 17.12)
	in directory doc/standards/ansi/X3.159-1989 .  The Rationale has
	also been printed by Silicon Press, ISBN 0-929306-07-4.

5.3:	Does anyone have a tool for converting old-style C programs to
	ANSI C, or vice versa, or for automatically generating
	prototypes?

A:	Two programs, protoize and unprotoize, convert back and forth
	between prototyped and "old style" function definitions and
	declarations.  (These programs do _not_ handle full-blown
	translation between "Classic" C and ANSI C.)  These programs
	were once patches to the FSF GNU C compiler, gcc, but are now
	part of the main gcc distribution; look in pub/gnu at
	prep.ai.mit.edu (18.71.0.38), or at several other FSF archive
	sites.

	The unproto program (/pub/unix/unproto5.shar.Z on
	ftp.win.tue.nl) is a filter which sits between the preprocessor
	and the next compiler pass, converting most of ANSI C to
	traditional C on-the-fly.

	The GNU GhostScript package comes with a little program called
	ansi2knr.

	Several prototype generators exist, many as modifications to
	lint.  Version 3 of CPROTO was posted to comp.sources.misc in
	March, 1992.  There is another program called "cextract."  See
	also question 17.12.

	Finally, are you sure you really need to convert lots of old
	code to ANSI C?  The old-style function syntax is still
	acceptable.

5.4:	I'm trying to use the ANSI "stringizing" preprocessing operator
	# to insert the value of a symbolic constant into a message, but
	it keeps stringizing the macro's name rather than its value.

A:	You must use something like the following two-step procedure to
	force the macro to be expanded as well as stringized:

		#define str(x) #x
		#define xstr(x) str(x)
		#define OP plus
		char *opname = xstr(OP);

	This sets opname to "plus" rather than "OP".

	An equivalent circumlocution is necessary with the token-pasting
	operator ## when the values (rather than the names) of two
	macros are to be concatenated.

	References: ANSI Sec. 3.8.3.2, Sec. 3.8.3.5 example p. 93.

5.5:	I don't understand why I can't use const values in initializers
	and array dimensions, as in

		const int n = 5;
		int a[n];

A:	The const qualifier really means "read-only;" an object so
	qualified is a normal run-time object which cannot (normally) be
	assigned to.  The value of a const-qualified object is therefore
	_not_ a constant expression in the full sense of the term.  (C
	is unlike C++ in this regard.)  When you need a true compile-
	time constant, use a preprocessor #define.

	References: ANSI Sec. 3.4 .

5.6:	What's the difference between "char const *p" and
	"char * const p"?

A:	"char const *p" is a pointer to a constant character (you can't
	change the character); "char * const p" is a constant pointer to
	a (variable) character (i.e. you can't change the pointer).
	(Read these "inside out" to understand them.  See question
	10.4.)

	References: ANSI Sec. 3.5.4.1 .

5.7:	Why can't I pass a char ** to a function which expects a
	const char **?

A:	You can use a pointer-to-T (for any type T) where a pointer-to-
	const-T is expected, but the rule (an explicit exception) which
	permits slight mismatches in qualified pointer types is not
	applied recursively, but only at the top level.

	You must use explicit casts (e.g. (const char **) in this case)
	when assigning (or passing) pointers which have qualifier
	mismatches at other than the first level of indirection.

	References: ANSI Sec. 3.1.2.6 p. 26, Sec. 3.3.16.1 p. 54,
	Sec. 3.5.3 p. 65.

5.8:	My ANSI compiler complains about a mismatch when it sees

		extern int func(float);

		int func(x)
		float x;
		{...

A:	You have mixed the new-style prototype declaration
	"extern int func(float);" with the old-style definition
	"int func(x) float x;".  It is usually safe to mix the two
	styles (see question 5.9), but not in this case.  Old C (and
	ANSI C, in the absence of prototypes, and in variable-length
	argument lists) "widens" certain arguments when they are passed
	to functions.  floats are promoted to double, and characters and
	short integers are promoted to ints.  (For old-style function
	definitions, the values are automatically converted back to the
	corresponding narrower types within the body of the called
	function, if they are declared that way there.)

	This problem can be fixed either by using new-style syntax
	consistently in the definition:

		int func(float x) { ... }

	or by changing the new-style prototype declaration to match the
	old-style definition:

		extern int func(double);

	(In this case, it would be clearest to change the old-style
	definition to use double as well, as long as the address of that
	parameter is not taken.)

	It may also be safer to avoid "narrow" (char, short int, and
	float) function arguments and return types.

	References: ANSI Sec. 3.3.2.2 .

5.9:	Can you mix old-style and new-style function syntax?

A:	Doing so is perfectly legal, as long as you're careful (see
	especially question 5.8).  Note however that old-style syntax is
	marked as obsolescent, and support for it may be removed some
	day.

	References: ANSI Secs. 3.7.1, 3.9.5 .

5.10:	Why does the declaration

		extern f(struct x {int s;} *p);

	give me an obscure warning message about "struct x introduced in
	prototype scope"?

A:	In a quirk of C's normal block scoping rules, a struct declared
	only within a prototype cannot be compatible with other structs
	declared in the same source file, nor can the struct tag be used
	later as you'd expect (it goes out of scope at the end of the
	prototype).

	To resolve the problem, precede the prototype with the vacuous-
	looking declaration

		struct x;

	, which will reserve a place at file scope for struct x's
	definition, which will be completed by the struct declaration
	within the prototype.

	References: ANSI Sec. 3.1.2.1 p. 21, Sec. 3.1.2.6 p. 26,
	Sec. 3.5.2.3 p. 63.

5.11:	I'm getting strange syntax errors inside code which I've
	#ifdeffed out.

A:	Under ANSI C, the text inside a "turned off" #if, #ifdef, or
	#ifndef must still consist of "valid preprocessing tokens."
	This means that there must be no unterminated comments or quotes
	(note particularly that an apostrophe within a contracted word
	could look like the beginning of a character constant), and no
	newlines inside quotes.  Therefore, natural-language comments
	and pseudocode should always be written between the "official"
	comment delimiters /* and */.  (But see also question 17.14, and
	6.7.)

	References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37.

5.12:	Can I declare main as void, to shut off these annoying "main
	returns no value" messages?  (I'm calling exit(), so main
	doesn't return.)

A:	No.  main must be declared as returning an int, and as taking
	either zero or two arguments (of the appropriate type).  If
	you're calling exit() but still getting warnings, you'll have to
	insert a redundant return statement (or use some kind of
	"notreached" directive, if available).

	Declaring a function as void does not merely silence warnings;
	it may also result in a different function call/return sequence,
	incompatible with what the caller (in main's case, the C run-
	time startup code) expects.

	References: ANSI Sec. 2.1.2.2.1 pp. 7-8.

5.13:	Is exit(status) truly equivalent to returning status from main?

A:	Formally, yes, although discrepancies arise under a few older,
	nonconforming systems, or if data local to main() might be needed
	during cleanup (due perhaps to a setbuf or atexit call), or if
	main() is called recursively.

	References: ANSI Sec. 2.1.2.2.3 p. 8.

5.14:	Why does the ANSI Standard not guarantee more than six monocase
	characters of external identifier significance?

A:	The problem is older linkers which are neither under the control
	of the ANSI standard nor the C compiler developers on the
	systems which have them.  The limitation is only that
	identifiers be _significant_ in the first six characters, not
	that they be restricted to six characters in length.  This
	limitation is annoying, but certainly not unbearable, and is
	marked in the Standard as "obsolescent," i.e. a future revision
	will likely relax it.

	This concession to current, restrictive linkers really had to be
	made, no matter how vehemently some people oppose it.  (The
	Rationale notes that its retention was "most painful.")  If you
	disagree, or have thought of a trick by which a compiler
	burdened with a restrictive linker could present the C
	programmer with the appearance of more significance in external
	identifiers, read the excellently-worded section 3.1.2 in the
	X3.159 Rationale (see question 5.1), which discusses several
	such schemes and explains why they could not be mandated.

	References: ANSI Sec. 3.1.2 p. 21, Sec. 3.9.1 p. 96, Rationale
	Sec. 3.1.2 pp. 19-21.

5.15:	What is the difference between memcpy and memmove?

A:	memmove offers guaranteed behavior if the source and destination
	arguments overlap.  memcpy makes no such guarantee, and may
	therefore be more efficiently implementable.  When in doubt,
	it's safer to use memmove.

	References: ANSI Secs. 4.11.2.1, 4.11.2.2, Rationale
	Sec. 4.11.2 .

5.16:	My compiler is rejecting the simplest possible test programs,
	with all kinds of syntax errors.

A:	Perhaps it is a pre-ANSI compiler, unable to accept function
	prototypes and the like.  See also questions 5.17 and 17.2.

5.17:	Why are some ANSI/ISO Standard library routines showing up as
	undefined, even though I've got an ANSI compiler?

A:	It's not unusual to have a compiler available which accepts ANSI
	syntax, but not to have ANSI-compatible header files or run-time
	libraries installed.  See also questions 5.16 and 17.2.

5.18:	Why won't the Frobozz Magic C Compiler, which claims to be ANSI
	compliant, accept this code?  I know that the code is ANSI,
	because gcc accepts it.

A:	Most compilers support a few non-Standard extensions, gcc more
	so than most.  Are you sure that the code being rejected doesn't
	rely on such an extension?  It is usually a bad idea to perform
	experiments with a particular compiler to determine properties
	of a language; the applicable standard may permit variations, or
	the compiler may be wrong.  See also question 4.4.

5.19:	Why can't I perform arithmetic on a void * pointer?

A:	The compiler doesn't know the size of the pointed-to objects.
	Before performing arithmetic, cast the pointer either to char *
	or to the type you're trying to manipulate (but see question
	2.18).

5.20:	Is char a[3] = "abc"; legal?  What does it mean?

A:	It is legal in ANSI C (and perhaps in a few pre-ANSI systems),
	though questionably useful.  It declares an array of size three,
	initialized with the three characters 'a', 'b', and 'c', without
	the usual terminating '\0' character; the array is therefore not
	a true C string and cannot be used with strcpy, printf %s, etc.

	References: ANSI Sec. 3.5.7 pp. 72-3.

5.21:	What are #pragmas and what are they good for?

A:	The #pragma directive provides a single, well-defined "escape
	hatch" which can be used for all sorts of implementation-
	specific controls and extensions: source listing control,
	structure packing, warning suppression (like the old lint
	/* NOTREACHED */ comments), etc.

	References: ANSI Sec. 3.8.6 .

5.22:	What does "#pragma once" mean?  I found it in some header files.

A:	It is an extension implemented by some preprocessors to help
	make header files idempotent; it is essentially equivalent to
	the #ifndef trick mentioned in question 6.4.

5.23:	People seem to make a point of distinguishing between
	implementation-defined, unspecified, and undefined behavior.
	What's the difference?

A:	Briefly: implementation-defined means that an implementation
	must choose some behavior and document it.  Unspecified means
	that an implementation should choose some behavior, but need not
	document it.  Undefined means that absolutely anything might
	happen.  In no case does the Standard impose requirements; in
	the first two cases it occasionally suggests (and may require a
	choice from among) a small set of likely behaviors.

	If you're interested in writing portable code, you can ignore
	the distinctions, as you'll want to avoid code that depends on
	any of the three behaviors.

	References: ANSI Sec. 1.6, especially the Rationale.


Section 6. C Preprocessor

6.1:	How can I write a generic macro to swap two values?

A:	There is no good answer to this question.  If the values are
	integers, a well-known trick using exclusive-OR could perhaps be
	used, but it will not work for floating-point values or
	pointers, or if the two values are the same variable (and the
	"obvious" supercompressed implementation for integral types
	a^=b^=a^=b is in fact illegal due to multiple side-effects; see
	questions 4.1 and 4.2).  If the macro is intended to be used on
	values of arbitrary type (the usual goal), it cannot use a
	temporary, since it does not know what type of temporary it
	needs, and standard C does not provide a typeof operator.

	The best all-around solution is probably to forget about using a
	macro, unless you're willing to pass in the type as a third
	argument.

6.2:	I have some old code that tries to construct identifiers with a
	macro like

		#define Paste(a, b) a/**/b

	but it doesn't work any more.

A:	That comments disappeared entirely and could therefore be used
	for token pasting was an undocumented feature of some early
	preprocessor implementations, notably Reiser's.  ANSI affirms
	(as did K&R) that comments are replaced with white space.
	However, since the need for pasting tokens was demonstrated and
	real, ANSI introduced a well-defined token-pasting operator, ##,
	which can be used like this:

		#define Paste(a, b) a##b

	(See also question 5.4.)

	References: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7.

6.3:	What's the best way to write a multi-statement cpp macro?

A:	The usual goal is to write a macro that can be invoked as if it
	were a single function-call statement.  This means that the
	"caller" will be supplying the final semicolon, so the macro
	body should not.  The macro body cannot be a simple brace-
	delineated compound statement, because syntax errors would
	result if it were invoked (apparently as a single statement, but
	with a resultant extra semicolon) as the if branch of an if/else
	statement with an explicit else clause.

	The traditional solution is to use

		#define Func() do { \
			/* declarations */ \
			stmt1; \
			stmt2; \
			/* ... */ \
			} while(0)	/* (no trailing ; ) */

	When the "caller" appends a semicolon, this expansion becomes a
	single statement regardless of context.  (An optimizing compiler
	will remove any "dead" tests or branches on the constant
	condition 0, although lint may complain.)

	If all of the statements in the intended macro are simple
	expressions, with no declarations or loops, another technique is
	to write a single, parenthesized expression using one or more
	comma operators.  (See the example under question 6.10 below.
	This technique also allows a value to be "returned.")

	References: CT&P Sec. 6.3 pp. 82-3.

6.4:	Is it acceptable for one header file to #include another?

A:	It's a question of style, and thus receives considerable debate.
	Many people believe that "nested #include files" are to be
	avoided: the prestigious Indian Hill Style Guide (see question
	14.3) disparages them; they can make it harder to find relevant
	definitions; they can lead to multiple-declaration errors if a
	file is #included twice; and they make manual Makefile
	maintenance very difficult.  On the other hand, they make it
	possible to use header files in a modular way (a header file
	#includes what it needs itself, rather than requiring each
	#includer to do so, a requirement that can lead to intractable
	headaches); a tool like grep (or a tags file) makes it easy to
	find definitions no matter where they are; a popular trick:

		#ifndef HEADERUSED
		#define HEADERUSED
		...header file contents...
		#endif

	makes a header file "idempotent" so that it can safely be
	#included multiple times; and automated Makefile maintenance
	tools (which are a virtual necessity in large projects anyway)
	handle dependency generation in the face of nested #include
	files easily.  See also section 14.

6.5:	Does the sizeof operator work in preprocessor #if directives?

A:	No.  Preprocessing happens during an earlier pass of
	compilation, before type names have been parsed.  Consider using
	the predefined constants in ANSI's <limits.h>, if applicable, or
	a "configure" script, instead.  (Better yet, try to write code
	which is inherently insensitive to type sizes.)

	References: ANSI Sec. 2.1.1.2 pp. 6-7, Sec. 3.8.1 p. 87
	footnote 83.

6.6:	How can I use a preprocessor #if expression to tell if a machine
	is big-endian or little-endian?

A:	You probably can't.  (Preprocessor arithmetic uses only long
	ints, and there is no concept of addressing.)  Are you sure you
	need to know the machine's endianness explicitly?  Usually it's
	better to write code which doesn't care.

6.7:	I've got this tricky processing I want to do at compile time and
	I can't figure out a way to get cpp to do it.

A:	cpp is not intended as a general-purpose preprocessor.  Rather
	than forcing it to do something inappropriate, consider writing
	your own little special-purpose preprocessing tool, instead.
	You can easily get a utility like make(1) to run it for you
	automatically.

	If you are trying to preprocess something other than C, consider
	using a general-purpose preprocessor (such as m4).

6.8:	I inherited some code which contains far too many #ifdef's for
	my taste.  How can I preprocess the code to leave only one
	conditional compilation set, without running it through cpp and
	expanding all of the #include's and #define's as well?

A:	There are programs floating around called unifdef, rmifdef, and
	scpp which do exactly this.  (See question 17.12.)

6.9:	How can I list all of the pre#defined identifiers?

A:	There's no standard way, although it is a frequent need.  If the
	compiler documentation is unhelpful, the most expedient way is
	probably to extract printable strings from the compiler or
	preprocessor executable with something like the Unix strings(1)
	utility.  Beware that many traditional system-selective
	pre#defined identifiers (e.g. "unix") are non-Standard (because
	they clash with the user's namespace) and are being removed or
	renamed.

6.10:	How can I write a cpp macro which takes a variable number of
	arguments?

A:	One popular trick is to define the macro with a single argument,
	and call it with a double set of parentheses, which appear to
	the preprocessor to indicate a single argument:

		#define DEBUG(args) (printf("DEBUG: "), printf args)

		if(n != 0) DEBUG(("n is %d\n", n));

	The obvious disadvantage is that the caller must always remember
	to use the extra parentheses.  Other solutions are to use
	different macros (DEBUG1, DEBUG2, etc.) depending on the number
	of arguments, or to play games with commas:

		#define DEBUG(args) (printf("DEBUG: "), printf(args))
		#define _ ,
		DEBUG("i = %d" _ i)

	It is often better to use a bona-fide function, which can take a
	variable number of arguments in a well-defined way.  See
	questions 7.1 and 7.2.


Section 7. Variable-Length Argument Lists

7.1:	How can I write a function that takes a variable number of
	arguments?

A:	Use the <stdarg.h> header (or, if you must, the older
	<varargs.h>).

	Here is a function which concatenates an arbitrary number of
	strings into malloc'ed memory:

		#include <stdlib.h>		/* for malloc, NULL, size_t */
		#include <stdarg.h>		/* for va_ stuff */
		#include <string.h>		/* for strcat et al */

		char *vstrcat(char *first, ...)
		{
			size_t len = 0;
			char *retbuf;
			va_list argp;
			char *p;

			if(first == NULL)
				return NULL;

			len = strlen(first);

			va_start(argp, first);

			while((p = va_arg(argp, char *)) != NULL)
				len += strlen(p);

			va_end(argp);

			retbuf = malloc(len + 1);	/* +1 for trailing \0 */

			if(retbuf == NULL)
				return NULL;		/* error */

			(void)strcpy(retbuf, first);

			va_start(argp, first);

			while((p = va_arg(argp, char *)) != NULL)
				(void)strcat(retbuf, p);

			va_end(argp);

			return retbuf;
		}

	Usage is something like

		char *str = vstrcat("Hello, ", "world!", (char *)NULL);

	Note the cast on the last argument.  (Also note that the caller
	must free the returned, malloc'ed storage.)

	Under a pre-ANSI compiler, rewrite the function definition
	without a prototype ("char *vstrcat(first) char *first; {"),
	include <stdio.h> rather than <stdlib.h>, add "extern
	char *malloc();", and use int instead of size_t.  You may also
	have to delete the (void) casts, and use the older varargs
	package instead of stdarg.  See the next question for hints.

	Remember that in variable-length argument lists, function
	prototypes do not supply parameter type information; therefore,
	default argument promotions apply (see question 5.8), and null
	pointer arguments must be typed explicitly (see question 1.2).

	References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S
	Sec. 13.4 pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 .

7.2:	How can I write a function that takes a format string and a
	variable number of arguments, like printf, and passes them to
	printf to do most of the work?

A:	Use vprintf, vfprintf, or vsprintf.

	Here is an "error" routine which prints an error message,
	preceded by the string "error: " and terminated with a newline:

		#include <stdio.h>
		#include <stdarg.h>

		void
		error(char *fmt, ...)
		{
			va_list argp;
			fprintf(stderr, "error: ");
			va_start(argp, fmt);
			vfprintf(stderr, fmt, argp);
			va_end(argp);
			fprintf(stderr, "\n");
		}

	To use the older <varargs.h> package, instead of <stdarg.h>,
	change the function header to:

		void error(va_alist)
		va_dcl
		{
			char *fmt;

	change the va_start line to

		va_start(argp);

	and add the line

		fmt = va_arg(argp, char *);

	between the calls to va_start and vfprintf.  (Note that there is
	no semicolon after va_dcl.)

	References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S
	Sec. 17.12 p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 .

7.3:	How can I discover how many arguments a function was actually
	called with?

A:	This information is not available to a portable program.  Some
	old systems provided a nonstandard nargs() function, but its use
	was always questionable, since it typically returned the number
	of words passed, not the number of arguments.  (Structures and
	floating point values are usually passed as several words.)

	Any function which takes a variable number of arguments must be
	able to determine from the arguments themselves how many of them
	there are.  printf-like functions do this by looking for
	formatting specifiers (%d and the like) in the format string
	(which is why these functions fail badly if the format string
	does not match the argument list).  Another common technique
	(useful when the arguments are all of the same type) is to use a
	sentinel value (often 0, -1, or an appropriately-cast null
	pointer) at the end of the list (see the execl and vstrcat
	examples under questions 1.2 and 7.1 above).

7.4:	I can't get the va_arg macro to pull in an argument of type
	pointer-to-function.

A:	The type-rewriting games which the va_arg macro typically plays
	are stymied by overly-complicated types such as pointer-to-
	function.  If you use a typedef for the function pointer type,
	however, all will be well.

	References: ANSI Sec. 4.8.1.2 p. 124.

7.5:	How can I write a function which takes a variable number of
	arguments and passes them to some other function (which takes a
	variable number of arguments)?

A:	In general, you cannot.  You must provide a version of that
	other function which accepts a va_list pointer, as does vfprintf
	in the example above.  If the arguments must be passed directly
	as actual arguments (not indirectly through a va_list pointer)
	to another function which is itself variadic (for which you do
	not have the option of creating an alternate, va_list-accepting
	version) no portable solution is possible.  (The problem can be
	solved by resorting to machine-specific assembly language.)

7.6:	How can I call a function with an argument list built up at run
	time?

A:	There is no guaranteed or portable way to do this.  If you're
	curious, ask this list's editor, who has a few wacky ideas you
	could try...  (See also question 16.11.)


Section 8. Boolean Expressions and Variables

8.1:	What is the right type to use for boolean values in C?  Why
	isn't it a standard type?  Should #defines or enums be used for
	the true and false values?

A:	C does not provide a standard boolean type, because picking one
	involves a space/time tradeoff which is best decided by the
	programmer.  (Using an int for a boolean may be faster, while
	using char may save data space.)

	The choice between #defines and enums is arbitrary and not
	terribly interesting (see also question 9.1).  Use any of

		#define TRUE  1			#define YES 1
		#define FALSE 0			#define NO  0

		enum bool {false, true};	enum bool {no, yes};

	or use raw 1 and 0, as long as you are consistent within one
	program or project.  (An enum may be preferable if your debugger
	expands enum values when examining variables.)

	Some people prefer variants like

		#define TRUE (1==1)
		#define FALSE (!TRUE)

	or define "helper" macros such as

		#define Istrue(e) ((e) != 0)

	These don't buy anything (see question 8.2 below; see also
	question 1.6).

8.2:	Isn't #defining TRUE to be 1 dangerous, since any nonzero value
	is considered "true" in C?  What if a built-in boolean or
	relational operator "returns" something other than 1?

A:	It is true (sic) that any nonzero value is considered true in C,
	but this applies only "on input", i.e. where a boolean value is
	expected.  When a boolean value is generated by a built-in
	operator, it is guaranteed to be 1 or 0.  Therefore, the test

		if((a == b) == TRUE)

	will work as expected (as long as TRUE is 1), but it is
	obviously silly.  In general, explicit tests against TRUE and
	FALSE are undesirable, because some library functions (notably
	isupper, isalpha, etc.) return, on success, a nonzero value
	which is _not_ necessarily 1.  (Besides, if you believe that
	"if((a == b) == TRUE)" is an improvement over "if(a == b)", why
	stop there?  Why not use "if(((a == b) == TRUE) == TRUE)"?)  A
	good rule of thumb is to use TRUE and FALSE (or the like) only
	for assignment to a Boolean variable or function parameter, or
	as the return value from a Boolean function, but never in a
	comparison.

	The preprocessor macros TRUE and FALSE are used for code
	readability, not because the underlying values might ever
	change.  (See also questions 1.7 and 1.9.)

	References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42,
	Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI Secs. 3.3.3.3, 3.3.8,
	3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5; Achilles and the
	Tortoise.


Section 9. Structs, Enums, and Unions

9.1:	What is the difference between an enum and a series of
	preprocessor #defines?

A:	At the present time, there is little difference.  Although many
	people might have wished otherwise, the ANSI standard says that
	enumerations may be freely intermixed with integral types,
	without errors.  (If such intermixing were disallowed without
	explicit casts, judicious use of enums could catch certain
	programming errors.)

	Some advantages of enums are that the numeric values are
	automatically assigned, that a debugger may be able to display
	the symbolic values when enum variables are examined, and that
	they obey block scope.  (A compiler may also generate nonfatal
	warnings when enums and ints are indiscriminately mixed, since
	doing so can still be considered bad style even though it is not
	strictly illegal).  A disadvantage is that the programmer has
	little control over the size (or over those nonfatal warnings).

	References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S
	Sec. 5.5 p. 100; ANSI Secs. 3.1.2.5, 3.5.2, 3.5.2.2 .

9.2:	I heard that structures could be assigned to variables and
	passed to and from functions, but K&R I says not.

A:	What K&R I said was that the restrictions on struct operations
	would be lifted in a forthcoming version of the compiler, and in
	fact struct assignment and passing were fully functional in
	Ritchie's compiler even as K&R I was being published.  Although
	a few early C compilers lacked struct assignment, all modern
	compilers support it, and it is part of the ANSI C standard, so
	there should be no reluctance to use it.

	References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S
	Sec. 5.6.2 p. 103; ANSI Secs. 3.1.2.5, 3.2.2.1, 3.3.16 .

9.3:	How does struct passing and returning work?

A:	When structures are passed as arguments to functions, the entire
	struct is typically pushed on the stack, using as many words as
	are required.  (Programmers often choose to use pointers to
	structures instead, precisely to avoid this overhead.)

	Structures are often returned from functions in a location
	pointed to by an extra, compiler-supplied "hidden" argument to
	the function.  Some older compilers used a special, static
	location for structure returns, although this made struct-valued
	functions nonreentrant, which ANSI C disallows.

	References: ANSI Sec. 2.2.3 p. 13.

9.4:	The following program works correctly, but it dumps core after
	it finishes.  Why?

		struct list
			{
			char *item;
			struct list *next;
			}

		/* Here is the main program. */

		main(argc, argv)
		...

A:	A missing semicolon causes the compiler to believe that main
	returns a structure.  (The connection is hard to see because of
	the intervening comment.)  Since struct-valued functions are
	usually implemented by adding a hidden return pointer, the
	generated code for main() tries to accept three arguments,
	although only two are passed (in this case, by the C start-up
	code).  See also question 17.21.

	References: CT&P Sec. 2.3 pp. 21-2.

9.5:	Why can't you compare structs?

A:	There is no reasonable way for a compiler to implement struct
	comparison which is consistent with C's low-level flavor.  A
	byte-by-byte comparison could be invalidated by random bits
	present in unused "holes" in the structure (such padding is used
	to keep the alignment of later fields correct; see questions
	9.10 and 9.11).  A field-by-field comparison would require
	unacceptable amounts of repetitive, in-line code for large
	structures.

	If you want to compare two structures, you must write your own
	function to do so.  C++ would let you arrange for the ==
	operator to map to your function.

	References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI
	Rationale Sec. 3.3.9 p. 47.

9.6:	How can I read/write structs from/to data files?

A:	It is relatively straightforward to write a struct out using
	fwrite:

		fwrite((char *)&somestruct, sizeof(somestruct), 1, fp);

	and a corresponding fread invocation can read it back in.
	However, data files so written will _not_ be very portable (see
	questions 9.11 and 17.3).  Note also that on many systems you
	must use the "b" flag when fopening the files.

9.7:	I came across some code that declared a structure like this:

		struct name
			{
			int namelen;
			char name[1];
			};

	and then did some tricky allocation to make the name array act
	like it had several elements.  Is this legal and/or portable?

A:	This technique is popular, although Dennis Ritchie has called it
	"unwarranted chumminess with the C implementation."  An ANSI
	Interpretation Ruling has deemed it (more precisely, access
	beyond the declared size of the name field) to be not strictly
	conforming, although a thorough treatment of the arguments
	surrounding the legality of the technique is beyond the scope of
	this list.  It seems, however, to be portable to all known
	implementations.  (Compilers which check array bounds carefully
	might issue warnings.)

	To be on the safe side, it may be preferable to declare the
	variable-size element very large, rather than very small; in the
	case of the above example:

		...
		char name[MAXSIZE];
		...

	where MAXSIZE is larger than any name which will be stored.
	(The trick so modified is said to be in conformance with the
	Standard.)

	References: ANSI Rationale Sec. 3.5.4.2 pp. 54-5.

9.8:	How can I determine the byte offset of a field within a
	structure?

A:	ANSI C defines the offsetof macro, which should be used if
	available; see <stddef.h>.  If you don't have it, a suggested
	implementation is

		#define offsetof(type, mem) ((size_t) \
			((char *)&((type *) 0)->mem - (char *)((type *) 0)))

	This implementation is not 100% portable; some compilers may
	legitimately refuse to accept it.

	See the next question for a usage hint.

	References: ANSI Sec. 4.1.5, Rationale Sec. 3.5.4.2 p. 55.

9.9:	How can I access structure fields by name at run time?

A:	Build a table of names and offsets, using the offsetof() macro.
	The offset of field b in struct a is

		offsetb = offsetof(struct a, b)

	If structp is a pointer to an instance of this structure, and b
	is an int field with offset as computed above, b's value can be
	set indirectly with

		*(int *)((char *)structp + offsetb) = value;

9.10:	Why does sizeof report a larger size than I expect for a
	structure type, as if there was padding at the end?

A:	Structures may have this padding (as well as internal padding;
	see also question 9.5), so that alignment properties will be
	preserved when an array of contiguous structures is allocated.

9.11:	My compiler is leaving holes in structures, which is wasting
	space and preventing "binary" I/O to external data files.  Can I
	turn off the padding, or otherwise control the alignment of
	structs?

A:	Your compiler may provide an extension to give you this control
	(perhaps a #pragma), but there is no standard method.  See also
	question 17.3.

9.12:	Can I initialize unions?

A:	ANSI Standard C allows an initializer for the first member of a
	union.  There is no standard way of initializing the other
	members (nor, under a pre-ANSI compiler, is there generally any
	way of initializing any of them).

9.13:	How can I pass constant values to routines which accept struct
	arguments?

A:	C has no way of generating anonymous struct values.  You will
	have to use a temporary struct variable.


Section 10. Declarations

10.1:	How do you decide which integer type to use?

A:	If you might need large values (above 32767 or below -32767),
	use long.  Otherwise, if space is very important (there are
	large arrays or many structures), use short.  Otherwise, use
	int.  If well-defined overflow characteristics are important
	and/or negative values are not, use the corresponding unsigned
	types.  (But beware of mixing signed and unsigned in
	expressions.)  Similar arguments apply when deciding between
	float and double.

	Although char or unsigned char can be used as a "tiny" int type,
	doing so is often more trouble than it's worth, due to
	unpredictable sign extension and increased code size.

	These rules obviously don't apply if the address of a variable
	is taken and must have a particular type.

	If for some reason you need to declare something with an _exact_
	size (usually the only good reason for doing so is when
	attempting to conform to some externally-imposed storage layout,
	but see question 17.3), be sure to encapsulate the choice behind
	an appropriate typedef.

10.2:	What should the 64-bit type on new, 64-bit machines be?

A:	Some vendors of C products for 64-bit machines support 64-bit
	long ints.  Others fear that too much existing code depends on
	sizeof(int) == sizeof(long) == 32 bits, and introduce a new 64-
	bit long long (or __longlong) type instead.

	Programmers interested in writing portable code should therefore
	insulate their 64-bit type n