I am trying to implement a message that contains sub messages. The format would look something like the following.

Message: Field 1, field 2, ..., sub type, buffer

Depending on the sub type there could be one of several ways to interpret the buffer. Some of the sub messages might look something like the following.

Sub type 1: Field 1, field 2, ..., sub sub type

Sub sub type 1: Field 1, field 2, ..., data buffer

What I'm not sure about is how to structure my code in order to best represent the structure that exists. The sub messages don't inherit from each other, so I don't want to use inheritance.

Each of the fields represented in the message could be anywhere from 1 to 31 bits in length. Ideally I would like to have a struct/class with all unsigned int data types to make it easy to interact with the data and let the serialize/deserialize methods handle packing and unpacking the data before/after sending/receiving the buffer on the network.

  • It sounds like you are talking about a union of structs (classes).
    – msw
    Commented Mar 20, 2017 at 22:13
  • 1
    Did you look at how TCP/IP does it? It is done that way and is very successful because it is one of the easiest ways to do it. LAYERS.
    – Dunk
    Commented Mar 20, 2017 at 22:16
  • This sounds like you're reinventing the wheel; have you seen Google Protocol Buffers ? It may solve many of your problems for you. Commented Mar 21, 2017 at 20:49

1 Answer 1


You may structure your object classes using composition. This means referring in your message object to another object that will hold the sub type.

struct Message { 
    unsigned message_type; 
    unsigned field1; 
    unsigned fieldn; 
    Message *sub_message;  // if there's a dedicated type for this

If any sub type could have sub sub types, which may have sub sub sub types, and so on, then you should consider using a composite design pattern.

If your payload contains mostly unsigned integers, then you could make your classes easier to use with an array or a vector of unsigned integer. This can help to avoid redundant code: instead of copy-pasting a lot of code to replicate similar behavior but for each field (for example print it on the screen, or serialize it), you could use a loop instead.

struct Message { 
    unsigned message_type; 
    vector<unsigned> field; // with a vector, the number of field could be variable  
    Message *sub_message;  // if there's a dedicated type for this

You could then define somewhere some rules, like for example the number of fields to use for each specific subtype.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.