Search the FAQ Archives

3 - A - B - C - D - E - F - G - H - I - J - K - L - M
N - O - P - Q - R - S - T - U - V - W - X - Y - Z
faqs.org - Internet FAQ Archives

C++ FAQ (part 04 of 14)

( Part1 - Part2 - Part3 - Part4 - Part5 - Part6 - Part7 - Part8 - Part9 - Part10 - Part11 - Part12 - Part13 - Part14 )
[ Usenet FAQs | Web FAQs | Documents | RFC Index | Zip codes ]
Archive-name: C++-faq/part04
Posting-Frequency: monthly
Last-modified: Jun 17, 2002
URL: http://www.parashift.com/c++-faq-lite/

See reader questions & answers on this topic! - Help others by sharing your knowledge
AUTHOR: Marshall Cline / cline@parashift.com / 972-931-9470

COPYRIGHT: This posting is part of "C++ FAQ Lite."  The entire "C++ FAQ Lite"
document is Copyright(C)1991-2002 Marshall Cline, Ph.D., cline@parashift.com.
All rights reserved.  Copying is permitted only under designated situations.
For details, see section [1].

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.

C++-FAQ-Lite != C++-FAQ-Book: This document, C++ FAQ Lite, is not the same as
the C++ FAQ Book.  The book (C++ FAQs, Cline and Lomow, Addison-Wesley) is 500%
larger than this document, and is available in bookstores.  For details, see
section [3].

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

SECTION [5]: Netiquette when posting to comp.lang.c++


[5.1] What does IMHO mean? (or IMO, IMNSHO, FWIW, OTOH, etc.)?

Here's a partial list of acronyms in alphabetical order:
 * AFAICS = As far as I can see
 * BTW = By the way
 * FWIW = For what it's worth
 * FYI = For your information
 * IMHO = In my humble opinion (egoless)
 * IMAO = In my arrogant opinion (a lot of ego)
 * IMNSHO = In my not-so humble opinion (a lot of ego)
 * IMO = In my opinion (a little ego)
 * KUTGW = Keep Up The Good Work
 * MYOB = Mind your own business
 * OO = Object-Oriented
 * OTOH = On the other hand
 * RTFM = Read the ___ manual
 * SO = Significant other (as in, "My SO and I went for a walk...")

BTW my SO says, "FWIW IMNSHO 'KUTGW' is rare; OTOH it may be helpful to
somebody."

For more acronyms please see www.astro.umd.edu/~marshall/abbrev.html.

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

[5.2] How do I get other people to do my homework problem for me?

Shame on you!

Please do not post your homework questions to comp.lang.c++.  And don't send
them to people via email either!

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

[5.3] What should I do if I see someone else posting a homework problem?

When a slackard[5.2] asks comp.lang.c++ to do their homework for them,
answering their question is the worst thing for them.  Please don't do it!
Instead you can use the following table of "frequently asked homework
assignments" to give them a hint/pointer:

===TABLE-BEGIN=== (yea, I know; it's pathetic; the HTML version is better)

===TABLE-ROW===
If someone asks...
---
...then here's a brief answer:

===TABLE-ROW===
How do I do Equation Parsing in C++?
---
Use a stack of operators to convert infix to postfix, then a stack of operands
to evaluate the postfix expression.

===TABLE-ROW===
How do I do Shortest Path in C++?
---
Look up Dijkstra's algorithm and backtracking.

===TABLE-ROW===
How do I do Sorting in C++?
---
Look up heapsort, quicksort, merge sort, internal and external sorting.

===TABLE-ROW===
How do I do Minimum Spanning Trees in C++?
---
Look up Kruskal and/or Prim's algorithm.

===TABLE-ROW===
How do I do Combinations and/or Permutations in C++?
---
See your algorithms book.

===TABLE-ROW===
How do I do <some small essay problem; obviously contrived for a school
assignment; too well defined to to be from the real world> in C++?
---
Do it yourself. If you get stuck, ask a specific question.

===TABLE-END===

[If anyone has other suggestions that should go into this table, please let me
know; thanks; (cline@parashift.com)].

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

[5.4] How can I find out about general netiquette so I don't embarrass myself?

Key guidelines:
 * Do not say, "Please respond by e-mail because I don't normally read this
   newsgroup".  If you don't have enough time for the newsgroup, don't expect
   the newsgroup to have enough time for you.
 * Do not post questions that are answered in the newsgroup's FAQ.  That's like
   saying your time (to read the FAQ) is more valuable than the time of
   hundreds and hundreds of others (to answer your question).  Tres uncool.
   Read the FAQ first![5.5]
 * Do not cross post your question to a big pile of newsgroups.  Post to the
   newsgroup (singular) that best fits your question[5.9].  If you don't get an
   answer in the "right" newsgroup, post somewhere else but redirect followups
   back to the "right" newsgroup.
 * Do include a working e-mail address in your signature.  If your From:
   address is not correct, please notify your system administrator.  Until it's
   fixed, add a Reply-To: line that gives your correct e-mail address.

Many more general netiquette questions are answered in the newsgroup
news.announce.newusers.  This newsgroup contains many must-read articles for
new users.

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

[5.5] What do I do if someone else posts a question that's already in the FAQ?

Please don't answer a question that's already in the FAQ.  Instead politely but
firmly point the questioner to the FAQ using the following template:

    Subject: It's in the FAQ (was: Original_Subject_Goes_Here)

    > Original_Question_Goes_Here [...]

    This issue is covered in the C++ FAQ.
    You can get the FAQ at:
        http://www.parashift.com/c++-faq-lite/

    Please read the FAQ.

If you're willing to help in this effort, consider yourself "deputized" to
point people to the FAQ using something like the above template.  With your
help, hopefully we can improve the signal-to-noise ratio on comp.lang.c++ and
thereby preserve it as a valuable resource.

Note #1: Please don't give them the location of the appropriate FAQ.  E.g.,
don't say, "Look at FAQ [10.3]" or "Look in section [10]".  It's the old
give-them-a-fish vs. teach-them-to-fish problem.

Note #2: Please be polite.  I'm hoping we can avoid "RTFM" or "RTFFAQ"
euphemisms (or worse!).

Thanks for any help you can give in this matter.

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

[5.6] Wait a minute, does that previous FAQ say to not answer their question
      just because it's already answered in the FAQ?!? [NEW!]

[Recently created (in 5/02) and fixed misspelling in "cripple" thanks to John
Marshall plus general rewording (in 6/02).]

Yes, that's exactly what the previous FAQ says: when someone asks a question
that's already in the FAQ, please do not answer their question.
 * The poster is better off if you don't answer a FAQ-question: if you really
   want to help people, help them become self sufficient so they're not always
   dependent on others to look things up for them.
 * The newsgroup is better off if you don't answer a FAQ-question: if you
   actually answer their question, chances are your answer will elicit
   follow-up postings and increase the amount of "noise" on the newsgroup.
   This reduces the newsgroup's value to everyone.

People ought to ask others for help with questions that aren't in the FAQ.  But
please don't cripple people by training them to depend on others for answers to
questions that are in the FAQ.

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

[5.7] What makes a good Subject: line?

Be descriptive:
 * Bad: "Subject: HELP"
 * Bad: "Subject: C++ problem"
 * Bad: "Subject: SEX SEX SEX"
 * Good: "Subject: Problem new'ing a multi-dimensional array"

Mention your compiler/version if you think it's relevant.

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

[5.8] How do I post a question about code that doesn't work correctly?

Key guidelines:

 1. Post compile'able code: avoid ellipses, such as void f() { ... }

 2. Post complete code: put in all necessary #includes and declarations of
    needed types and functions

 3. Post minimal code: just enough to demonstrate the problem; skip I/O and
    calls to libraries if possible

 4. Post one compilation unit: if possible, combine Foo.h into Foo.cpp

 5. Post the tools you used: compiler name, version number, operating system,
    etc

 6. Post the tool options you used: libraries, exact compiler and linker
    options, etc

 7. Post the exact messages you received; differentiate between compiler,
    linker, and runtime messages

As always, make sure your question isn't already in the FAQ.  Use the subject
index to check.

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

[5.9] Which newsgroup should I post my questions?

Only post to comp.lang.c++ if your question is about the C++ language itself.
For example, C++ code design, syntax, style, rules, bugs, etc.
Operating-specific questions (e.g., about Windows NT / 95 / 3.x, UNIX, etc.)
should go to an operating-system-specific newsgroup (see below), not to
comp.lang.c++.

Here are some other potentially relevant newsgroups:
 * comp.lang.c++.moderated
   - A moderated variant of comp.lang.c++
   - The moderator's job is to keep the signal-to-noise ratio higher than in
     comp.lang.c++
 * comp.object
   - Mostly OO design issues, with less emphasis on OO programming)
   - That group's FAQ contains an excellent introduction to OO along with an
     overview of OO terms and concepts
 * comp.std.c++
   - Discussion directly related to the evolving ANSI/ISO C++ standard
   - The evolving ANSI/ISO C++ standard is discussed below
 * 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
   - Sample topic: Accessing C++ classes in a DLL
   - Sample topic: A dialog as an MDI child window [with OWL]
   - Sample topic: Disabled menu choices become enabled [with MFC]
   - Sample topic: Using STRICT with windows.h
   - Sample topic: A programmer's bibliography
 * comp.os.msdos.programmer
   - Much of the traffic is about language products, chiefly from Borland and
     Microsoft
   - Note: The FAQ for this group is not available at rtfm.mit.edu; it is at
     ftp://oak.oakland.edu/pub/msdos/ and ftp://garbo.uwasa.fi/pc/doc-net
   - Sample topic: How can I read a character without [waiting for] the Enter
     key?
   - Sample topic: How can I read, create, change, or delete the volume label?
   - Sample topic: How do I configure a COM port and use it to transmit data?
   - Sample topic: How can a C program send control codes to my printer?
   - Sample topic: How can I find the Microsoft mouse position and button
     status?
   - Sample topic: How can I write a TSR (terminate-stay-resident) utility?
   - Sample topic: How can I contact [Borland, Microsoft]?
 * comp.os.msdos.programmer.turbovision
   - Borland's character-mode framework
 * comp.unix.programmer
   - Sample topic: How do I use popen() to open a process for reading and
     writing?
   - Sample topic: How do I sleep() in a C program for less than one second?
 * comp.unix.solaris
   - Covers SunOS 4.x and Solaris
   - Sample topic: Signal Primer
   - Sample topic: Waiting for Children to Exit
 * gnu.g++.help
   - Sample topic: Where can I find a demangler?
   - Sample topic: Getting gcc/g++ binaries for Solaris 2.x
   - Sample topic: What documentation exists for g++ 2.x?
 * comp.sys.mac.programmer.* and comp.sys.mac.oop.*
   - Macintosh issues
 * gnu.g++.bug
   - Bug reports for g++; see the g++ docs
 * comp.lang.c
   - FAQ is posted monthly, and is maintained by Steve Summit
   - Sample topic: I'm confused.  NULL is guaranteed to be 0, but the null
     pointer is not?
   - Sample topic: So what is meant by the "equivalence of pointers and arrays"
     in C?
   - Sample topic: Why doesn't printf("%d\n", i++ * i++); work?
   - Sample topic: How can I write a function that takes a variable number of
     arguments? [stdarg.h or varargs.h]
   - Sample topic: How do I declare an array of pointers to functions returning
     pointers to functions returning pointers to characters?
 * comp.graphics
   - Issues revolving around graphics programming
 * comp.sources.wanted
   - If you want some source code for something, post your request there
 * comp.programming
   - General programming issues

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

