Why does the size of a derived class include private members from the base class?

前端 未结 7 1723
谎友^
谎友^ 2021-02-09 19:52

I have the following code:

class A {
  private:
    int i;
 };

class B : public A {
 private:
  int j;
 };

When I check sizeof(B)

7条回答
  •  情书的邮戳
    2021-02-09 20:03

    You either misunderstand sizeof or your misunderstand the layout (in memory) of C++ objects.

    For performance reason (to avoid the cost of indirection), compilers will often implement Derivation using Composition:

    // A
    +---+
    | i |
    +---+
    
    // B
    +---+---+
    | A | j |
    +---+---+
    

    Note that if private, B cannot peek in A even though it contains it.

    The sizeof operator will then return the size of B, including the necessary padding (for alignment correction) if any.

    If you want to learn more, I heartily recommend Inside the C++ Object Model by Stanley A. Lippman. While compiler dependent, many compilers do in fact use the same basic principles.

提交回复
热议问题