Why vptr is not static?

前端 未结 7 989
忘了有多久
忘了有多久 2020-12-28 19:27

Every class which contains one or more virtual function has a Vtable associated with it. A void pointer called vptr points to that vtable. Every object of that class contain

7条回答
  •  梦毁少年i
    2020-12-28 19:59

    As everyone attest Vptr is a property of an object. Lets see why?

    Assume we have three objects Class Base{ virtual ~Base(); //Class Definition }; Class Derived: public Base{ //Class Definition }; Class Client: public Derived{ //Class Definition };

    holding relation Base<---Derived<----Client. Client Class is derived from Derived Class which is in turn derived from Base

    Base * Ob = new Base; Derived * Od = new Derived; Client* Oc = new Client;

    Whenever Oc is destructed it should destruct base part, derived part and then client part of the data. To aid in this sequence Base destructor should be virtual and object Oc's destructor is pointing to Client's destructor. When object Oc's base destructor is virtual compiler adds code to destructor of object Oc to call derived's destructor and derived destructor to call base's destructor. This chaining sees all the base, derived and client data is destructed when Client object is destroyed.

    If that vptr is static then Oc's vtable entry will still be pointing to Base's destructor and only base part of Oc is destroyed. Oc's vptr should always point to most derived object's destructor, which is not possible if vptr is static.

提交回复
热议问题