How to Order the Members of a C++ Class

What is the optimal order of members in a class?

As a rule of thumb you should order by size, greater to smaller. This will create the minimum padding of the structure, thus minimizing the structure size. This matters most if objects of the structure are used in a contiguous allocated memory, e.g. vector and helps a lot with cache (more objects fit in the same cache line).

Another surprising optimization demonstrated by Andrei Alexandrescu (I think was in one of CppCon) is that he brought the most accessed member first. This is faster because the offset is zero. Of course he was talking about micro-optimization, after benchmarking the hell out of the application and caring for every little strop of performance.

Order of items in classes: Fields, Properties, Constructors, Methods

According to the StyleCop Rules Documentation the ordering is as follows.

Within a class, struct or interface: (SA1201 and SA1203)

  • Constant Fields
  • Fields
  • Constructors
  • Finalizers (Destructors)
  • Delegates
  • Events
  • Enums
  • Interfaces (interface implementations)
  • Properties
  • Indexers
  • Methods
  • Structs
  • Classes

Within each of these groups order by access: (SA1202)

  • public
  • internal
  • protected internal
  • protected
  • private

Within each of the access groups, order by static, then non-static: (SA1204)

  • static
  • non-static

Within each of the static/non-static groups of fields, order by readonly, then non-readonly : (SA1214 and SA1215)

  • readonly
  • non-readonly

An unrolled list is 130 lines long, so I won't unroll it here. The methods part unrolled is:

  • public static methods
  • public methods
  • internal static methods
  • internal methods
  • protected internal static methods
  • protected internal methods
  • protected static methods
  • protected methods
  • private static methods
  • private methods

The documentation notes that if the prescribed order isn't suitable - say, multiple interfaces are being implemented, and the interface methods and properties should be grouped together - then use a partial class to group the related methods and properties together.

C#, How to simply change order of class members

There is no defined order in a CLR class; it is up to the implementation that is inspecting the metadata of the class to determine how a class is interpreted.

For example, your Excel library is probably using reflection to inspect the class you pass it and reflection makes no guarantees as to the order in which things are processed.

Other implementations such as the WCF DataContractSerializer or ProtoBuf.NET handle order through the use of DataMember.

That said, if your library can handle dynamic or anonymous types then you can use the approach detailed in the other answers. .NET seems to consistently reflect these types in the same order that they were created.

var x = new { Z = "", Y = 1, X = true };
Console.WriteLine(x.GetType().GetProperties().Select(y => y.Name));

However it should be noted that this is an implementation detail and should not be relied upon. I'd see if you library allows you to specify the mapping between properties in your class and columns in your spreadsheet otherwise you might run into weird bugs in the future!

Declaration order of types or members in c#

When you write this:

class Program
{

static readonly int A = Method();
static readonly int B = 42;
static int Method() => B;

static void Main()
{
Console.WriteLine(A); // 0
}
}

The compiler will generate a static constructor for you, which assigns the initial values to your various fields. The order of these assignments matches the order that the fields are declared in:

class Program
{

static readonly int A;
static readonly int B;

static Program()
{
A = Method();
B = 42;
}

static int Method() => B;

static void Main()
{
Console.WriteLine(A); // 0
}
}

When the static constructor runs, it's fairly clear that Method() is executed, and A assigned to, before B is assigned to. Fields have an initial value of 0, before anything is assigned to them. So Method() will return 0.

Follow the same logic for your second scenario, and you'll see how it's different.

Is order in memory guaranteed for class private members in C++?

They are guaranteed to have increasing addresses with respect to each other ([class.mem]/13):

Nonstatic data members of a (non-union) class with the same access
control
(Clause [class.access]) are allocated so that later members
have higher addresses within a class object.

Note the text I marked in bold. While it's guaranteed field2 is after field1 when they are both private, it need not be the case if they had different access control. And of course, intermediate padding is always an option.

But if you want to force the absence of padding, and they are of the same type, an array would do it:

uint64_t field[2];

It also makes &field[0] + 1 well defined, since those objects are now obviously members of the same array.

Constructor invocation order for member objects

Construction of the members happens in the order in which they are declared. This is very important for the following. If the order of declaration does not match the order in which the dependencies are used, then the program will have undefined behavior.

The initializers with which they are constructed can be specified in the member initializer list of the constructor after after a colon before the function body:

void Tree::Tree(const std::istream& input)
: height_(/* initializer for height_ */),
leaf_(/* initializer for leaf_ */)
{
//...
}

(Instead of parentheses, braces for list-initialization may also be used.)

In the initializer for leaf_, the value of height_ can be used.

Since you probably need to do some work to get height_ from the inputs, you probably want to write an extra function for that and call it for /* initializer for height_ */.



Related Topics



Leave a reply



Submit