dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
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 3, 1999

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date