title: How to define a well made message class in C++
body: <p>At the moment I am working on a message class in C++ for data communication, e.g. over a serial port. For this question let's say I have two different messages (I do have more), e.g. a gyroscope- and a acceleration message both with calibration data and sensor values. Since I am an engineer who learned C++ for himself I had a look at my favorite C++ book and figured out that it might be useful to use a factory pattern for the message.</p>
  
  <p>So a simplified version of my header file looks like this:</p>
  
  <pre><code>#ifndef MESSAGE_H
  #define MESSAGE_H
  #include &lt;cstddef&gt;
  
  class message
  {
  public:
  
  /**
   * \brief ~message:
   *        Virtual destructor of the class message.
   */
  virtual ~message();
  
  /**
   * \brief getMessage:
   *        Creates a message (with new).
   *
   * \param[in] size  Size of the dataArray.
   * \param[in] data  Bytearray of the message.
   *
   * \return If messagetype in the Array data eqal to 0 =&gt; new GyroMessage.
   *         If messagetype in the Array data eqal to 1 =&gt; new AccelMessage.
   *         Else =&gt; new NotValidMessage.
   *
   */
  static message* getMessage(size_t size, char* data);
  
  protected:
  
  /**
   * \brief message:
   *        Default konstructor of the class message.
   *
   * \param[in] size  Size of the dataArray.
   * \param[in] data  Bytearray of the message.
   *
   */
  message(size_t size, char* data);
  
  /// Size of the dataArray.
  int size;
  /// Bytearray of the message.
  char* dataArray;
  /// Type of message.
  char messagetype;
  };
  
  #endif // MESSAGE_H
  </code></pre>
  
  <p>The clases <code>GyroMessage</code>, <code>AccelMessage</code> and <code>NotValidMessage</code> are child classes of <code>message</code>. There are two things I do not like about this pattern:</p>
  
  <p>First: If I want to add a new message, it is now enough to add a new class which is inherited form <code>message</code>, you have to add another if statement is in the static function <code>getMessage</code>.</p>
  
  <p>Second: If I want to use the data e.g. from the <code>GyroMessage</code>, I have to <code>reinterpret_cast</code> the message.</p>
  
  <p>Is there a better pattern that I could use for this purpose?</p>