title: Declaring user-defined class types inside a C++ 'for' loop
body: <p>Here are questions related to declaring built-in type variables inside a <code>for</code> loop:</p>
  
  <ul>
  <li><p><a href="https://stackoverflow.com/questions/982963/is-there-any-overhead-to-declaring-a-variable-within-a-loop-c">Is there any overhead to declaring a variable within a loop? (C++)</a></p></li>
  <li><p><a href="https://stackoverflow.com/questions/7959573/declaring-variables-inside-loops-good-practice-or-bad-practice-2-parter">Declaring Variables inside Loops, good practice or bad practice? (2 Parter)</a></p></li>
  </ul>
  
  <p>But I would like to narrow down this subject and ask about declaring user-defined class type variables, which are inherited or made using composition and have non-trivial constructors/destructor with dynamic memory allocation/deallocation (new/delete).</p>
  
  <pre><code>a)  int count = 0;
      while(count &lt; 1000000)
      {
          myClass myObj = some value;
          ++count;
      }
  
  b)  int count = 0;
      myClass myObj;
      while(count &lt; 1000000)
      {
          myObj = some value;
          ++count;
      }
  
  c)  {
          int count = 0;
          myClass myObj;
          while(count &lt; 1000000)
          {
              myObj = some value;
              ++count;
          }
      }
  </code></pre>
  
  <ol>
  <li>If I have to use a user-defined class variable inside a loop which is best practise for that, declare it inside or outside loop?</li>
  </ol>
  
  <p>If it will be declared inside a loop the chain of constructors and destructors will be called per each iteration, but we will have advantages  of restricted scope (a).</p>
  
  <p>If a variable we had declared outside of loop, only the assignment operator will be called per each iteration, but this variable will be accessible out of loop scope (b).</p>
  
  <ol start="2">
  <li><p>Are compilers smart enough to optimize complex data types declaration as a loop local variable? Does memory allocation happen once and then the same space is reused on each iteration?</p></li>
  <li><p>If best practices is, to declare variable outside a loop, is it a good idea to put the loop inside scope to restrict the scope (C)?</p></li>
  </ol>