Main function:
1#include <iostream>2#include"test.h"3#include"testfuc.h"4 using namespacestd;5 6 intMainvoid)7 { 8A *p=Newb ();9 TenP->fuc (); One Acout<<"pointer p occupies space"<<sizeof(p) <<Endl; -cout<<"class occupies Space"<<sizeof(a) <<Endl; - the Deletep; - - return 0; -}
Test.h
1 #ifndef Test_h2 #defineTest_h3 4 classa5 {6 Public:7 a ();8~a ();9 void Virtualfuc ();Ten }; One A classB: Publica - { - Public: the b (); -~b (); - voidfuc (); - }; + - #endif
Testfuc.h
1 #ifndef Testfuc_h2 #defineTestfuc_h3 4#include <iostream>5 using namespacestd;6 7 a::a ()8 {9cout<<"A's constructor"<<Endl;Ten } One Aa::~A () - { -cout<<"A's destructor"<<Endl; the } - - b::b () - { +cout<<"The constructor of B"<<Endl; - } +b::~B () A { atcout<<"B's destructor"<<Endl; - } - - voida::fuc () - { -cout<<"the function of a"<<Endl; in } - to voidb::fuc () + { -cout<<"function of B"<<Endl; the } * #endif
Operation Result:
A's constructor
The constructor of B
function of B
Pointer p occupies space 8
Class takes up space 8 //Each virtual function has a 8-byte (64-bit system) pointer pointing to its own virtual function table
A's destructor
Will
A *p=new b ();
Switch
b *p=new B ();
Operation Result:
A's constructor
The constructor of B
function of B
Pointer p occupies space 8
Class Occupy space 8
B's destructor
A's destructor
Remove virtual a *p=new B ();
Operation Result:
A's constructor
The constructor of B
The function of a
Pointer p occupies space 8
Class Occupy space 1
A's destructor
Remove Virtual B *p=new B ();
Operation Result:
A's constructor
The constructor of B
function of B
Pointer p occupies space 8
Class Occupy space 1
B's destructor
A's destructor
C + + class inheritance, virtual inheritance, hiding, occupy space