title: Can I cast an object class to the interface pointer in which it implements?
body: <p>I have defined an interface class like the following.</p>
  
  <pre><code>class IRecyclableObject
  {
  public:
      virtual ~IRecyclableObject() {}
  
      virtual void recycle() = 0;
      virtual void dump() = 0;
      virtual int getRecycleTypeID() = 0;
  };
  </code></pre>
  
  <p>The following is my <em>CharacterAI</em> class which inherits another class and implements above interface class. It's defined as follows.</p>
  
  <pre><code>class CharacterAI : public harp::Character, public harp::IRecyclableObject
  {
  public:
      CharacterAI();
      virtual ~CharacterAI();
  
      ...
  
      // -- note these 3 virtual functions -- //
      virtual void recycle();
      virtual void dump();
      virtual int getRecycleTypeID();
  
      ...
  };
  </code></pre>
  
  <p>Those three virtual functions as defined in interface, I have implemented it normally in <em>CharacterAI</em> class. Nothing fancy goes there.</p>
  
  <p>It's time when I put them into use with <em>ObjectPool</em> (a self-made) class in which the data storage of available objects in </p>
  
  <pre><code>m_freeList
  </code></pre>
  
  <p>uses <em>CCArray</em> class.</p>
  
  <p>The problem occurs in the following code.</p>
  
  <pre><code>IRecyclableObject* ObjectPool::popFreeObjectAndAddToActiveListForType(int recycleTypeID)
  {
      // search from free-list
      for(unsigned int i=0; i&lt;m_freeList-&gt;count(); i++)
      {
          IRecyclableObject* obj = (IRecyclableObject*)m_freeList-&gt;objectAtIndex(i);
          CharacterAI *obj1 = (CharacterAI*)m_freeList-&gt;objectAtIndex(i);
  
          CCLog("recycleTypeID : %d %d %d", obj-&gt;getRecycleTypeID(), recycleTypeID, obj1-&gt;getRecycleTypeID());
  
          ...
      }
      return NULL;
  }
  </code></pre>
  
  <p>The expected result is to show </p>
  
  <pre><code>recycleTypeID : 4 4 4
  </code></pre>
  
  <p>But I got</p>
  
  <pre><code>recycleTypeID : 524241408 4 4
  </code></pre>
  
  <p>The first one is clearly garbage there and randomly different from each loop.
  I tried to put a breakpoint in the implemented function <strong><em>getRecycleTypeID()</em></strong> inside <em>CharacterAI</em> class before it returns. I found out that only</p>
  
  <pre><code>obj1-&gt;getRecycleTypeID()
  </code></pre>
  
  <p>was called but <strong>not</strong> another.</p>
  
  <p>By focusing on <em>obj</em> variable, It's clearly seen that it seems different object calls that function, and the cause may come from casting an object to interface class and use if from there in which it's wrong or some kind.</p>
  
  <p>What's going on there?
  Can I cast an object type class to interface class pointer (which it implements) and correctly call functions as defined in interface class?</p>