title: Class A initialisation within class B containing pointer to class A
body: <p>I wish for a class A to contain some data, and class B will contain a pointer to that data. I am providing access to the data through a function returning a reference to the data object A. If I create an object B then i can access the object A, however if create a pointer to B then the equivalent operation produces a segmentation fault.  Like this:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  class A {
  public:
      A(const int pInt) {mInt = pInt;}
      void print() {std::cout &lt;&lt; mInt &lt;&lt; std::endl;}
  private:
      int mInt; //some data
  };
  
  class B {
  public:
     B() {mP1 = new A(1);} //initialise to 1
     ~B() {delete mP1;}
     A&amp; access() {return *mP1;} //return reference to the data
  
  private:
      A* mP1; //pointer to some data
  };
  
  int main() {
      B vB;
      vB.access().print(); //this works.
  
      B *vBptr;
      vBptr-&gt;access().print(); //Segmentation fault!
  
      std::vector&lt;B*&gt; vVec;
      vVec.resize(1);
      vVec[0]-&gt;access().print(); //Segmentation fault!
  }
  </code></pre>
  
  <p>I guess when creating B *vBptr then a B object is not getting initialised?
  How then could I create a vector of pointers to B objects that are automatically initialised?</p>
  
  <p>Cheers.</p>