title: How to allocate memory for an object I don't know the real type of? C++
body: <p>I want to store an object of some derived class as a property of another object.</p>
  
  <p>The problem for me is to know the size of the object to be stored, as it can be any derived class of a given base class. I cannot just allocate memory for the base class' object, right, as it's smaller. I suppose, <em>typeof</em> operator would also just give the size of the base class, right?</p>
  
  <p>Here is my sample code. Please, see the comments to understand what I mean. Excuse me for the unoriginality…</p>
  
  <pre><code>BaseA {};
  
  DerivedA1 : BaseA {public: void property() { cout &lt;&lt; 1; }};
  DerivedA2 : BaseA {public: void property() { cout &lt;&lt; 2; }};
  // etc. - several derived classes.
  
  BaseB   // Contains (or links to) an instance of class derived from BaseA.
  {
  public:
      BaseA * instanceA;
  
      BaseB (BaseA instanceAX)
      {
          // ??? =&gt; How to allocate memory for the object
          // I don't know the real type of?
          instanceA = new BaseA (instanceAX);
      }
  
      BaseB (BaseA instanceAX) { delete instanceA; }
  };
  
  main()
  {
      DerivedA1 instanceA1;
      BaseB instanceB (instanceA1);
  
      // Use "property" regardless of which derived class it belongs to.
      instanceB.instanceA-&gt;property();
  } 
  </code></pre>
  
  <p>I could store a pointer instead of the object itself, it would be easier. But I'm not sure I want to rely on the caller to retain the property object for the life of instance <em>instanceB</em>.</p>
  
  <p>Thanks!</p>