Search code examples
c++classcastingcompiler-errorsdynamic-cast

Convert by "dynamic_cast" between points to classes


I tried to convert by "dynamic_cast" in the following way:

#include <iostream>

class Shape {
    //....
};

class Square: Shape {
    //....
};

class Circle: Shape {
    //....
};

int main() {
    Circle cr;
    Shape* sh = &cr; // ERROR1
    Square* psq = dynamic_cast<Square*>(sh); //ERROR2
    return 0;
}

And I get error messages:

ERROR1: 'Shape' is an inaccessible base of 'Circle'

ERROR2: cannot dynamic_cast 'sh' (of type 'class Shape*') to type 'class Square*' (source type is not polymorphic)

Can someone explain why I get these errors?


Solution

  • The first error is that you must inherit publicly from Shape To be able to call the Shape's constructor in the derived object construction.

    The second error is because class Shape must be polymorphic which means at least there's a virtual method:

    class Shape {
        public:
            virtual ~Shape(){}
        //....
    };
    
    class Square: public Shape {
        //....
    };
    
    class Circle: public Shape {
    };
    
    Circle cr;
    Shape* sh = &cr; // ERROR1
    Square* psq = dynamic_cast<Square*>(sh);
    
    • Polymorphism requires pointer to base class and virtual functions and operator overloading.

    • You could use dynamic_cast to cast a derived class to a non polymorphic base class. But you cannot dynamic_cast a non polymorphic base to a derived class.

    Eg:

    Circle* cr = new Circle;
    Shape* shp = dynamic_cast<Shape*>(cr); // upcasting
    

    The lines above works fine even if the base class Shape is not polymorphic.