# Include <stdio. h> Class A {public: A () {function () ;}virtual void function () {printf ("A") ;}}; Class B: Public A {public: B () {function () ;}void function () {printf ("B") ;}}; int main () {B; return 0;};
What will happen ??? Some may say that two B instances are output. Isn't this a virtual function ?? Isn't it a legend of polymorphism. Unfortunately, we are sorry to tell you that AB is output.
Analysis: Before calling constructor B, it will certainly call the constructor of the parent class, that is, a (). This is beyond doubt, so why does a call B's function in its constructor ?? At this time, no part of B has been constructed yet. How can we call B .. Of course, what we need here is the address of a virtual function table, that is, the pointer in a subclass object .. Therefore, a cannot call the pointer of B ..
If you are interested, check the assembly.CodeTo see what is going on .. I believe there will be gains ..
Some people may ask this question. Let's give a small answer .. It is purely entertainment ..