Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are essentially three options:</p> <ol> <li><p>Everybody is free to specify the initial name and health of an <code>Enemy</code>, which accepts both as parameters in its (public) constructor.</p></li> <li><p>The <code>Enemy</code> class constructor maps an 'Enemy ID' to the appropriate values of the properties. The problems in this approach come when you need to verify the validity of the 'Enemy ID' and/or the presence of the mapping, while also using initialiser-lists for the properties. This is typically solved by adding a dummy member/base-class, which is initialised by calling a verification function.<br> This would typically look like this:</p></li> </ol> <pre><code> class Enemy { bool dummy_must_be_first; public: Enemy(int type) : dummy_must_be_first(validate(type), name(properties[type].name), health(properties[type].health) {} private: bool validate(int type) { // ensure properties is initialised and verify type is within range... // on failure, throw an exception return true; } string name; int health; }; </code></pre> <ol> <li>You use a factory function to perform the mapping between an 'Enemy ID' and the properties that are used to initialise the <code>Enemy</code> object.</li> </ol> <p>There is no need to have a separate factory class. For this, a factory-method would be sufficient:</p> <pre><code>class Enemy { private: Enemy(string name_, int health_) : name(name_), health(health_) {} string name; int health; public: static auto_ptr&lt;Enemy&gt; createEnemy(int type) { // ensure properties is initialised and verify type is within range... return auto_ptr&lt;Enemy&gt;(new Enemy(properties[type].name, properties[type].health)); } }; </code></pre>
 

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