Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>C++</strong></p> <p>There is a difference between </p> <pre><code>ClassType t(initialization arguments); </code></pre> <p>and </p> <pre><code>ClassType * pt; </code></pre> <p>The latter doesn't need to be initialized (set to NULL). The former does. Think of it as an integer. You can't have an int without a value, <strong>BUT</strong> you can have an int pointer without a value.</p> <p>So when you have:</p> <pre><code>class ClassType { OtherClass value; OtherClass * reference; }; </code></pre> <p>Then the declaration:</p> <pre><code>ClassType object; </code></pre> <p>automatically creates an instance of <code>OtherClass</code> in <code>value</code>. Therefore, if <code>OtherClass</code> has initialization, it must be done in the <code>ClassType</code> constructor. However, <code>reference</code> is just a pointer (address in memory) and can remain uninitialized. If you want an instance of <code>OtherClass</code> you must use</p> <pre><code>object.reference = new OtherClass(initialization arguments); </code></pre> <p><strong>Java</strong></p> <p>There is only </p> <pre><code>class ClassType { OtherClass reference; } </code></pre> <p>This is equivalent to a pointer in C++. In this case when you do:</p> <pre><code>ClassType object = new ClassType(); </code></pre> <p>You don't automatically create an instance of <code>OtherClass</code>. Therefore, you don't have to initialize anything in the constructor unless you want to. When you want an object of <code>OtherClass</code> you can use</p> <pre><code>object.reference = new OtherClass(); </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