jeudi 10 mars 2022

About dynamic_cast of base pointer to dynamic pointer type [duplicate]

Why do I get compilation error when I try to dynamic_cast the A* to B*. I get the below error:

error: cannot dynamic_cast ‘ptr’ (of type ‘class A*’) to type ‘class B*’ (source type is not polymorphic)
     if(B *ptrb = dynamic_cast<B*>(ptr))

Code as below:

class A
{
    public:
    A(){cout<<"A";}
    ~A(){}
    void print(){cout<<"A";}
};

class B: public A
{
    public:
    B(){cout<<"B";}
    void print(){cout<<"B";}
};

class C: public A
{
    public:
    C(){cout<<"C";}
    void print(){cout<<"C";}
};

int main()
{

    int x;

    cin>>x;

    A* ptr;

    if(x==1)
    {
        ptr= new B;
    }
    else
    {
        ptr = new C;
    }
    
    if(B *ptrb = dynamic_cast<B*>(ptr))
    {
        ptrb->print();
    }
    else if(C *ptrc = dynamic_cast<C*>(ptr))
    {
        ptrc->print();
    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire