Accessing a C++ Object in C Code: The Memory Layout of Derived Objects

The Standard does not specify the memory layout of base class subobjects in a derived class. In practice, however, all C++ compilers use the same convention: The base class subobject appears first (in left-to-right order in case of multiple inheritance), and data members of the derived class follow. C code can access derived objects, as long as the derived class abides by the same restrictions that were specified in the Tip “Accessing a C++ Object in C Code.” For example, consider a non-polymorphic class that inherits from Date (the declaration of Date is repeated here for convenience) and has additional data members:

 class Date{public:  int day;  int month;  int year;  Date(); //current date  ~Date();  bool isLeap() const;  bool operator == (const Date& other);};class DateTime: public Date{public:    long time; //additional members  char AM // AM or PM?  DateTime();  ~DateTime();  long getTime() const;};

The two additional data members of DateTime, namely ‘time’ and ‘AM’, are appended after the three members of the base class Date, so the memory layout of a DateTime object is equivalent to this C struct:

 struct POD_DateTime{  int day;  int month;  int year;  long time  char AM;};

As with class Date, the non-polymorphic member functions of DateTime have no effect on the size or memory layout of the object.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: