1

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.

Kundan Kumar
  • 1,974
  • 7
  • 32
  • 54
  • 1
    read this very similar question : http://stackoverflow.com/questions/3747066/c-cannot-convert-from-base-a-to-derived-type-b-via-virtual-base-a – Mr.Anubis May 12 '12 at 20:45

1 Answers1

2

The cast can't be done statically. Imagine a class which inherits virtually from Top (possibly multiple times) and from Left. The layout depends on the details of that class. So there's no single known way to work out where the data for the Left instance is, given only where the Top instance is.

The solution is to embed the information in the object itself (as part of the vtable, normally) and then do the computation dynamically. So you might include some data saying "I am really an instance of Left, and my Top base instance is 12 bytes from where my this pointer points".

But C++ doesn't want every object to be forced to hold that information, because it often isn't needed. It's only required to be stored by polymorphic classes, which are (and this is not a coincidence) exactly those that need to have a vtable anyway.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64