Search code examples
c++dynamic-cast

C++ dynamic_cast issue


class C1
{
   public:
   C1* A;

   void SomeMethod()
   {
       class C2;
       C2* c2 = dynamic_cast<C2*>(A);
    }
};

class C2 : public C1 {};

In gcc i'm getting "target is not a pointer or reference to complete type" when dynamic_cast is invoked. What's wrong?


Solution

  • The following compiles:

    class C2;
    
    class C1
    {
       virtual ~C1() { } // <--- NOTE MUST BE polymorphic to use dynamic_cast
       public:
       C1* A;
    
       void SomeMethod();
    };
    
    class C2 : public C1 {};
    
    void C1::SomeMethod()
    {
           C2* c2 = dynamic_cast<C2*>(A); // <=== USED after C2 definition 
    }
    
    int main() {
    
    }
    

    Two problems:

    1. C2 was only forward declared, thus an incomplete type (need complete declaration of the class)
    2. C1 was not polymorphic (dynamic_cast only applies to polymorphic types)