vptr is a const non-static field – (slicing, casting)

When you “cast” a c++ or java POINTER[1] up and down family tree, the vptr field of the pointee persistently points to the “most derived” vtbl. To fully appreciate the constness of the vptr, consider slicing —

Q: during slicing, how does vptr end up pointing to the base vtbl?
A: copy constructor of the base object will be used, which (blindly) initializes vptr with the base object’s vtbl.

Background — vtbl is an array of func pointers. One vtbl per CLASS, but —

Q: Is there any compiler where superclass’s and subclass’s vtbl share the same address?
A: Won’t work. When slicing, the trim-down object’s vptr must NOT point to original vtbl. Trim-down object can never access derived class methods.
A: but what if a subclass overrides no method? Probably will share the vtbl with super class?

vptr is like a non-static const field. In the non-slicing scenario, The magic of polymorphism depends on the “vptr still pointing to subclass vtbl even if object is accessed by a base ptr”.

A twist on the constness — After this->vptr is initialized in the base ctor, it gets reseated during subclass ctor. During destruction, this->vptr gets reseated during Base dtor. This knowledge is relevant only if base ctor/dtor calls virtual methods.

[1] nonref won’t work.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s