Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since during last hour nobody got it right... Actually @taylorc93 was the closest, but he still managed to make a mistake.</p> <p>So, back to the question. CakePacket is supposed to store the Cakes, right? <code>Cake</code> is a base class, but it has no virtual methods. Using pointers is completely unnecessary in this scenario, and the only thing you have to do is to use some container. Now, which one you choose depends on desired usage of CakePacket. Let's write it in general way, then:</p> <pre><code>class CakePacket { // this can be whatever you might need; a list, set, unordered_set... // vector is a reasonable default vector&lt;Cake&gt; cakes; public: // We'll also need a way to add them: void addCake(Cake cake) { // I'm moving the parameter to avoid copying // refer to "move semantics" to understand it deeper cakes.push_back(std::move(cake)); } }; </code></pre> <p>Voila! You've asked how to create a CakePacket, and it's dead simple.</p> <pre><code>CakePacket cp; cp.addCake(Cake(1)); cp.addCake(Cake(2)); cp.addCake(Cake(3)); </code></pre> <p>Of course you can move these to the constructor of <code>CakePacket</code>, but...</p> <pre><code>CakePacket cp { Cake(1), Cake(2), Cake(3), Cake(4) }; </code></pre> <p>If you want to be able to create from the array-like list, you need to provide aditional constructor taking <code>initializer_list&lt;Cake&gt;</code>, but I'll leave that as an exercise. (<em>Hint: you <strong>won't</strong> need a <code>for</code> loop</em>).</p> <h2>Is CakePacket really necessary?</h2> <p>It's a learning question, so I am not going to be picky on it, but I'd like to point out the fact how CakePacket really does... nothing, at least in its current state. Sometimes it's easier to simply use <code>std</code> container, instead of wrapping it in a whole new type. This avoids polluting the code with superfluous classes, and you'll be amazed how much functionality standard library offers you to work with its containers.</p> <h2>Caveat</h2> <p>If you try to store AppleCake in it, the <code>diameter</code> will get <em>sliced</em>, i.e. only the common part will be saved. In that case you'd need to either store the pointer to base class (using <code>boost::ptr_vector&lt;Cake&gt;</code> or <code>std::vector&lt;std::unique_ptr&lt;Cake&gt;&gt;</code>), or use something like <code>Boost.Variant</code>.</p> <h2>What you certainly <em>don't want</em> to do here</h2> <p>... is storing raw pointers. You would have to destroy each Cake added in the CakePacket dtor, which is error-prone and simply unnecessary.</p> <p>Using C-style array is also rather bad, because it constrains you with fixed size.</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