title: Same class name in different C++ files
body: <p>If two C++ files have different definitions of classes with the same name, then when they are compiled and linked, something is thrown out even without a warning. For example, </p>
  
  <pre><code>// a.cc
  class Student {
  public:
      std::string foo() { return "A"; }
  };
  void foo_a()
  {
      Student stu;
      std::cout &lt;&lt; stu.foo() &lt;&lt; std::endl;
  }
  
  // b.cc
  class Student {
  public:
      std::string foo() { return "B"; }
  };
  void foo_b()
  {
      Student stu;
      std::cout &lt;&lt; stu.foo() &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>When compiled and linked together using g++, both will output "A" (if a.cc precedes b.cc in the command line order).</p>
  
  <p>A similar topic is <a href="https://stackoverflow.com/questions/2075078/c-vs2005-defining-the-same-class-name-in-two-different-cpp-files">here</a>. I see namespace will solve this problem but I don't know why the linker doesn't even shoot a warning. And if one definition of the class has extra function that isn't defined in another, say if b.cc is updated as:</p>
  
  <pre><code>// b.cc
  class Student {
  public:
      std::string foo() { return "B"; }
      std::string bar() { return "K"; }
  };
  void foo_b()
  {
      Student stu;
      std::cout &lt;&lt; stu.foo() &lt;&lt; stu.bar() &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>Then stu.bar() works well. Thanks to anyone who can tell me how the compiler and linker work in such situation.</p>
  
  <p>As an extra question, if classes are defined in header files, should they always be wrapped with unnamed namespace to avoid such situation? Is there any side effects?</p>