[5.10] Should I post job advertisements and/or resumes on comp.lang.c++?

NO!!!

Job ads, off-topic in comp.lang.c++, give the impression of an employer that is
irresponsible and/or technically clueless -- not the impression you want to
make! Instead post this sort of thing in one of the dozens of *.jobs.*
newsgroups that are designed for that purpose.

Note: if you see someone else posting a job ad, please check here before
flaming them[5.12].

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

[5.11] What if I really need a job; should I post my resume on comp.lang.c++?

NO!!!

Resume postings, off-topic in comp.lang.c++, give the impression of an employee
that is irresponsible and/or technically clueless -- not the impression you
want to make! Instead post this sort of thing in one of the newsgroups that are
designed for that purpose.

Note: if you see someone else posting a resume or job request, please check
here before flaming them[5.12].

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

[5.12] What should I do to someone who posts something off-topic?

An extended flame war against an off-topic posting is just as off-topic as the
original off-topic posting.  The cure can be worse than the disease.

Instead use something brief and professional such as in the previous two FAQs
(which, by the way, were adapted from other sources; see the credits in those
FAQs).  And please don't get personal or nasty -- that just prolongs the
(off-topic) exchange.

Remember the 5 "B"s of correction: Be Brief Brother, Be Brief.

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

[5.13] What about spam? [UPDATED!]

[Recently fixed a typo thanks to Paul Savage (in 6/02).]

Before you throw the word "spam" around (and especially before you accuse
someone else of posting "spam"), please check to see some sites that provide a
clear definition of exactly when a posting is or is not "spam." One such
definition is provided here <http://www.killfile.org/faqs/spam.html>.

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

[5.14] How do I get the FAQs for a particular newsgroup?

Let me count the ways...

FAQs (Frequently Asked Questions lists) are available 24-hours a day via:
 * The web: www.faqs.org/
 * ftp: ftp://rtfm.mit.edu/pub/usenet/
 * e-mail: send a message with the line "help" to mail-server@rtfm.mit.edu
 * usenet: many FAQs are available in the newsgroup news.answers

Please, PLEASE do not send e-mail to me!

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

SECTION [6]: Big Picture issues


[6.1] Is C++ a practical language?

Yes.

C++ is a practical tool.  It's not perfect[6.2], but it's useful.

In the world of industrial software, C++ is viewed as a solid, mature,
mainstream tool.  It has widespread industry support which makes it "good" from
an overall business perspective.

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

[6.2] Is C++ a perfect language?

Nope.

C++ wasn't designed to demonstrate what a perfect OO language looks like.  It
was designed to be a practical tool for solving real world problems.  It has a
few warts, but the only place where it's appropriate to keep fiddling with
something until it's perfect is in a pure academic setting.  That wasn't C++'s
goal.

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

[6.3] What's the big deal with OO?

Object-oriented techniques are the best way we know of to develop large,
complex software applications and systems.

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.

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

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

[6.4] Is C++ better than Ada? (or Visual Basic, C, FORTRAN, Pascal, Smalltalk,
      or any other language?)

This question generates much much more heat than light.  Please read the
following before posting some variant of this question.

In 99% of the cases, programming language selection is dominated by business
considerations, not by technical considerations.  Things that really end up
mattering are things like availability of a programming environment for the
development machine, availability of runtime environment(s) for the deployment
machine(s), licensing/legal issues of the runtime and/or development
environments, availability of trained developers, availability of consulting
services, and corporate culture/politics.  These business considerations
generally play a much greater role than compile time performance, runtime
performance, static vs. dynamic typing, static vs. dynamic binding, etc.

Anyone who argues in favor of one language over another in a purely technical
manner (i.e., who ignores the dominant business issues) exposes themself as a
techie weenie, and deserves not to be heard.

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

[6.5] Who uses C++?

Lots and lots of companies and government sites.  Lots.

The large number of developers (and therefore the large amount of available
support infrastructure including vendors, tools, training, etc.) is one of
several critical features of C++[6.7].

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

[6.6] How long does it take to learn OO/C++?

Companies successfully teach standard industry "short courses," where a
university semester course is compressed into one 40 hour work week.  But
regardless of where you get your training, make sure the courses have a
hands-on element, since most people learn best when they have projects to help
the concepts "gel." But even if they have the best training, they're not ready
yet.

It takes 6-12 months to become proficient in OO/C++.  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 been wrong.  As a bare minimum on "drive," you must
be willing to put in some extra hours (it's a lot easier to learn some new
facts than it is to change your paradigm [i.e., to change the way you think; to
change your notion of goodness; to change your mental model of the world of
technology]).

Two things you should do:
 * Bring in a "mentor"[27.1]
 * Get your people two books: one to tell them what is legal[27.6], another to
   tell them what is moral[27.5]

Two things you should not do:
 * You should not bother having your people trained in C as a stepping-stone to
   learning OO/C++[27.2]
 * You should not bother having your people trained in Smalltalk as a
   stepping-stone to learning OO/C++[27.3]

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

[6.7] What are some features of C++ from a business perspective?

Here are a few features of OO/C++ from a business perspective:
 * C++ has a huge installed base[6.5], which means you'll have multi-vendor
   support for tools, environments, consulting services, etc.[6.4], plus you'll
   have a very valuable line-item on your resume
 * C++ lets developers provide simplified interfaces[7.3] to software chunks,
   which improves the defect-rate when those chunks are (re)used
 * C++ lets you exploit developer's intuition through operator
   overloading[13.2], which reduces the learning curve for (re)users
 * C++ localizes access[7.4] to a software chunk, which reduces the cost of
   changes.
 * C++ reduces the safety-vs.-usability tradeoff[7.5], which improves the cost
   of (re)using a chunk of software.
 * C++ reduces the safety-vs.-speed tradeoff[9.2], which improves defect rates
   without degrading performance.
 * C++ gives you inheritance and dynamic binding[6.8] which let old code call
   new code[6.9], making it possible to quickly extend/adapt your software to
   hit narrow market windows.

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

[6.8] Are virtual functions (dynamic binding) central to OO/C++?

Yes!

Without virtual functions[20], C++ wouldn't be object-oriented.  Operator
overloading[13] and non-virtual member functions are great, but they are, after
all, just syntactic sugar for the more typical C notion of passing a pointer to
a struct to a function.  The standard library[34.1] contains numerous templates
that illustrate "generic programming" techniques, which are also great, but
virtual functions are still at the heart of object-oriented programming using
C++.

From a business perspective, there is very little reason to switch from
straight C to C++ without virtual functions (we'll ignore generic programming
and the standard library[34.1] in this FAQ).  Technical people often think that
there is a large difference between C and non-OO C++, but without OO, the
difference usually isn't enough to justify the cost of training developers, new
tools, etc.  In other words, if I were to advise a manager regarding whether to
switch from C to non-OO C++ (i.e., to switch languages but not paradigms), I'd
probably discourage him or her unless there were compelling tool-oriented
reasons.  From a business perspective, OO can help make systems extensible and
adaptable, but just the syntax of C++ classes without OO may not even reduce
the maintenance cost, and it surely adds to the training cost significantly.

Bottom line: C++ without virtual is not OO.  Programming with classes but
without dynamic binding is called "object based," but not "object oriented."
Throwing out virtual functions is the same as throwing out OO.  All you have
left is object-based programming, similar to the original Ada language (the new
Ada language, by the way, supports true OO rather than just object-based
programming).

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

