Mapping a C++ Class to a C Structure
A C++ class without virtual functions can be mapped to a corresponding C structure, but there are fundamental differences between both data types. The C++ class contains data members and member functions to access and manipulate these data members. The corresponding C structure contains only the data members, but not the member functions contained in the C++ class.
Figure 1 shows the C++ class Class1
and Figure 2 shows the corresponding C structure.
class Class1
{
public:
int m1;
int m2;
int m3;
f1();
f2();
f3();
};
struct Class1
{
int m1;
int m2;
int m3;
};
To access a C++ class from a C program you need to write your own functions to inspect and manipulate the class data members directly.
Note: While data members in the C++ class can be public,
protected, or private, the variables in the corresponding C structure
are always publicly accessible. You might
eliminate the safeguards built into the C++ language.
You can use C++ operators on this class if you supply your own definitions of these operators in the form of member functions.
When you write your own C++ classes that you want to access from
other languages:
- Do not use static data members in your class, because they are not part of the C++ object that is passed to the other language.
- Do not use virtual functions in your class, because you cannot
access the data members because the alignment of the data members
between the class and the C structure is different.
Note: By making all data members of a class publicly accessible to programs written in other languages, you might be breaking data encapsulation.