Thursday, April 9, 2015

How are C++ objects laid out in memory?

Like C, C++ doesn’t define layouts, just semantic constraints that must be met. Therefore different implementations do things differently. One good explanation is in a book that is otherwise outdated and doesn’t describe any current C++ implementation: The Annotated C++ Reference Manual (usually called the ARM). It has diagrams of key layout examples. There is a very brief explanation in Chapter 2 of TC++PL3.
Basically, C++ constructs objects simply by concatenating sub objects. Thus

is represented by two ints next to each other, and

is represented by an A followed by an int; that is, by three ints next to each other.

Virtual functions are typically implemented by adding a pointer (the “vptr”) to each object of a class with virtual functions. This pointer points to the appropriate table of functions (the “vtbl”). Each class has its own vtbl shared by all objects of that class.

1 comment:

  1. I discovered your blog site on google and verify a few of your early posts. Continue to maintain up the superb operate. I simply extra up your RSS feed to my MSN News Reader. Looking for forward to reading extra from you in a while!… free C++ Courses