[6.9] I'm from Missouri.  Can you give me a simple reason why virtual functions
      (dynamic binding) make a big difference?

Overview: Dynamic binding can improve reuse by letting old code call new code.

Before OO came along, reuse was accomplished by having new code call old code.
For example, a programmer might write some code that called some reusable code
such as printf().

With OO, reuse can also be accomplished by having old code call new code.  For
example, a programmer might write some code that is called by a framework that
was written by their great, great grandfather.  There's no need to change
great-great-grandpa's code.  In fact, it doesn't even need to be recompiled.
Even if all you have left is the object file and the source code that
great-great-grandpa wrote was lost 25 years ago, that ancient object file will
call the new extension without anything falling apart.

That is extensibility, and that is OO.

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

[6.10] Is C++ backward compatible with ANSI/ISO 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, a function declared using f() can be
passed an arbitrary number of parameters of arbitrary types).

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 (e.g., the typedef struct Fred Fred; technique still works, but is
redundant in C++).

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

[6.11] Is C++ standardized?

Yes.

The C++ standard was finalized and adopted by ISO (International Organization
for Standardization) as well as several national standards organizations such
as ANSI (The American National Standards Institute), BSI (The British Standards
Institute), DIN (The German National Standards Organization).  The ISO standard
was finalized and adopted by unanimous vote November 14, 1997.

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 include
just about everyone: representatives from Australia, Canada, Denmark, France,
Germany, Ireland, Japan, the Netherlands, New Zealand, Sweden, the UK, and the
USA, along with representatives from about a hundred companies and many
interested individuals.  Major players include AT&T, Ericsson, Digital,
Borland, Hewlett Packard, IBM, Mentor Graphics, Microsoft, Silicon Graphics,
Sun Microsystems, and Siemens.  After about 8 years of work, this standard is
now complete.  On November 14, 1997, the standard was approved by a unanimous
vote of the countries that had representatives present in Morristown.

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

[6.12] Where can I get a copy of the ANSI/ISO C++ standard?

There are at least three ways to get a soft-copy of this document:
 * $18 [published by ANSI]: go to this page
   <http://www.techstreet.com/cgi-bin/detail?product_id=49964>, select "PDF
   file" from the pull-down, and click "Place this in your shopping basket."
 * $18 [published by ANSI]: go to this page
   <http://webstore.ansi.org/ansidocstore/product.asp?sku=ISO%2FIEC+14882%2D1998>
   and click "Add to Basket."
 * $245 [published by ISO]: go to this page
   <http://webstore.ansi.org/ansidocstore/product.asp?sku=ISO%2FIEC+14882%3A1998>
   and click "Add to Basket."

Note: The ISO document is well over ten times more expensive than the ANSI
document, however the technical content is the same.  The ISO document has a
different title page, but the technical material is identical to the ANSI
document.  Please don't email asking me why ISO charges so much more for
fundamentally the same thing; that's ISO's business decision; you'll have to
take it up with ISO's publishing/sales department.

There are at least two ways to get a hard-copy of this document:
 * $175 [published by ANSI]: go to this page
   <http://www.techstreet.com/cgi-bin/detail?product_id=49964>, select
   "Hardcopy" from the pull-down, and click "Place this in your shopping
   basket."
 * Unknown price [published by ANSI]: call NCITS (National Committee for
   Information Technology Standards; this is the new name of the organization
   that used to be called "X3").  The contact person is Monica Vega,
   202-626-5739 or 202-626-5738.  Ask for document FDC 14882.  Be prepared to
   spend some money -- the document is certainly not free.

There are two other potentially interesting (and free) documents you might want
to look at:
 * $0: If you're willing to put up with a (free) document that's
   non-authorative, out-of-date, and partially incorrect, you can get
   "committee draft #2" here <ftp://ftp.maths.warwick.ac.uk/pub/c++/std/cd2/>
   and/or here <ftp://ftp.research.att.com/dist/c++std/WP/CD2/>.
 * $0: The ISO committee's press release (not a copy of the ANSI or ISO
   standards!) is here <http://www.research.att.com/~bs/iso_release.html>.
   This press release is readable by non-programmers.

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

[6.13] What are some "interview questions" I could ask that would let me know
       if candidates really know their stuff? [UPDATED!]

[Recently rewrote from scratch thanks to Robin (in 5/02).]

This answer is primarily for non-technical managers and HR folks who are trying
to do a good job at interviewing C++ candidates.  If you're a C++ programmer
about to be interviewed, and if you're lurking in this FAQ hoping to know the
questions they'll ask you ahead of time so you can avoid having to really learn
C++, shame on you: spend your time becoming technically competent and you won't
have to try to "cheat" your way through life!

