Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Intermediate
Jun 4, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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
  int day;
  int month;
  int year;
  Date(); //current date
  bool isLeap() const;
  bool operator == (const Date& other);

class DateTime: public Date
  long time; //additional members
  char AM // AM or PM?
  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.

Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date