Inside the Overriding Mechanism
From Andrey
Among possible implementations of overriding in owner class the most natural is to use the same mechanism of dynamic binding through the virtual method tables as for the usual overriding. The implementation described below is simple, straightforward, does not require special data structures, does not interfere with other language features, and does not require additional memory. The efficiency of a call to an overridden member’s method is the same as of a call to a virtual function of an object, when not optimized by knowing the exact type.
The process of overriding in owner class consists of the following steps: 1. A new virtual method table is created for the member. 2. The new table is initialized with the data from the original table. 3. In the new table, the address of the original function(s) is changed to the address of the function override(s). 4. The pointer to the virtual method table in the member object is modified to point to the new table. 5. When entering the body of the function override, this pointer value is modified to point to the owner object.
Step 5 needs further explanation. When entering the override, this points to the member for which the function has is been called. But the code of the override resides in the owner class, and deals with the owner class. It requires this pointer to point to the owner object. Therefore, this is modified - by subtracting the offset between the owner and the member object. The place of the member inside the owner class is known in the compile time, so the modification of this is merely the subtracting of a constituent.
The first three steps are done one time, when the owner class is initialized. Step four is done every time the owner class is instantiated. Step five is done every time the overridden function is called, when entering the body of the function override. The result of steps 1-4 is a structure shown at Figure 2. In the figure, PVTBL is a pointer to a virtual method table from an instance of a class; A VTBL is a virtual method table of class A, and B VTBL for B::a is virtual method table created in step one. One concern that may arise is about the stability of the pointer to the member’s new virtual method table. Can it suffer when an object of the owner class, or its subclass, is assigned to with an object of the owner class when C++ copies objects "by bits", i.e. when the default assignment operator is used? Fortunately, the answer is no. C++ guarantees that the copying affects neither the pointer to the virtual method table in the owner object, nor the pointers to the virtual method tables in its members. Algorithm 1-5 was used when implementing overriding in owner class in [1]. [1] contains description of this work, more details, including the information on the modification of this in case of multiple inheritance, the source code, and the usage sample.
Next: Conclusion