1:# Include<Iostream>
2:# Include<String>
3:Using namespaceSTD;
4:
5:ClassA{
6:Public:
7:Void virtualF()
8:{
9:Cout<""<Endl;
10:}
11:};
12:
13:ClassB:PublicA{
14:Public:
15:Void virtualF(){
16:Cout<"B"<Endl;
17:}
18:};
19:
20:IntMain()
21:{
22:A*Pa=NewA();
23:Pa->F();
24:B*PB= (B*)Pa;
25:PB->F();
26:DeletePa,PB;
27:Pa=NewB();
28:Pa->F();
29:PB= (B*)Pa;
30:PB->F();
31:
32:Getchar();
33:Return0;
34:}
Running result:
Analysis:
1) a virtual function occupies space and contains an object of the class of a virtual function. It has a virtual function pointer, so the sizeof size is the sum of the values of each member variable, add the size of the virtual function pointer (usually 4B, 32-bit machine ).
2) When calling a virtual function through a base class pointer or subclass pointer, the virtual function pointer in the object to which the pointer is currently directed is used to call a suitable virtual function. Therefore, no matter the pointer is of the base class type or subclass type, the type of the object to which the virtual function is called depends on the type of the object to which the pointer is directed (the virtual function pointer in the actual dependent object ).
3) When a virtual function is called through a class object, the virtual function of the Class Object is called.
# Include <Iostream> # Include <String> Using namespace STD ; Class A { Public : Int Val ;A ( Int I = 1 ): Val ( I ){}; Int virtual F (){ Return Val ;}}; Class B : Public A { Public : Int Val ; B ( Int I = 2 ): Val ( I ){};}; Int Main (){ B ; Cout < B . F () < Endl ; Getchar ();Return 0 ;}
Output:
The result is 1.