title: How to call generic struct in C++
body: <p>I'm trying to make a class in which we can encode and decode different structs from and to a char*.</p>
  
  <p>I'm doing this the following way I've made an abstract 
  generic class called CANgenericMsg with CANgenericMsg.cpp being:</p>
  
  <pre><code>#include "CANgenericMsg.h"
  
  CANgenericMsg::CANgenericMsg() {
       // TODO Auto-generated constructor stub
  
  }
  
  void CANgenericMsg::decode(char* chars) {
      CANgenericMsg::str* data = reinterpret_cast&lt;CANgenericMsg::str*&gt;(chars);
      structure = *data;
  }
  
  char* CANgenericMsg::encode() {
       return reinterpret_cast&lt;char*&gt;(&amp;structure);
  }
  
  
  CANgenericMsg::~CANgenericMsg() {
      // TODO Auto-generated destructor stub
  }
  </code></pre>
  
  <p>And with header:</p>
  
  <pre><code>class CANgenericMsg {
  public:
      CANgenericMsg();
      void decode(char* chars);
      virtual ~CANgenericMsg();
      char* encode();
      virtual struct str structure;
  };
  </code></pre>
  
  <p>This class is extended by real classes such as CANintegermsg, in which the constructor of this class inits the struct:</p>
  
  <pre><code>class CANintegermsg: public CANgenericMsg {
  public:
       CANintegermsg(int i);
       virtual ~CANintegermsg();
  
      struct str {
          unsigned short int my_int;
      } structure;
  };
  </code></pre>
  
  <p>The idea being that you can set a specific struct type in each extended class. The problem is that C++ doesn't recognize virtual structs. I could move the encode and decode functions to each extended class, but as there are a lot of them, this would result in code duplication. Does there exist a neat way to be able to use the encode and decode functions like this?</p>