title: C++ and Dependency Injection in unit testing
body: <p>Suppose I have a C++ class like so:</p>
  
  <pre><code>class A
  {
      public:
          A()
          {
  
          }
  
          void SetNewB( const B&amp; _b ) { m_B = _b; }
  
      private:
          B m_B;
  }
  </code></pre>
  
  <p>In order to unit test something like this, I would have to break A's dependency on B. Since class A holds onto an actual object and not a pointer, I would have to refactor this code to take a pointer. Additionally, I would need to create a parent interface class for B so I can pass in my own fake of B when I test SetNewB.</p>
  
  <p>In this case, doesn't unit testing with dependency injection further complicate the existing code? If I make B a pointer, I'm now introducing heap allocation, and some piece of code is now responsible for cleaning it up (unless I use ref counted pointers). Additionally, if B is a rather trivial class with only a couple of member variables and functions, why introduce a whole new interface for it instead of just testing with an instance of B?</p>
  
  <p>I suppose you could make the argument that it would be easier to refactor A by using an interface. But are there some cases where two classes might need to be tightly coupled? </p>