This virtual inheritance is really a tough guy. Every time I encounter a pen test, I really need to take a test. Can you change the style? It's really easy to make mistakes. Today, let's make a summary and let this guy die! The concept of virtual functions is not described much. The main function is to implement polymorphism. First look at a piece of code:
1. The parent class is not virtual, and your son will not be virtual. I am still not strong enough!
[Cpp]
# Include <iostream>
Using namespace std;
Class
{
Public:
Void find ()
{
Cout <"find: A" <endl;
}
Virtual void get ()
{
Cout <"get: A" <endl;
}
};
Class B: public
{
Public:
Void find ()
{
Cout <"find: B" <endl;
}
Virtual void get ()
{
Cout <"get: B" <endl;
}
};
Int main ()
{
A * a = new B ();
A-> find ();
A-> get ();
Return 0;
}
What will the above Code output?
The answer is:
Find:
Get: B
Let's assume that we remove the virtual keyword from the get () method in the Code: A and change it to A general function. What is the result?
Answer:
Find:
Get:
This is where the coverage of virtual functions occurs.
Ii. Test the knife
Continue with the following code:
[Cpp]
Class
{
Public:
Virtual void get ()
{
Cout <"A" <endl;
}
};
Class B: public
{
Public:
Virtual void get ()
{
Cout <"B" <endl;
}
};
Int main ()
{
A * pa = new ();
Pa-> get ();
B * pb = (B *) pa;
Pb-> get ();
Delete pa, pb;
Pa = new B ();
Pa-> get ();
Pb = (B *) pa;
Pb-> get ();
Return 0;
}
Output: A B
The above two examples are about the problem of overwriting virtual functions by virtual functions. B * pb = (B *) pa; we can see the forced conversion, but the pointer of pa has not changed and the content pointed to has not changed, so we know that pb points to the content that pa points.
Delete pa, pb. The addresses pointed to by pa and pb are deleted. However, pa and pb are not deleted and are suspended pointers. We re-assign a value to pa, pointing to B, so pa-> get (); outputs B
3. What do you know about virtual inheritance!
[Cpp]
// MicroTest. cpp: Defines the entry point for the console application.
//
# Include "stdafx. h"
# Include <iostream>
Using namespace std;
Class
{
Public:
Void getA ()
{
Cout <"";
}
Virtual void getAA ()
{
Cout <"1 ";
}
};
Class B: public
{
Public:
Virtual void getA ()
{
Cout <"B ";
}
Virtual void getAA ()
{
Cout <"2 ";
}
};
Class C: virtual public
{
Public:
Void getA ()
{
Cout <"C ";
}
Virtual void getAA ()
{
Cout <"3 ";
}
};
Int main (int argc, char * argv [])
{
Printf ("Hello World! \ N ");
A * a = new B ();
A * B = new C ();
A-> getA ();
A-> getAA ();
B-> getA ();
B-> getAA ();
Return 0;
}