title: Why overloading the [] operator in a class/struct makes it so slow to access an array?
body: <p>For studying purposes, I was trying to create my own array class.</p>
  <p>So i just created a simple class with an array and overloaded the [] operator to access the elements in the class:</p>
  <pre><code>template &lt;class T&gt;
  class Array
  {
    private:
      T *arr;
      int size;
  
    public:
      Array(int arrSize)
      {
          this-&gt;arr = new T [arrSize];
          this-&gt;size = arrSize;
      }
  
      T&amp; operator[](int pos)
      {
          return this-&gt;arr[pos];
      }
  };
  </code></pre>
  <p>When I run a simple test to check how fast different containers access 1.000.000 of their elements, I usually get these results (in seconds):</p>
  <p>MyArrayClass: 0.017294</p>
  <p>C Array: 0.009943</p>
  <p>std::array: 0.014728</p>
  <p>std::vector: 0.013836</p>
  <p>Why is C array so much faster than my class? Weren't they supposed to be equally fast? At least, I wasn't expecting my own class to take twice the time the c array takes, considering it uses the same principle to access the elements.</p>
  <p>Code used to measure the time (timenow = std::chrono::system_clock::now()) :</p>
  <pre><code>auto ti = timenow, te=timenow;
  
  
  Array&lt;int&gt; tst (1000000);
  int tst2[1000000];
  std::array&lt;int, 1000000&gt; tst3;
  vector&lt;int&gt; tst4(1000000);
  ArrayT tst5(1000000);
  
  ti = timenow;
  for (int i = 0; i &lt; 1000000; i++)
  {
      tst[i] = 1;
  }
  te = timenow;
  
  std::chrono::duration&lt;float&gt; et = te-ti;
  
  cout &lt;&lt; &quot;MyArrayClass: &quot; &lt;&lt; et.count() &lt;&lt; nl
  
  ti = timenow;
  for (int i = 0; i &lt; 1000000; i++)
  {
      tst2[i] = 1;
  }
  te = timenow;
  
  et = te-ti;
  
  cout &lt;&lt; &quot;C Array: &quot; &lt;&lt; et.count() &lt;&lt; nl
  
  ti = timenow;
  for (int i = 0; i &lt; 1000000; i++)
  {
      tst3[i] = 1;
  }
  te = timenow;
  
  et = te-ti;
  
  cout &lt;&lt; &quot;std::array: &quot; &lt;&lt; et.count() &lt;&lt; nl
  
  ti = timenow;
  for (int i = 0; i &lt; 1000000; i++)
  {
      tst4[i] = i;
  }
  te = timenow;
  
  et = te-ti;
  
  cout &lt;&lt; &quot;std::vector: &quot; &lt;&lt; et.count() &lt;&lt; nl
  </code></pre>