In this paper, a simple example is given to illustrate how virtual functions are called when a cast occurs between subclasses, aiming at a deeper understanding of the mechanism of virtual function tables in C + + inheritance.
#include <iostream>using namespacestd;classbase{ Public: Virtual voidf () {cout<<"base::f ()"<<Endl; }};classChild1: Publicbase{ Public: Virtual voidf () {cout<<"child1::f ()"<<Endl; } Virtual voidA () {cout<<"child1::a ()"<<Endl; }};classChild2: Publicbase{ Public: Virtual voidf () {cout<<"child2::f ()"<<Endl; } Virtual voidB () {cout<<"child2::b ()"<<Endl; } Virtual voidA () {cout<<"child2::a ()"<<Endl; }};intMain () {child1 C1; Child2* pc21= (child2*) &C1; Pc21->b ();//output child1::a ()
///Pc21->a ();// access out of Bounds, program run-time crash
child2 C2; Child1* Pc12= (child1*) &C2; PC12->a ();//output child2::b () return 0;}
Conclusion:
1, the usual type of strong turn is to tell the compiler must follow the specified structure of the memory layout to resolve the corresponding memory, as in the above example "child2* pc21= (child2*) &c1;", the compiler will parse the c1 corresponding memory as the derive memory layout.because in the virtual function table of the corresponding class child1 of the object C1, there are altogether three functions, F () B () A (), where function B () is the second one, so The compiler will c1 the corresponding memory of the object as the memory layout of the class child2 (notice that the contents of the memory are not changed, or C1, that is, the memory layout of the class child1, where there is only a virtual function table), at this time in the virtual function table of class Child1 also find the second function, function A () is found, so output "child1::a ()" and run normally. ButThis behavior can be dangerous, if the memory layout used is not suitable for real memory, it is likely to cause problems such as access violation ("pc21->a ()," in the example above, this time in the virtual function table of Class B to find the third function, the result is not found (access out of bounds) , the function crashes when it runs. ), so you should pay special attention when you use a cast operation.
2. The above example shows that the virtual function in the virtual function table in the order of storage is consistent with the declaration order, rather than the virtual function name of the string ordering, as in this case, F () B () a (), although the programming of the auto-completion prompt box in the order shown in a () B () f (), but may have been This is not very clear (nor what we are going to study).
How virtual function tables work when C + + inherits class casts