title: Friend Function calling Static Members of Derived Classes. Not getting expected output
body: <p>My first post here :)</p>
  
  <p>I am having a problem with the following C++ code. I have an ABC class A, and two derived classes B and C. All of them have a static member called id:</p>
  
  <pre><code>using std::cout;
  
  class A
  {
  private:
      friend int bar(A&amp; a);
      static const int id = 1;
  
      virtual void foo() = 0;
  };
  
  class B : public A
  {
  private :
      friend int bar(A&amp; a);
      static const int id = 2;
  
      void foo() { /*Do something*/ }
  };
  
  class C : public A
  {
  private:
      friend int bar(A&amp; a);
      static const int id = 3;
  
      void foo() { /*Do something*/ }
  };
  
  int bar(A&amp; a)
  {
      return a.id;
  }
  
  int main()
  {
      B b;
      C c;
  
      cout &lt;&lt; bar(b) &lt;&lt; "\n";
      cout &lt;&lt; bar(c) &lt;&lt; "\n";
  
      return 0;
  }
  </code></pre>
  
  <p>I was expecting this code to print out 2 and 3 - rather it prints out 1 and 1 (bar() is always using A::id). What am I doing wrong? Any ideas?</p>
  
  <hr>
  
  <p>Based on the comments below, this the final code I am using. It works, but would love to hear more thoughts :)</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using std::cout;
  
  class A
  {
  private:
      virtual void foo() = 0;
  };
  
  class B : public A
  {
  private:
      template &lt;typename T&gt;
      friend int bar(T&amp; t);
  
      static const int id = 2;
      void foo() { /*do something*/ }
  };
  
  class C : public A
  {
  private:
      template &lt;typename T&gt;
      friend int bar(T&amp; t);
  
      static const int id = 3;
      void foo() { /*do something*/ }
  };
  
  
  template &lt;typename T&gt;
  int bar(T&amp; t)
  {
      return t.id;
  }
  
  
  int main()
  {
      B b;
      C c;
  
      cout &lt;&lt; bar(b) &lt;&lt; "\n";
      cout &lt;&lt; bar(c) &lt;&lt; "\n";
  
      return 0;
  }
  </code></pre>