title: Inherit from a template parameter and upcasting back in c++
body: <p>I have tried to use this code in VS2008 (and may have included too much context in the sample...):</p>
  
  <pre><code>class Base
  {
      public:
      void Prepare() {
         Init();
         CreateSelectStatement();
         // then open a recordset
      }
      void GetNext() { /* retrieve next record */ }
      private:
      virtual void Init() = 0;
      virtual string CreateSelectStatement() const = 0;
  };
  class A : public Base
  {
     public:
     int foo() { return 1; }
     private:
     virtual void Init() { /* init logic */ }
     virtual string CreateSelectStatement() { /* return well formed query */ }
  };
  
  template&lt;typename T&gt; class SomeValueReader : protected T
  {
     public:
     void Prepare() { T::Prepare(); }
     void GetNext() { T::GetNext(); }
     T&amp; Current() { return *this; } // &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; this is where it is interesting
     SomeValue Value() { /* retrieve values from the join tables */ }
     private :
     string CreateSelectStatement() const
     {
     // special left join selection added to T statement
     }
  };
  
  void reader_accessAmemberfunctions_unittest(...)
  {
     SomeValueReader&lt;A&gt; reader();
     reader.Prepare();
     reader.GetNext();
     A a = reader.Current();
     int fooresult = a.foo();
     // reader.foo()            &gt;&gt; ok, not allowed
     Assert::IsEqual&lt;int&gt;( 1, fooresult );
  };
  </code></pre>
  
  <p>This works as expected, i.e. having access to "A" member functions and fooresult returning 1. However, an exception is thrown when objects are deleted at the end of the unittest function:</p>
  
  <blockquote>
    <p>System.AccessViolationException:
    Attempted to read or write protected
    memory. This is often an indication
    that other memory is corrupt</p>
  </blockquote>
  
  <p>If I change the return type of Current() function to :</p>
  
  <pre><code>T* Current()
  {
     T* current = dynamic_cast&lt;T*&gt;(this);
     return current;
  }
  </code></pre>
  
  <p>then everything is ok and the unit test ends with no access violation. Does someone can tell me what was wrong with the first Current() implementation? Thanks, bouchaet.</p>