title: How to create object required for the class constructor in inversion of control?
body: <p>I am programming in c++ using TDD, which suggests to use inversion of control when creating objects (when creating objects of certain class, pass constructed objects to it's constructor). This is fine, but how do I create objects required for the constructor?</p>
  
  <p>Right now, I am using a factory (which I can easy change for my unit tests), which returns a shared_ptr pointing to the created object.
  Is this the correct way, or are there better ways of doing this?</p>
  
  <p>Very simplified example demonstrates what I am doing :</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  struct A {
      virtual ~A() { }
      virtual void foo() = 0;
  };
  
  struct B : A {
      virtual ~B() { }
      virtual void foo() { std::cout&lt;&lt;"B::foo()"&lt;&lt;std::endl; }
  };
  
  struct C {
      C( A *a ) : a(a) { }
      void DoSomething() { a-&gt;foo(); }
  
      A *a;
  };
  
  int main() {
      C c( new B );
  
      c.DoSomething();
  }
  </code></pre>
  
  <p>against this :</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  struct A {
      virtual ~A() { }
      virtual void foo() = 0;
  };
  
  struct B : A {
      virtual ~B() { }
      virtual void foo() { std::cout&lt;&lt;"B::foo()"&lt;&lt;std::endl; }
  };
  
  struct C {
      C() : a() { }
      void DoSomething() { a.foo(); }
  
      B a;
  };
  
  int main() {
      C c;   // the object of type B is constructed in the constructor
  
      c.DoSomething();
  }
  </code></pre>
  
  <p><strong>EDIT1</strong></p>
  
  <p><a href="http://www.devx.com/Java/Article/27583/1954" rel="nofollow">This link</a> explains the IoC for java, but as you may know, in java you can do something like this:</p>
  
  <pre><code>class B
  {
  };
  class A
  {
    public:
      A( B b )
  ...
  };
  
  ...
  A objA( new B );   // this doesn't work in c++
  ...
  </code></pre>