Home > Back-end >  C polymorphism mechanism analysis
C polymorphism mechanism analysis

Time:09-27

 # include 

using namespace std;

Class A
{
Public:
Virtual void print () {cout<" "This is a. & lt; };

Class B: public A
{
Public:
(B) {data=https://bbs.csdn.net/topics/2; }
Virtual void printB () {cout<" This is b. "& lt; The int data;
};

Int main ()
{
A a;
A, b.
A * c=new A ();
B, d;
B e;
A * f=new B ();
B * g=new B ();

return 0;
}

Code as above, and then use the GDB debugging results are as follows:
 
29 return 0;
(GDB) print a
$1={_vptr. A=0 x400bc0}
(GDB) print b
$2={_vptr. A=0 x400bc0}
(GDB) print * c
$3={_vptr. A=0 x400bc0}
(GDB) print d
$4={& lt; A>={_vptr. A=0 x400c10}, data=https://bbs.csdn.net/topics/2}
(GDB) print e
$5={& lt; A>={_vptr. A=0 x400c10}, data=https://bbs.csdn.net/topics/2}
(GDB) print * f
$6={_vptr. A=0 x400c10}
(GDB) print * g
$7={& lt; A>={_vptr. A=0 x400c10}, data=https://bbs.csdn.net/topics/2}
The quit (GDB)
A was debugging session is active.

Is not A virtual table is followed by an object, why defines the different objects, they use the same virtual pointer table (of the same type of object _vptr. A at the same address), A great god explain it in detail,
  • Related