C++ Guidelines

P

Pete Vidler

Hi Folks,

I'm wondering if there is a compilation of C++ guidelines out there
anywhere. Here are some of the ones I've picked up so far (as examples):

- Functions should fit on one screen, from various sources.

- Non-leaf classes should be abstract (have pure virtual methods), from
More Effective C++, Item 33.

- Virtual methods should be private by default and protected if they
need access to a base classes version (except for the destructor, of
course), from http://www.gotw.ca/publications/mill18.htm.

- Header files should be self contained, from various sources.

- Destructors for base classes should be either virtual or protected.

I think I've probably missed (or never heard of) quite a few more.
Anyone know where I can find such things? Or have some guidelines of
their own to share?

-- Pete
 
P

Phlip

Pete said:
I'm wondering if there is a compilation of C++ guidelines out there
anywhere. Here are some of the ones I've picked up so far (as examples):

- Functions should fit on one screen, from various sources.

Functions should have 1 to 5 activities. In higher level languages this
translates to 1 to 5 statements, but C++ requires a lot of rigging and
piping.
- Non-leaf classes should be abstract (have pure virtual methods), from
More Effective C++, Item 33.

The corpus of Addison Wesley [Longman]'s C++ and theory books form the
pinacle of known style. Try /Design Patterns/, /Large Scale C++ Software
Design/, and /Refactoring/.
- Virtual methods should be private by default and protected if they
need access to a base classes version (except for the destructor, of
course), from http://www.gotw.ca/publications/mill18.htm.

Also try /Exceptional C++/, by Herb Sutter.
- Header files should be self contained, from various sources.

The implication here is you can always add a new #include "thing.h", and it
takes care of itself. You never need to add another #include above it.
/Large Scale/ covers this in great detail.
- Destructors for base classes should be either virtual or protected.

Never heard of the "protected" one.
I think I've probably missed (or never heard of) quite a few more.
Anyone know where I can find such things? Or have some guidelines of
their own to share?

These guidelines occupy a spectrum. At one end, we have requirements that
C++'s minimal expression enforces. Thou shalt make all destructors virtual
unless profiling reveals the need to remove a class's 'vtable'. At the other
end we have team specific patterns and behaviors. For example, one team may
adopt STL for all collection classes, and another may have an alternative
library, hence should not use STL. But we should recommend STL when writing
books for AW.
 
D

Daniel T.

Pete Vidler said:
I'm wondering if there is a compilation of C++ guidelines out there
anywhere. Here are some of the ones I've picked up so far (as examples):

- Functions should fit on one screen, from various sources.

- Non-leaf classes should be abstract (have pure virtual methods), from
More Effective C++, Item 33.

- Virtual methods should be private by default and protected if they
need access to a base classes version (except for the destructor, of
course), from http://www.gotw.ca/publications/mill18.htm.

- Header files should be self contained, from various sources.

- Destructors for base classes should be either virtual or protected.

I think I've probably missed (or never heard of) quite a few more.
Anyone know where I can find such things? Or have some guidelines of
their own to share?

Check out these two books:
"Large-Scale C++ Software Design" by John Lakos
"Object-Oriented Design Heuristics" by Arthur J. Riel

This site may also be helpful:
<http://www.chris-lott.org/resources/cstyle/>
 
P

Pete Vidler

Daniel T. wrote:
[snip]
Check out these two books:
"Large-Scale C++ Software Design" by John Lakos

I've heard of this one, but isn't it seriously out of date? I've also
heard that he has some strange guidelines like not using namespaces?
"Object-Oriented Design Heuristics" by Arthur J. Riel

I'll look into it, thanks.

Most of the links there appear to be documents detailing naming
conventions and recommending a given style for the placement of braces.
I'm looking for more along the lines of design guidelines like I posted
(there was one good page there though, thanks).

I don't really need the basic stuff (I know most of them), but I am
looking for more advanced guidelines (with justifications, like the one
about making virtual methods private).

Thanks,
-- Pete
 
C

Claudio Puviani

Pete Vidler said:
I'm wondering if there is a compilation of C++ guidelines out there
anywhere.

http://search.barnesandnoble.com/booksearch/isbnInquiry.asp?isbn=0521893089

It's basically an extension of what used to be Rogue Wave's guidelines. No
one will agree with every guideline, but they're mostly reasonable.
Here are some of the ones I've picked up so far (as examples):

- Functions should fit on one screen, from various sources.

That's really a side-effect of a few more fundamental principles, such as
"maximize cohesion" and "modularize where reasonable." A function that is
very large should raise flags, but there are rare instances where it's
entirely justified to have even extremely large functions (as anyone who's
ever used YACC will testify).
- Header files should be self contained, from various sources.

This one should be shredded or rephrased. Header files have dependencies
just like any other software component, and so can rarely be self-contained.

Claudio Puviani
 
P

Pete Vidler

Claudio Puviani wrote:
[snip]
http://search.barnesandnoble.com/booksearch/isbnInquiry.asp?isbn=0521893089

It's basically an extension of what used to be Rogue Wave's guidelines. No
one will agree with every guideline, but they're mostly reasonable.

Interesting.. but the summary says it deals with formatting, naming,
documentation, etc. I was looking for design guidelines along the lines
of those that I posted. Am I correct in assuming it doesn't cover such
issues?
That's really a side-effect of a few more fundamental principles, such as
"maximize cohesion" and "modularize where reasonable." A function that is
very large should raise flags, but there are rare instances where it's
entirely justified to have even extremely large functions (as anyone who's
ever used YACC will testify).

Yes that example was more basic than I really wanted. Ignore it, I'm far
more interested in guidelines similar to the others that I posted.
This one should be shredded or rephrased. Header files have dependencies
just like any other software component, and so can rarely be self-contained.
[snip]

Obviously if a header file is from a library then the library must be
linked to. I meant from a compiler point of view.

More specifically that it should forward declare or #include everything
it requires to compile. I'm fairly sure most people would understand
this from "self contained", but I suppose I should have been more precise.

-- Pete
 
D

David Harmon

On Sat, 10 Apr 2004 16:16:23 +0100 in comp.lang.c++, Pete Vidler
Most of the links there appear to be documents detailing naming
conventions and recommending a given style for the placement of braces.
I'm looking for more along the lines of design guidelines like I posted

Well, arguing over the placement of braces has less potential for harm
than many of the design guidelines I have seen.
 
P

Pete Vidler

David Harmon wrote:
[snip]
Well, arguing over the placement of braces has less potential for harm
than many of the design guidelines I have seen.

Yes, but there's no potential for learning anything with
brace-placement. You can already see the possibilities.

-- Pete
 
D

Daniel T.

Pete Vidler said:
Daniel T. wrote:
[snip]
Check out these two books:
"Large-Scale C++ Software Design" by John Lakos

I've heard of this one, but isn't it seriously out of date? I've also
heard that he has some strange guidelines like not using namespaces?
"Object-Oriented Design Heuristics" by Arthur J. Riel

I'll look into it, thanks.

Most of the links there appear to be documents detailing naming
conventions and recommending a given style for the placement of braces.
I'm looking for more along the lines of design guidelines like I posted
(there was one good page there though, thanks).

I don't really need the basic stuff (I know most of them), but I am
looking for more advanced guidelines (with justifications, like the one
about making virtual methods private).

Try the articles at this site:
<http://tinyurl.com/2tt4h >
 
S

Steven T. Hatton

Pete said:
David Harmon wrote:
[snip]
Well, arguing over the placement of braces has less potential for harm
than many of the design guidelines I have seen.

Yes, but there's no potential for learning anything with
brace-placement. You can already see the possibilities.

-- Pete
This looks like food for thought. I'm not endorsing, just passing it on:
http://www.possibility.com/Cpp/CppCodingStandard.html#cuh

You may already be aware of this. It's general, but certainly has a link or
five that will be relevant:
http://www.fz-juelich.de/zam/cxx/extmain.html
 
C

Claudio Puviani

Pete Vidler said:
Claudio Puviani wrote:
[snip]
http://search.barnesandnoble.com/booksearch/isbnInquiry.asp?isbn=0521893089

It's basically an extension of what used to be Rogue
Wave's guidelines. No one will agree with every
guideline, but they're mostly reasonable.

Interesting.. but the summary says it deals with formatting,
naming, documentation, etc. I was looking for design
guidelines along the lines of those that I posted. Am I
correct in assuming it doesn't cover such issues?

It has rudimentary design guidelines as well. The formatting section is just
a few pages, and the least interesting at that.

Here's a list of books I posted once before that would give you what you
need:

For general inheritance guidelines, strategies, pitfalls, etc. (in no
particular order):

"C++ Primer" by Lippman and Lajoie
"Effective C++" by Scott Meyers
"More Effective C++" by Scott Meyers
"Effective STL" by Scott Meyers
"Exceptional C++" by Herb Sutter
"More Exceptional C++" by Herb Sutter
"Large Scale C++ Software Design" by John Lakos
"Designing and Coding Reusable C++" by Carroll and Ellis
"Ruminations on C++" by Koenig and Moo
"Enough Rope to Shoot Yourself in the Foot" by Allen Holub
"C++ Strategies and Tactics" by Bob Murray
"C++ Programming Style" by Tom Cargill
"C++ in Action" by Bartosz Milewski
"C++ Code Capsules" by Chuck Allison
and even the old but excellent "Advanced C++" by James Coplien

