Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: A Typical Class Layout

📅 2010-Sep-07 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ classes, cpp ⬩ 📚 Archive

How the class is laid out in the header file is important for understanding it. This is the typical layout of the C++ classes I write these days:

// Foo.h
#ifndef FOO_H
#define FOO_H

// Headers
#include "Bar.h"

// Forward Declarations
class Joe;

// The Class
class Foo
{
    ////
    // Public Members
    ////

public:

    // *** Types

    typedef int FooValType;
    enum FooItemType
    {
        FOO_ITEM_0,
        // ...
    };

    // *** Methods

    // Constructors-Destructors
    Foo();
    ~Foo();

    // Get-Set-ers
    FooValType val() const;

    // Other methods
    void process( const Joe& ) const;

    // Friends
    friend std::ostream& operator << ( std::ostream&, const Foo& );

    ////
    // Private Members
    ////

private:

    // *** Data

    FooValType _val;

    // *** Methods

    void _process() const;
};

// *** Inline Functions

inline const FooValType& Foo::val() const
{
    return _val;
}

#endif // FOO_H

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