title: Dependency injection with same class name in source links to same object?
body: <p>I may be missing something basic, but not sure what to lookup to find out what.</p>
  <p>I have a simple program that I expect to return:</p>
  <pre><code>ImplA
  ImplB
  </code></pre>
  <p>It actually returns:</p>
  <pre><code>ImplA
  ImplA
  </code></pre>
  <p>I know renaming class &quot;Do&quot; in each file, or wrapping the class definition in a namespace, solves the issue, but is there a way for this to work where both files name the implementation the same? Is the some way to limit the class visibility to the file?</p>
  <pre><code>// main.cpp
  #include &quot;do_a.h&quot;
  #include &quot;do_b.h&quot;
  
  #include &lt;cstdint&gt;
  
  int32_t main(int32_t,char**) {
      IDo* a = getImplA();
      IDo* b = getImplB();
      
      a-&gt;print();
      b-&gt;print();
  
      delete b;
      delete a;
  
      return 0;
  }
  </code></pre>
  <pre><code>// i_do.h
  // interface file for DI
  #pragma once
  
  class IDo {
  public:
      virtual ~IDo() {}
      virtual void print() = 0;
  };
  </code></pre>
  <pre><code>// do_a.h
  #pragma once
  #include &quot;i_do.h&quot;
  
  IDo *getImplA();
  </code></pre>
  <pre><code>// do_b.h
  #pragma once
  #include &quot;i_do.h&quot;
  
  IDo *getImplB();
  </code></pre>
  <pre><code>// do_a.cpp
  #include &quot;do_a.h&quot;
    
  #include &lt;iostream&gt;
  
  namespace { // adding anon-namespace seems to be another alternative
  
  class Do : public IDo {
  public:
      virtual void print() override {
          std::cout &lt;&lt; &quot;ImplA&quot; &lt;&lt; std::endl;
      }
  };
  
  } 
  
  IDo* getImplA() {
      return new Do();
  }
  </code></pre>
  <pre><code>// do_b.cpp
  #include &quot;do_b.h&quot;
    
  #include &lt;iostream&gt;
  
  namespace {
  
  class Do : public IDo {
  public:
      virtual void print() override {
          std::cout &lt;&lt; &quot;ImplB&quot; &lt;&lt; std::endl;
      }
  };
  
  }
  
  IDo* getImplB() {
      return new Do();
  }
  </code></pre>
  <pre><code>cmake_minimum_required(VERSION 3.12)
  
  # C++ version required
  set(CMAKE_CXX_STANDARD 20)
  set(CMAKE_CXX_STANDARD_REQUIRED ON)
  
  set(CMAKE_CXX_FLAGS
      &quot;-std=gnu++2a -Wall -Wpedantic -Wextra -fexceptions -O0 -g3 ${CMAKE_CXX_FLAGS_DEBUG}&quot;
  )
  
  project(main)
  
  set(CMAKE_BUILD_TYPE &quot;Debug&quot;)
  
  set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
  
  set(Main main)
  
  set(MainSrc
      main.cpp
  )
  
  set(ApplSrc
      do_a.cpp
      do_a.h
      do_b.cpp
      do_b.h
      i_do.h
  )
  
  add_executable(${Main} ${ApplSrc} ${MainSrc})
  </code></pre>
  <p>Edited to wrap the class Do {...}; in an anonymous namespace.</p>