Back to the non-technical manager / HR person: obviously you are eminently
qualified to judge whether a candidate is a good "fit" with your company's
culture.  However there are enough charlatans, wannabes, and posers out there
that you really need to team up with someone who is technically competent in
order to make sure the candidate has the right level of technical skill.  A lot
of companies have been burned by hiring nice but incompetent duds -- people who
were incompetent in spite of the fact that they knew the answers to a few
obscure questions.  The only way to smoke out the posers and wannabes is to get
someone in with you who can ask penetrating technical questions.  You have no
hope whatsoever of doing that yourself.  Even if I gave you a bunch of "tricky
questions," they wouldn't smoke out the bad guys.

Your technical sidekick might not be (and often isn't) qualified to judge the
candidate on personality or soft skills, so please don't abdicate your role as
the final arbiter in the decision making process.  But please don't think you
can ask a half dozen C++ questions and have the slightest clue if the candidate
really knows what they're talking about from a technical perspective.

Having said all that, if you're technical enough to read the C++ FAQ, you can
dig up a lot of good interview questions here.  The FAQ has a lot of goodies
that will sepatate the wheat from the chaff.  The FAQ focuses on what
programmers should do, as opposed to merely what the compiler will let them do.
There are things that can be done in C++ but shouldn't be done.  The FAQ helps
people separate those two.

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

[6.14] What does the FAQ mean by "such-in-such is evil"? [NEW!]

[Recently created (in 6/02).]

It means such-in-such is something you should avoid most of the time, but not
something you should avoid all the time.  For example, you will end up using
these "evil" things whenever they are "the least evil of the evil
alternatives." It's a joke, okay? Don't take it too seriously.

The real purpose of the term ("Ah ha, I hear you saying, there really is a
hidden motive!"; you're right: there is) is to shake new C++ programmers free
from some of their old thinking.  For example, C programmers who are new to C++
often use pointers, arrays and/or #define more than they should.  The FAQ lists
those as "evil" to give new C++ programmers a vigorous (and droll!) shove in
the right direction.  The goal of farcical things like "pointers are evil" is
to convince new C++ programmers that C++ really isn't "just like C except for
those silly "//" comments."

Now let's get real here.  I'm not suggesting macros or arrays or pointers are
right up there with murder or kidnapping.  Well, may be pointers.  (Just
kidding!) So don't get all hyper about the word "evil": it's supposed to sound
a little outrageous.  So don't look for a technically precise definition of
exactly when something is or isn't "evil": there isn't one.

Another thing: don't assume things labeled as "evil" (macros, arrays, pointers,
etc.) are always bad in all situations.  One size does not fit all.  Take out a
fine-point marker and write on the inside of your glasses, Software Development
Is Decision Making.  In other words, there are very few if any "never..." and
"always..." rules in software -- rules that you can apply without thinking --
rules that always work in all situations in all markets -- one-size-fits-all
rules.

In plain English, you will have to make decisions, and the quality of your
decisions will effect the business value of your software.  And sometimes you
will have to choose between a bunch of bad options.  When that happens, the
best you can hope for is to choose the least bad of the alternatives, the
lesser of the "evils."

So you will end up using approaches and techniques labeled as "evil." If that
makes you uncomfortable, mentally change the word "evil" to "frequently
undesirable" (but don't quit your day job to become an author: milquetoast
<http://www.dictionary.com/search?q=milquetoast> terms like that put people to
sleep :-)

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

SECTION [7]: Classes and objects


[7.1] 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 i + j or i++, 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.

You can imagine that int is a class that has member functions called
operator++, etc.  (int isn't really a class, but the basic analogy is this: a
class is a type, much like int is a type.)

Note: a C programmer can think of a class as a C struct whose members default
to private.  But if that's all you think of a class, then you probably need to
experience a personal paradigm shift.

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

[7.2] 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
OO/C++, "object" usually means "an instance of a class." Thus a class defines
the behavior of possibly many objects (instances).

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

[7.3] When is an interface "good"?

When it provides a simplified view of a chunk of software, and it is expressed
in the vocabulary of a user (where a "chunk" is normally a class or a tight
group of classes[14.2], and a "user" is another developer rather than the
ultimate customer).
 * The "simplified view" means unnecessary details are intentionally hidden.
   This reduces the user's defect-rate.
 * The "vocabulary of users" means users don't need to learn a new set of words
   and concepts.  This reduces the user's learning curve.

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

[7.4] What is encapsulation?

Preventing unauthorized access to some piece of information or functionality.

The key money-saving insight is to separate the volatile part of some chunk of
software from the stable part.  Encapsulation puts a firewall around the chunk,
which prevents other chunks from accessing the volatile parts; other chunks can
only access the stable parts.  This prevents the other chunks from breaking if
(when!) the volatile parts are changed.  In context of OO software, a "chunk"
is normally a class or a tight group of classes[14.2].

