In this program :
class Top
{
public:
int a;
};
class Left : virtual public Top
{
public:
int b;
};
class Right : virtual public Top
{
public:
int c;
};
class Bottom : public Left, public Right
{
public:
int d;
};
class AnotherBottom : public Left, public Right
{
public:
int e;
int f;
};
int main()
{
Bottom* bottom1 = new Bottom();
AnotherBottom* bottom2 = new AnotherBottom();
Top* top1 = bottom1;
Top* top2 = bottom2;
Left* left = static_cast<Left*>(top1);
return 0;
}
I have few doubts regarding this program :
On doing the static_cast the compiler gives the error
error: cannot convert from base ‘Top’ to derived type ‘Left’ via virtual base ‘Top
Even on dynamic casting it gives error that
error: cannot dynamic_cast ‘top1’ (of type ‘class Top*’) to type ‘class Left*’ (source type is not polymorphic)
So, on adding virtual destructor in the Top class it becomes polymorphic and dynamic casting is allowed.
I am unable to grasp why this is happening so.