Claudio Puviani
 
C

Claudio Puviani

Pete Vidler said:
Daniel T. wrote:
[snip]
Check out these two books:
"Large-Scale C++ Software Design" by John Lakos

I've heard of this one, but isn't it seriously out of date?

Good information is never out of date. Knuth's "Art of Computer Programming"
series was first published in 1968 and anyone would get shot for calling it
out of date. A discriminating reader can easily filter out what's still
relevant and what isn't. Those who can't are probably not ready to read the
book yet.
I've also heard that he has some strange guidelines like
not using namespaces?

EVERY book that proposes guidelines has strange guidelines. Or at least, we
perceive them as being strange because the author comes from a different
background. The thing to remember is that guidelines are NOT rules and
should be followed only if they make sense in a given context. Taking John's
admonition against using namespaces out of context is less than meaningless.
What he actually suggested, which anyone who actually read the book would
know, is to wait until namespace support was more stable and universal
before using it. At the time the book was written, there were quite a few
compilers that didn't support namespaces or that supported them incorrectly.

The truth is that whether or not one appreciates John's style or agrees with
every detail, anyone who hasn't read the book is a step behind those who
have with regard to physical design.

Claudio Puviani
 
S

Siemel Naran

I'm wondering if there is a compilation of C++ guidelines out there
anywhere. Here are some of the ones I've picked up so far (as examples):

We should have guidelines and suggestions. Suggestions are weaker than
guidelines.

- Functions should fit on one screen, from various sources.

A suggestion. Functions could easily be longer once you add blank lines and
comments. Functions that are pretty straightforward but long, say because
they have to read in a lot of input arguments, are fine, it seems to me. As
soon as you start to process input arguments and do stuff, that's when the
long function should raise a bell.

A related concept is that functions should have few input arguments.

- Non-leaf classes should be abstract (have pure virtual methods), from
More Effective C++, Item 33.

A suggestion. Sometimes we want a reasonable default behavior which clients
can then override. Requring the above as a guideline imposes too much
design burden on the project and could cause it to run out of budget.

- Virtual methods should be private by default and protected if they
need access to a base classes version (except for the destructor, of
course), from http://www.gotw.ca/publications/mill18.htm.

They should be private or protected. Often, a virtual function will call
the same function in the base class and do some additional processing, as
for example a virtual equal function. I generally call the private virtual
functions myaction, and the protected ones doaction.

- Header files should be self contained, from various sources.
What?


- Destructors for base classes should be either virtual or protected.

No. Classes meant to not be derived from may have public non-virtual
destructors, such as std::vector.

I think I've probably missed (or never heard of) quite a few more.
Anyone know where I can find such things? Or have some guidelines of
their own to share?

There are lots of others.
 
P

Pete Vidler

Siemel Naran wrote:
[snip]
We should have guidelines and suggestions. Suggestions are weaker than
guidelines.

I see no difference. I am just as free to ignore either. The purpose of
my post was to find out what various people (or websites, books, etc)
might have to say about what they consider to be "good" design.
A suggestion. Functions could easily be longer once you add blank lines and
comments. Functions that are pretty straightforward but long, say because
they have to read in a lot of input arguments, are fine, it seems to me. As
soon as you start to process input arguments and do stuff, that's when the
long function should raise a bell.

A related concept is that functions should have few input arguments.

I usually adhere to this one because I find that I make fewer mistakes
if the entire method is immediately available. I'm not sure how this
relates to the number of arguments, but I'll accept that as a suggestion.
A suggestion. Sometimes we want a reasonable default behavior which clients
can then override. Requring the above as a guideline imposes too much
design burden on the project and could cause it to run out of budget.

You can have pure virtual methods with an implementation. Note that
abstract in this case means simply that the class has >=1 pure virtual
method, not that they are all pure virtual (my interpretation of that
source).

Having tried this in a recent project, it really isn't that much of a
burden (most of my classes were close anyway).
They should be private or protected. Often, a virtual function will call
the same function in the base class and do some additional processing, as
for example a virtual equal function. I generally call the private virtual
functions myaction, and the protected ones doaction.

Aside from the naming that is exactly what I posted? Except that I'm not
too sure about having a virtual "equal function".

I posted more info on this elsewhere in the thread. Basically I just
meant that you should be able to include the header at the very top of
your source file and not get errors.
No. Classes meant to not be derived from may have public non-virtual
destructors, such as std::vector.

Umm.. since when is std::vector a base class? A base class is one that
has been (or is intended to be) derived from (IMO).

[snip]
There are lots of others.

That doesn't help. The entire purpose of my post was to get people to
post some (or post links, etc).

-- Pete
 
P

Pete Vidler

Claudio Puviani wrote:
[snip]
It has rudimentary design guidelines as well. The formatting section is just
a few pages, and the least interesting at that.

But how rudimentary? I can't possibly buy a book on the off-chance it
might contain what I need (I couldn't afford it). I can't find any
actual reviews of the book, and the only info in the summary suggets the
book is about formatting/naming conventions (useless to me).
Here's a list of books I posted once before that would give you what you
need:

Cool, thanks. I have read most of these, but there are one or two on
that list I haven't seen before.

-- Pete
 
P

Pete Vidler

Claudio Puviani wrote:
[snip]
Good information is never out of date. Knuth's "Art of Computer Programming"
series was first published in 1968 and anyone would get shot for calling it
out of date. A discriminating reader can easily filter out what's still
relevant and what isn't. Those who can't are probably not ready to read the
book yet.

Right, but if it almost pre-dates namespaces there is going to be a lot
missing from it -- am I right? Templates and such?

Knuth's book is somewhat different, the concepts it addresses are not
based on a language that has changed a great deal over time. It isn't
even based on a real language at all (unless you count a few
implementations by enthusiasts).
EVERY book that proposes guidelines has strange guidelines. Or at least, we
perceive them as being strange because the author comes from a different
background. The thing to remember is that guidelines are NOT rules and
should be followed only if they make sense in a given context.
[snip]

I have to disagree. I have read many guideline type books (the
"Effective" and "Exceptional" books to name five) that I have had no
disagreements with at all. I don't believe I come from the same
background as the authors.
The truth is that whether or not one appreciates John's style or agrees with
every detail, anyone who hasn't read the book is a step behind those who
have with regard to physical design.
[snip]

That cannot possibly be true. If we haven't read the book we might still
know everything it contains (through other sources) and not realise it.
And for all I know, if I do read it much of its contents might be
obvious to me.

-- Pete
 
J

Joe Gottman

Phlip said:
Never heard of the "protected" one.

If you have code like
class D : public B {};
B * pb = new D();
delete pb;

and D does not have a virtual destructor, undefined behavior results. There
are two possible solutions to this. If you give B a virtual destructor,
the correct destructor is called by delete. Alternatively, if you give B a
protected destructor the "delete pb;" statement will fail to compile. Thus,
you give a class a protected destructor when you don't want anybody deleting
a derived class through a pointer to the base class.

Joe Gottman
 
P

Phlip

Joe said:
If you have code like
class D : public B {};
B * pb = new D();
delete pb;

and D does not have a virtual destructor, undefined behavior results. There
are two possible solutions to this. If you give B a virtual destructor,
the correct destructor is called by delete. Alternatively, if you give B a
protected destructor the "delete pb;" statement will fail to compile. Thus,
you give a class a protected destructor when you don't want anybody deleting
a derived class through a pointer to the base class.

The rules for 'protected' roughly mean "anything you could reference thru
'this' (plus statics)".

So 'delete this' breaks your protection.
 
P

Phlip

Pete said:
Right, but if it almost pre-dates namespaces there is going to be a lot
missing from it -- am I right? Templates and such?

What you need is not in any book.

From Lakos, you will learn dozens of very valid guidelines. For example, the
first #include line inside foo.cpp should always be foo.h. This ensures that
foo.h can stand alone without any other header above it - no surprise
requirements.

From Knuth, you will learn how to think and reason much harder than is
usually needed. These are just warmups for thinking outside the box, and
going off one of Knuth's diagrams.

Also (if Pete Becker isn't around and it's safe to mention this), read the
Sedgewick books on algorithms.
Knuth's book is somewhat different, the concepts it addresses are not
based on a language that has changed a great deal over time. It isn't
even based on a real language at all (unless you count a few
implementations by enthusiasts).

So is /Design Patterns/. There is no book that says "How can Pete Vidler use
the latest language features safely". Not even /Modern C++ Design/ by Andrei
Alexandrescu, which covers templates in greater detail than mere mortals
need.
I have to disagree. I have read many guideline type books (the
"Effective" and "Exceptional" books to name five) that I have had no
disagreements with at all. I don't believe I come from the same
background as the authors.

This misses the point. Lakos says "I analyzed my huge project like this, and
I found these conclusions". Many of his recommendations are perfect, but
many are simply the result of his project. Learn from how he analyzed the
project.
 
S

Siemel Naran

Aside from the naming that is exactly what I posted? Except that I'm not
too sure about having a virtual "equal function".

bool C::eek:perator==(const C& that) const {
if (typeid(*this) != typeid(that)) return false;
return this->doequal(that);
}

bool C2::doequal(const C& arg) {
const C2& that = static_cast<const C2&>(arg);
...
}

Here C2 derives from C, and C::doequal is pure virtual. Though a double
dispatch mechanism might more elegant. Granted an operator== doesn't always
make sense.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top