Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your line <code>Class();</code> does call the constructor of the class <code>Class</code>, but it calls it in order to create a "temporary object". Since you don't use that temporary object, the line has no useful effect.</p> <p>Temporary objects (usually) disappear at the end of the expression in which they appear. They're useful for passing as function parameters, or initializing other objects. It's almost never useful to just create one in a statement alone. The language allows it as a valid expression, it's just that for most classes it doesn't do very much.</p> <p>There is no way in C++ to call a constructor on an object which has already been constructed. The lifecycle of a C++ object is one construction, and one destruction. That's just how it works. If you want to reset an object during its life, you've done the right thing, which is to call a function to reset it. Depending on your class you might not need to write one - the default assignment operator might do exactly what you need. That's when a temporary can come in handy:</p> <pre><code>Class myObject; // ... do some stuff to myObject ... myObject = Class(); </code></pre> <p>This updates <code>myObject</code> with the values from the freshly-constructed temporary. It's not necessarily the most efficient possible code, since it creates a temporary, then copies, then destroys the temporary, rather than just setting the fields to their initial values. But unless your class is huge, it's unlikely that doing all that 1000 times will take a noticeable amount of time.</p> <p>Another option is just to use a brand new object for each iteration:</p> <pre><code>int main() { int counter = 0; while (counter &lt; 1000) { Class myObject; // stuff happens, each iteration has a brand new object } } </code></pre> <p>Note that <code>Class MyClass();</code> does <em>not</em> define an object of type Class, called MyClass, and construct it with no parameters. It declares a function called MyClass, which takes no parameters and which returns an object of type Class. Presumably in your real code, the constructor has one or more parameters.</p>
    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