The parent class and subclass of an ordinary function virtual function call problem

Test sites: a pointer to the parent class of an object instance of a subclass, override the ordinary method calls, it calls the method of the parent class. When invoked subclass override the virtual function calls the method subclass.

 1 class A
 2 {
 3 public:
 4  void FuncA()
 5  {
 6      printf( "FuncA called\n" );
 7  }
 8  virtual void FuncB()
 9  {
10      printf( "FuncB called\n" );
11  }
12 };
13 class B : public A
14 {
15 public:
16  void FuncA()
17  {
18      A::FuncA();
19      printf( "FuncAB called\n" );
20  }
21  virtual void FuncB()
22  {
23      printf( "FuncBB called\n" );
24  }
25 };
26 void main( void )
27 {
28  B  b;
29  A  *pa;
30  pa = &b;
31  A *pa2 = new A;
32  PA-> func (); ( 3 )
 33   PA-> FuncB (); ( 4 )
 34   pa2-> func (); ( 5 )
 35   pa2-> FuncB ();
36   delete pA2;
37 }

Operational results:

FuncA called
FuncBB called
FuncA called
FuncB called

 pa-> FuncA (); (3) // pa = & b FuncA dynamic binding but not virtual, so FuncA Called
 pa-> FuncB (); (4) // FuncB B, it is a virtual function call FuncB, FuncBB called  
 pa2-> FuncA (); (5) // pa2 A class is a pointer, does not involve the virtual function call is a function A, so FuncA called FuncB called
 pa2->FuncB()
 
Again, the subclass is overridden virtual function of the operating mode are dynamically bound, regardless of the type of the parent class pointer points to the current instance of the class, the class and instance objects only itself.

Guess you like

Origin www.cnblogs.com/lyqf/p/12515920.html