title: How can I send pointer members of a class through a QDataStream?
body: <p>I have a user-defined class, say, <code>MyClass</code>. Suppose its definition is as follows:</p>
  
  <pre><code>class MyClass
  {
      int a;
      int *b;
      Base *c;
  };
  </code></pre>
  
  <p>where I have</p>
  
  <pre><code>class Base
  {
      int base_data;
      public:
          Base(int) { //implementation }
          virtual void some_func() = 0;
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>class Derived1 : public Base
  {
      int derived_1;
      public:
          Derived1(int) { //implementation }
          virtual void some_func() { //implementation }
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>class Derived2 : public Base
  {
      int derived_2;
      public:
          Derived2(int) { //implementation }
          virtual void some_func() { //implementation }
  }
  </code></pre>
  
  <p>I would like to send an object of this class to a <code>QTcpsocket</code>. As per <a href="https://stackoverflow.com/a/5894744/5987698">this answer</a>, I could use a <code>QDataStream</code>, and with the help of <a href="https://stackoverflow.com/a/2473395/5987698">this</a>, I have implemented as follows:</p>
  
  <pre><code>friend QDataStream&amp; operator&lt;&lt;(QDataStream&amp;, const MyClass&amp;);
  friend QDataStream&amp; operator&gt;&gt;(QDataStream&amp;, MyClass&amp;);
  </code></pre>
  
  <p>in the class declaration, and am considering defining it as:</p>
  
  <pre><code>QDataStream&amp; operator&lt;&lt;(QDataStream &amp;stream, const MyClass &amp;obj)
  {
      stream &lt;&lt; obj.a;
      stream &lt;&lt; obj.(*b);
      stream &lt;&lt; obj.(*Base); // assume QDataStream has been overloaded for Base already
  }
  </code></pre>
  
  <p>As I need to send the data, I am dereferencing the pointers and sending the data it points to.</p>
  
  <p>Is this the correct way to do this?</p>
  
  <p>If I do send it this way, I am not able to understand how I can recreate the object at the receiving end. I am considering:</p>
  
  <pre><code>QDataStream&amp; operator&lt;&lt;(QDataStream &amp;stream, MyClass &amp;obj)
  {
      stream &gt;&gt; obj.a;
      b = new int;
      stream &gt;&gt; obj.(*b);
      Base = new //what?
      stream &gt;&gt; obj.(*Base); // assume QDataStream has been overloaded for Base already
  }
  </code></pre>
  
  <p>For an <code>int</code> pointer, I can create a <code>new int</code> and assign the incoming value to it. But what about a pointer of type <code>Base</code>? I don't know if it is of type <code>Derived1</code> or <code>Derived2</code>.</p>
  
  <p>How do I handle this?</p>
  
  <p>Is there any other way to send a class object, if there is no solution here?</p>
  
  <p>Thank you.</p>