Browse DevX
Sign up for e-mail newsletters from DevX

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



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

Accessing a C++ Object in C Code: Different Access Specifiers

The fourth restriction on the legality of accessing C++ objects from C code states that all the data members of the class must be declared without an intervening access specifier. This means, theoretically, that the memory layout of a class that looks similar to this example might differ from a class that has the same data members, which are declared in the same order, albeit without any intervening access specifiers:

class AnotherDate  // has intervening access specifiers
  int day;
  int month;
  int year;
  //constructor and destructor
  AnotherDate(); //current date
  //a non-virtual member function
  bool isLeap() const;
  bool operator == (const Date& other);

In other words, for class AnotherDate, an implementation is allowed to place the member 'month' before the member 'day', 'year' before 'month', or whatever. Of course, this nullifies any compatibility with a C struct. However, in practice, all current C++ compilers ignore the access specifiers and store the data members in the order of declaration. So C code that accesses a class object that has multiple access specifiers should work, but there is no guarantee that the compatibility will remain in the future.

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