Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I have polymorphic containers with value semantics in C++?
    text
    copied!<p>As a general rule, I prefer using value rather than pointer semantics in C++ (ie using <code>vector&lt;Class&gt;</code> instead of <code>vector&lt;Class*&gt;</code>). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects.</p> <p>Unfortunately, value collections don't work when you want to store a variety of object types that all derive from a common base. See the example below.</p> <pre><code>#include &lt;iostream&gt; using namespace std; class Parent { public: Parent() : parent_mem(1) {} virtual void write() { cout &lt;&lt; "Parent: " &lt;&lt; parent_mem &lt;&lt; endl; } int parent_mem; }; class Child : public Parent { public: Child() : child_mem(2) { parent_mem = 2; } void write() { cout &lt;&lt; "Child: " &lt;&lt; parent_mem &lt;&lt; ", " &lt;&lt; child_mem &lt;&lt; endl; } int child_mem; }; int main(int, char**) { // I can have a polymorphic container with pointer semantics vector&lt;Parent*&gt; pointerVec; pointerVec.push_back(new Parent()); pointerVec.push_back(new Child()); pointerVec[0]-&gt;write(); pointerVec[1]-&gt;write(); // Output: // // Parent: 1 // Child: 2, 2 // But I can't do it with value semantics vector&lt;Parent&gt; valueVec; valueVec.push_back(Parent()); valueVec.push_back(Child()); // gets turned into a Parent object :( valueVec[0].write(); valueVec[1].write(); // Output: // // Parent: 1 // Parent: 2 } </code></pre> <p>My question is: Can I have have my cake (value semantics) and eat it too (polymorphic containers)? Or do I have to use pointers?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload