title: Pattern to share data between objects in C++
body: <p>I have started a migration of a high energy physics algorithm written in FORTRAN to an object oriented approach in C++.  The FORTRAN code uses a lot of global variables all across a lot of functions.</p>
  
  <p>I have simplified the global variables into a set of input variables, and a set of <em>invariants</em> (variables calculated once at the beginning of the algorithm and then used by all the functions).</p>
  
  <p>Also, I have divided the full algorithm into three logical steps, represented by three different classes. So, in a very simple way, I have something like this:</p>
  
  <pre><code>double calculateFactor(double x, double y, double z)
  {
      InvariantsTypeA invA();
      InvariantsTypeB invB();
  
      // they need x, y and z
      invA.CalculateValues();
      invB.CalculateValues();
  
      Step1 s1();
      Step2 s2();
      Step3 s3();
  
      // they need x, y, z, invA and invB
      return s1.Eval() + s2.Eval() + s3.Eval();
  }
  </code></pre>
  
  <p>My problem is:</p>
  
  <ul>
  <li>for doing the calculations all the <code>InvariantsTypeX</code> and <code>StepX</code> objects need the input parameters (and these are not just three).</li>
  <li>the three objects <code>s1</code>, <code>s2</code> and <code>s3</code> need the data of the <code>invA</code> and <code>invB</code> objects.</li>
  <li>all the classes use several other classes through composition to do their job, and all those classes also need the input and the <em>invariants</em> (by example, <code>s1</code> has a member object <code>theta</code> of class <code>ThetaMatrix</code> that needs <code>x</code>, <code>z</code> and <code>invB</code> to get constructed).</li>
  <li>I cannot rewrite the algorithm to reduce the global values, because it follows several high energy physics formulas, and those formulas are just like that.</li>
  </ul>
  
  <p>Is there a good pattern to share the input parameters and the <em>invariants</em> to all the objects used to calculate the result?</p>
  
  <p>Should I use singletons? (but the <code>calculateFactor</code> function is evaluated around a million of times)</p>
  
  <p>Or should I pass all the required data as arguments to the objects when they are created?(but if I do that then the data will be passed everywhere in every member object of every class, creating a mess)</p>
  
  <p>Thanks.</p>