Initialising a virtual class from a byte array using memcpy
<p>My app receives a <code>byte[]</code> via the network which contains the memberwise representation of a fixed-size struct which is out of my control. Let's call it <code>Data</code>:</p>

<pre><code>struct Data {
  int id;
  int count;
}
</code></pre>

<p>This worked fine:</p>

<pre><code>char buffer[]; // filled with bytes from the network...

Data data;
memcpy(&amp;data, data, sizeof(Data));
</code></pre>

<p>Now, I want to make the <code>Data</code> type inherit from a class with a (pure) virtual function:</p>

<pre><code>struct Data : public SomethingVirtual {
  int id;
  int count;
}
</code></pre>

<p>And the above code no longer works. For a virtual class, the first N bytes of the instance appear to contain a pointer to the vtable, and so the data is offset.</p>

<p>I could increase the pointer for the call to <code>memcpy</code>, but I'm now wondering if this approach is misguided. I would like to avoid having too many layers of indirection or memory copying if possible. Also the approach should work across architectures and compilers ideally, although I'm primarily targeting i686 using g++.</p>

<p>What is a good solution to this problem?</p>