The "volatile parts" are the implementation details.  If the chunk is a single
class, the volatile part is normally encapsulated using the private and/or
protected keywords[19.5].  If the chunk is a tight group of classes[14.2],
encapsulation can be used to deny access to entire classes in that group.
Inheritance[19] can also be used as a form of encapsulation[22.2].

The "stable parts" are the interfaces.  A good interface provides a simplified
view in the vocabulary of a user[7.3], and is designed from the
outside-in[13.10] (here a "user" means another developer, not the end-user who
buys the completed application).  If the chunk is a single class, the interface
is simply the class's public member functions and friend[14] functions.  If the
chunk is a tight group of classes[14.2], the interface can include several of
the classes in the chunk.

Designing a clean interface and separating that interface from its
implementation[22.1] merely allows users to use the interface.  But
encapsulating (putting "in a capsule") the implementation forces users to use
the interface.

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

[7.5] How does C++ help with the tradeoff of safety vs. usability?

In C, encapsulation[7.4] was accomplished by making things static in a
compilation unit or module.  This prevented another module from accessing the
static stuff.  (By the way, that use is now deprecated: don't do that in C++.)

Unfortunately this approach doesn't support multiple instances of the data,
since there is no direct support for making multiple instances of a module's
static data.  If multiple instances were needed in C, programmers typically
used a struct.  But unfortunately C structs don't support encapsulation[7.4].
This exacerbates the tradeoff between safety (information hiding) and usability
(multiple instances).

In C++, you can have both multiple instances and encapsulation via a class.
The public part of a class contains the class's interface, which normally
consists of the class's public member functions and its friend[14] functions.
The private and/or protected[19.5] parts of a class contain the class's
implementation, which is typically where the data lives.

The end result is like an "encapsulated struct." This reduces the tradeoff
between safety (information hiding) and usability (multiple instances).

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

[7.6] How can I prevent other programmers from violating encapsulation by
      seeing the private parts of my class? [UPDATED!]

[Recently minor rewording (in 5/02).]

Not worth the effort -- encapsulation is for code, not people.

It doesn't violate encapsulation for a programmer to see the private and/or
protected[19.5] parts of your class, so long as they don't write code that
somehow depends on what they saw.  In other words, encapsulation doesn't
prevent people from knowing about the inside of a class; it prevents the code
they write from becoming dependent on the insides of the class.  Your company
doesn't have to pay a "maintenance cost" to maintain the gray matter between
your ears; but it does have to pay a maintenance cost to maintain the code that
comes out of your finger tips.  What you know as a person doesn't increase
maintenance cost, provided the code you write depends on the interface rather
than the implementation.

Besides, this is rarely if ever a problem.  I don't know any programmers who
have intentionally tried to access the private parts of a class.  "My
recommendation in such cases would be to change the programmer, not the code"
[James Kanze; used with permission].

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

[7.7] Is Encapsulation a Security device?

No.

Encapsulation != security.

Encapsulation prevents mistakes, not espionage.

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

[7.8] 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.

OK, enough of that squeaky clean techno talk.  Emotionally, most developers
make a strong distinction between a class and a struct.  A struct simply feels
like an open pile of bits with very little in the way of encapsulation or
functionality.  A class feels like a living and responsible member of society
with intelligent services, a strong encapsulation barrier, and a well defined
interface.  Since that's the connotation most people already have, you should
probably use the struct keyword if you have a class that has very few methods
and has public data (such things do exist in well designed systems!), but
otherwise you should probably use the class keyword.

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

SECTION [8]: References


[8.1] 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;
 }

 int 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 vice versa.

OK.  That's how you should think of references as a programmer.  Now, at the
risk of confusing you by giving you a different perspective, here's how
references are implemented.  Underneath it all, a reference i to object x is
typically the machine address of the object x.  But when the programmer says
i++, the compiler generates code that increments x.  In particular, the address
bits that the compiler uses to find x are not changed.  A C programmer will
think of this as if you used the C style pass-by-pointer, with the syntactic
variant of (1) moving the & from the caller into the callee, and (2)
eliminating the *s.  In other words, a C programmer will think of i as a macro
for (*p), where p is a pointer to x (e.g., the compiler automatically
dereferences the underlying pointer; i++ is changed to (*p)++; i = 7 is
automatically changed to *p = 7).

Important note: Even though a reference is often implemented using an address
in the underlying assembly language, please do not think of a reference as a
funny looking pointer to an object.  A reference is the object.  It is not a
pointer to the object, nor a copy of the object.  It is the object.

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

[8.2] What happens if you assign to a reference?

You change the state of the referent (the referent is the object to which the
reference refers).

Remember: the reference is the referent, so changing the reference changes the
state of the referent.  In compiler writer lingo, a reference is an "lvalue"
(something that can appear on the left hand side of an assignment operator).

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

[8.3] What happens if you return a reference?

The function call can appear on the left hand side of an assignment operator.

