Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Complex logic and constructor do not always mix well, and there are strong proponents against doing heavy work in a constructor (with reasons).</p> <p>The cardinal rule is that the constructor should yield a fully usable object.</p> <pre><code>class Vector { public: Vector(): mSize(10), mData(new int[mSize]) {} private: size_t mSize; int mData[]; }; </code></pre> <p>It does not mean a fully initialized object, you may defer some initialization (think lazy) as long as the user does not have to think about it.</p> <pre><code>class Vector { public: Vector(): mSize(0), mData(0) {} // first call to access element should grab memory private: size_t mSize; int mData[]; }; </code></pre> <p>If there is heavy work to be done, you might choose to proceed with a builder method, that will do the heavy work prior to calling the constructor. For example, imagine retrieving settings from a database and building a setting object.</p> <pre><code>// in the constructor Setting::Setting() { // connect // retrieve settings // close connection (wait, you used RAII right ?) // initialize object } // Builder method Setting Setting::Build() { // connect // retrieve settings Setting setting; // initialize object return setting; } </code></pre> <p>This builder method is useful if postponing the construction of the object yields a significant benefit. From example if the objects grab a lot of memory, postponing the memory acquisition after tasks that are likely to fail may not be a bad idea.</p> <p>This builder method implies Private constructor and Public (or friend) Builder. Note that having a Private constructor imposes a number of restrictions on the usages that can be done of a class (cannot be stored in STL containers, for example) so you might need to merge in other patterns. Which is why this method should only be used in exceptional circumstances.</p> <p>You might wish to consider how to test such entities too, if you depend on an external thing (file / DB), think about Dependency Injection, it really helps with Unit Testing.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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