Os:windows 7
Keywords: vs2012,c++,vtable, virtual table
1. Create a WIN32 console application code as follows:
#include"stdafx.h"#include<string>#include<iostream>classa{ Public: VirtualSTD::stringAName () {return "A";}};classb{ Public: VirtualSTD::stringBname () {return "B";}};classE | PublicA Publicb{ Public: VirtualSTD::stringBname () {return "C";}};int_tmain (intARGC, _tchar*argv[]) {C* PC =NewC (); C* PC1 =NewC (); Std::cout<<pc->bname () <<Std::endl; B* PB = static_cast<b*>(PC); Std::cout<<pb->bname () <<Std::endl; //A * PA = static_cast<a*> (PB);A * PA = dynamic_cast<a*>(PB); Std::cout<<pa->aname () <<Std::endl; A* PA1 = reinterpret_cast<a*>(PB); Std::cout<<pa1->aname () <<Std::endl; return 0;}
2. Compile and run, the console output is as follows:
C
C
A
C
Do you have any strange places to see this result? Why is the "pa1->aname ()" Output C?
3. The virtual table structure seen in the Watch Window is as follows:
Summarized as follows:
- PCs and pC1 are two instance pointers to Class C, and the virtual tables of the two instances are the same, meaning that the virtual table belongs to the class, and a class has a virtual table.
- Because Class C overrides the Bname function of Class B, the virtual table of c is stored in C::bname
- "A * PA = static_cast<a*> (PB);" is not compiled, because A and B are unrelated two classes, that is, there is no inheritance relationship.
- "A * PA = dynamic_cast<a*> (PB);" Yes, because dynamic_cast will perform type checking at run time, dynamic_cast is the safest, but least efficient.
- "A * pA1 = reinterpret_cast<a*> (PB);" Can be compiled and passed, but the runtime will have unexpected results. Reinterpret_cast casts a forced type, but does not correct the virtual table.
Instance parsing C + + virtual table