C++ Coding Guidelines

Last update: Thu Nov 13 15:54:51 2003.


See also C Coding Style for guidelines on C programming, most of which apply to C++.


Contents


"Rules"

  1. For each project or large subproject, pick a short prefix to use as a namespace for all top-level symbols.

  2. Name with increased specificity from left to right. If a superclass is called FooTable, its subclasses should be FooTableHash and FooTableLinked.

  3. Every class must have a destructor. It should be virtual if appropriate. Even pure-virtual classes should have a destructor, even if it's just an inline { }.

  4. For each class, define the default constructor, the copy constructor, and the assignment operator. If you don't want them used, make them protected and/or make them throw exceptions.

  5. Use C++ // comments wherever possible, but use C /* */ comments to the right of preprocessor directives.

  6. Member variable names should begin with underscore followed by a lowercase letter.

  7. Public methods should begin with capital letters. Protected and private methods should begin with lowercase.

  8. Public classes should begin with capital letters. Private classes should be avoided in preference to nested classes when possible.

  9. Skip two lines between functions, methods, and other major blocks of code. Skip only one line within these structures.

  10. Don't use tabs. Use spaces. They're always the same. And keep line lengths less than 80 characters.


Code Examples

  1. Headers & Implementations
    foobar.h
    // -*- C++ -*-
    // Copyright (c) 1996-1997 ABC, Inc.
    // $Id$
    //
    //        File: foobar.h
    //     Package: foo
    // Description: FOO project BAR manager header
    //
    
    #ifndef _foobar_h_
    #define _foobar_h_
    
    extern "C" {
    #include <stdio.h>
    }
    
    #ifndef _foo_h_
    # include "foo.h"
    #endif
    
    extern "C++" {
    
    class FooBar {
    public:
      FooBar(FILE *f);
    private:
      FILE           *_stream;
      unsigned char  *_buf;
    };
    
    } // extern "C++"
    
    #endif /* !_foobar_h_ */
    
    foobar.cxx
    #ifndef NORCSID
    static const char rcsid[] = "Copyright (c) 1996-1997 ABC, Inc. $Id$";
    #endif
    
    //
    // File: foobar.cxx
    // Package: foo
    // Description: FOO project BAR manager
    //
    
    extern "C" {
    #include <memory.h>
    }
    
    #ifndef _foobar_h_
    # include "foobar.h"
    #endif
    
    FooBar::FooBar(FILE *f)
    {
      _stream = f;
      _buf = new unsigned char [1024];
      memset(_buf, 0, 1024);
    }
    


    Thu Nov 13 15:54:51 2003