title: How safe and compiler-independent is this C++ code?
body: <p>I have created a bit of code that is strange to me, but seems to do what I want. However, I am not sure of its platform independence or how safe it is, or if there is a much easier way to do what I want.</p>
  
  <p>I was reading on the Curiously Recurring Template Program (<a href="http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="nofollow">on wikipedia</a>), and there was sample code for a class counter that lets each derived class keep track of how many instances have been created by inheriting from a base with that functionality. </p>
  
  <p>I had been looking for ways to have derived classes reference to a common object (by pointer) without having to add a static variable and define a virtual function for each new class I create. (I was planing on creating quite a few derived classes.) But, the derived classes, because they were created with templates, were considered different from the base so they could not be implicitly converted to a base pointer. </p>
  
  <p>Dynamic_cast and static_cast didn't work, so I tried reinterpret_cast, for fun, to see what behavior that had. It ended up showing the static variable from the base class, which isn't what I wanted, but it reminded me of a previous experience I had with statics and virtual functions (long story). I wrote a virtual function in the base class, and the virtual function reported the correct variable for the derived classes, polymorphic-ally.</p>
  
  <p>It works, at least according to codepad.org, but I'm still not sure of its platform consistency or the safety of reinterpret_cast in this case. Can someone with more experience than I clarify exactly why this works?</p>
  
  <p>Here is my code. It looks like the Wikipedia sample code because that's what it was originally.</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  template &lt;typename T&gt;
  class counter
  {
      public:
      static int separateObject;
      virtual void printStatic(){
      cout &lt;&lt; this-&gt;separateObject &lt;&lt; endl;
      }
  };
  
  template &lt;typename T&gt; int counter&lt;T&gt;::separateObject( 0 );
  
  class X : public counter&lt;X&gt;
  {
      // ...
  };
  
  class Y : public counter&lt;Y&gt;
  {
      // ...
  };
  
  typedef counter&lt;void*&gt;* voidcounter;
  int main(){
      X* counterX = new X;
      Y* counterY = new Y;
      counterX-&gt;separateObject = 9001;
      counterY-&gt;separateObject = 42;
      cout &lt;&lt; "Object Xs value is: " &lt;&lt; counterX-&gt;separateObject &lt;&lt; endl;
      cout &lt;&lt; "Object Ys value is: " &lt;&lt; counterY-&gt;separateObject &lt;&lt; endl;
      voidcounter polycount = reinterpret_cast&lt;voidcounter&gt;(counterX);
      polycount-&gt;printStatic();
      polycount = reinterpret_cast&lt;voidcounter&gt;(counterY);
      polycount-&gt;printStatic();
      return 0;
  }
  </code></pre>