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


i have following code:

class {   private:     int i;  };  class b : public {  private:   int j;  }; 

when check sizeof(b), appears sizeof(base) + sizeof(derived). however, understanding of inheritance private members of base class not inherited. why included in result of sizeof(b)?

you either misunderstand sizeof or misunderstand layout (in memory) of c++ objects.

for performance reason (to avoid cost of indirection), compilers implement derivation using composition:

// +---+ | | +---+  // b +---+---+ | | j | +---+---+ 

note if private, b cannot peek in a though contains it.

the sizeof operator return size of b, including necessary padding (for alignment correction) if any.

if want learn more, heartily recommend inside c++ object model stanley a. lippman. while compiler dependent, many compilers in fact use same basic principles.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -