devxlogo

Accessing a C++ Object in C Code: A Concrete Example

Accessing a C++ Object in C Code: A Concrete Example

The C++ Standard guarantees that within every instance of class Date, data members are set down in the order of their declarations (static data members are stored outside the object and are therefore ignored). Consider this declaration of the class Date:

 class Date{public:  int day;  int month;  int year;  Date(); //current date  ~Date();  bool isLeap() const;  bool operator == (const Date& other);};

There is no requirement that members be set down in contiguous memory regions; the compiler can insert additional padding bytes between data members to ensure proper alignment. However, this is also the practice in C, so you can safely assume that a Date object has a memory layout that is identical to that of this C struct:

 struct POD_Date/* the following struct has memory layout that is identical to a Date object */{  int day;  int month;  int year;};

Consequently, a Date object can be passed to C code and treated as if it were an instance of POD_Date. You might be surprised that the memory layout in C and C++ is identical in this case; class Date defines member functions in addition to data members, yet there is no trace of these member functions in the object’s memory layout. Where are these member functions stored? C++ treats nonstatic member functions as static functions. In other words, member functions are ordinary functions. They are no different from global functions, except that they take an implicit this argument, which ensures that they are called on an object and that they can access its data members. An invocation of a member function is transformed to a function call, in which the compiler inserts an additional argument that holds the address of the object.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist