memory layout of inherited class

后端 未结 5 630
不知归路
不知归路 2021-02-04 05:25

I\'m keen to know exactly how the classes will be arranged in memory esp. with inheritance and virtual functions.

I know that this is not defined by the c++ language st

5条回答
  •  無奈伤痛
    2021-02-04 05:39

    Create an object of class, cast pointer to it to your machine's word, use sizeof to find the size of the object, and examine the memory at the location. Something like this:

    #include 
    
    class A
    {
     public:
      unsigned long long int mData;
      A() :
       mData( 1 )
      {
      }      
      virtual ~A()
      {
      }
    };
    class B : public A
    {
     public:
      unsigned long long int mData1;
      B() :
       A(), mData1( 2 )
      {
      }
    };
    
    int main( void )
    {
     B lB;
    
     unsigned long long int * pB = ( unsigned long long int * )( &lB );
    
     for( int i = 0; i < sizeof(B) / 8; i++ )
     {
      std::cout << *( pB + i ) << std::endl;
     }
    
     return ( 0 );
    }
    
    
    Program output (MSVC++ x86-64):
    
    5358814688 // vptr
    1          // A::mData
    2          // B::mData1
    

    On a side note, Stanley B. Lippman has excellent book "Inside the C++ Object Model".

提交回复
热议问题