Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you make it a global object, then everyone has access to it, and anyone can use it without calling <code>getInstance()</code>. If so, then what is the purpose of <code>getInstance()</code> then? First time, you will call it to create the instance, then you wouldn't be required to call <code>getInstance()</code>, since after the first call, you can directly use <code>instance</code>.</p> <p>A <code>private</code> <em>static</em> instance gives you more control how it can be accessed: only through by calling <code>getInstance()</code>. </p> <p>Now why you get <code>multiple definition of instance</code> error when compiling your code? Its because you've defined the global object in the header file itself, which is included in multiple <code>.cpp</code> files. This causes multiple definitions of the object, one definition in each translation unit (.<code>obj</code> file).</p> <p>What you actually should be doing is this:</p> <pre><code>//Singleton.h class Singleton { private : Singleton(); Singleton(const Singleton &amp;); ~Singleton(); static Singleton* instance; //declaration of static member! public: static Singleton* getInstance(); //.. }; </code></pre> <p>And then define the <code>static</code> member in the <code>.cpp</code> file as:</p> <pre><code>//Singleton.cpp Singleton *Singleton::instance = 0; //definition should go in .cpp file! Singleton::Singleton() {} Singleton* Singleton::getInstance() { if ( instance == 0 ) instance = new Singleton(); return instance; } //... </code></pre>
    singulars
    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