c++ - why Base class and Drive class have same virtual pointer but 2 vtable when initiate a Drive instance -


#include <iostream> using namespace std;  class base { public:     base() {         cout << "in base" << endl;         cout << "virtual pointer = " << (int*)this << endl;         cout << "address of vtable = "         << (int*)*(int*)this << endl;         cout << "value @ vtable = "         << (int*)*(int*)*(int*)this << endl;         cout << endl;     }      virtual void f1() { cout << "base::f1" << endl; } };  class drive : public base { public:     drive() {         cout << "in drive" << endl;         cout << "virtual pointer = "         << (int*)this << endl;         cout << "address of vtable = "         << (int*)*(int*)this << endl;         cout << "value @ vtable = "         << (int*)*(int*)*(int*)this << endl;         cout << endl;     }      virtual void f1() { cout << "drive::f2" << endl; } };  int main() { drive d; return 0; 

}

the output of program is

in base virtual pointer = 0012ff7c address of vtable = 0046c08c value @ vtable = 004010f0  in drive virtual pointer = 0012ff7c address of vtable = 0046c07c value @ vtable = 00401217 

follow code, can see when create drive object, base constructor run , show address of virtual pointer same drive's virtual pointer: 0012ff7c. weird thing when dereference address in both constructors of base , drive class, pointed different value meaning there 2 vtable, 1 @ 0046c08c , @ 0046c07c. difficult understand in structure of drive object , in c langue when 1 pointer point 2 address.

you've witnessed how c++ compiler implements rules set out c++ standard. while base constructor running, calls virtual methods need dispatched base implementations, if drive overrides them. make happen, c++ compiler evidently makes object's vtable pointer point base vtable. when base constructor finishes , execution continues in drive constructor, vtable pointer gets updated point @ drive vtable.

that ends being convenient way implement it. rest of code, compiler generates instructions call virtual methods, doesn't need change detect whether special constructor behavior required. can in vtable always. changing vtable pointer quick way change effective run-time type of object while constructors run.

you'll find destructors work in similar manner, in reverse. if construct base object instead of drive object, you'll see similar addresses in base constructor of drive object.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -