Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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
Thanks for your registration, follow us on our social networks to keep up-to-date