Question about which virtual function to call

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.