This ability may seem strange at first.  For example, no one thinks the
expression f() = 7 makes sense.  Yet, if a is an object of class Array, most
people think that a[i] = 7 makes sense even though a[i] is really just a
function call in disguise (it calls Array::operator[](int), which is the
subscript operator for class Array).

 class Array {
 public:
   int size() const;
   float& operator[] (int index);
   // ...
 };

 int main()
 {
   Array a;
   for (int i = 0; i < a.size(); ++i)
     a[i] = 7;    // This line invokes Array::operator[](int)
 }

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

[8.4] What does object.method1().method2() mean?

It chains these method calls, which is why this is called method chaining.

The first thing that gets executed is object.method1().  This returns some
object, which might be a reference to object (i.e., method1() might end with
return *this;), or it might be some other object.  Let's call the returned
object objectB).  Then objectB) becomes the this object of method2().

The most common use of method chaining is in the iostream library.  E.g.,
cout << x << y works because cout << x is a function that returns cout.

A less common, but still rather slick, use for method chaining is in the Named
Parameter Idiom[10.17].

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

[8.5] How can you reseat a reference to make it refer to a different object?

No way.

You can't separate the reference from the referent.

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
identity; taking the address of a reference gives you the address of the
referent; remember: the reference is its referent).

In that sense, a reference is similar to a const pointer[18.5] such as
int* const p (as opposed to a pointer to const[18.4] such as const int* p).  In
spite of the gross similarity, please don't confuse references with pointers;
they're not at all the same.

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

[8.6] 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 pointers whenever you don't need
"reseating"[8.5].  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 pointer).

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.

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

[8.7] What is a handle to an object? Is it a pointer? Is it a reference? Is it
      a pointer-to-a-pointer? What is it?

The term handle is used to mean any technique that lets you get to another
object -- a generalized pseudo-pointer.  The term is (intentionally) ambiguous
and vague.

Ambiguity is actually an asset in certain cases.  For example, during early
design you might not be ready to commit to a specific representation for the
handles.  You might not be sure whether you'll want simple pointers vs.
references vs. pointers-to-pointers vs. references-to-pointers vs. integer
indices into an array vs. strings (or other key) that can be looked up in a
hash-table (or other data structure) vs. database keys vs. some other
technique.  If you merely know that you'll need some sort of thingy that will
uniquely identify and get to an object, you call the thingy a Handle.

So if your ultimate goal is to enable a glop of code to uniquely
identify/look-up a specific object of some class Fred, you need to pass a Fred
handle into that glop of code.  The handle might be a string that can be used
as a key in some well-known lookup table (e.g., a key in a
std::map<std::string,Fred> or a std::map<std::string,Fred*>[33.2]), or it might
be an integer that would be an index into some well-known array (e.g.,
Fred* array = new Fred[maxNumFreds][16.10]), or it might be a simple Fred*, or
it might be something else.

Novices often think in terms of pointers, but in reality there are downside
risks to using raw pointers.  E.g., what if the Fred object needs to move? How
do we know when it's safe to delete the Fred objects? What if the Fred object
needs to (temporarily) get serialized on disk? etc., etc.  Most of the time we
add more layers of indirection to manage situations like these.  For example,
the handles might be Fred**, where the pointed-to Fred* pointers are guaranteed
to never move but when the Fred objects need to move, you just update the
pointed-to Fred* pointers.  Or you make the handle an integer then have the
Fred objects (or pointers to the Fred objects) looked up in a
table/array/whatever.  Or whatever.

The point is that we use the word Handle when we don't yet know the details of
what we're going to do.

Another time we use the word Handle is when we want to be vague about what
we've already done (sometimes the term magic cookie is used for this as well,
as in, "The software passes around a magic cookie that is used to uniquely
identify and locate the appropriate Fred object").  The reason we (sometimes)
want to be vague about what we've already done is to minimize the ripple effect
if/when the specific details/representation of the handle change.  E.g.,
if/when someone changes the handle from a string that is used in a lookup table
to an integer that is looked up in an array, we don't want to go and update a
zillion lines of code.

To further ease maintenance if/when the details/representation of a handle
changes (or to generally make the code easier to read/write), we often
encapsulate the handle in a class.  This class often overloads operators
operator-> and operator*[13] (since the handle acts like a pointer, it might as
well look like a pointer).

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

User Contributions:

Comment about this article, ask questions, or add new information about this topic:

CAPTCHA




Part1 - Part2 - Part3 - Part4 - Part5 - Part6 - Part7 - Part8 - Part9 - Part10 - Part11 - Part12 - Part13 - Part14

[ Usenet FAQs | Web FAQs | Documents | RFC Index ]

Send corrections/additions to the FAQ Maintainer:
cline@parashift.com (Marshall Cline)





Last Update March 27 2014 @ 02:11 PM