[Effective-cpp] Item 34: Understand How to Combine C++ and C in the Same Program.

Klitos Kyriacou Klitos.Kyriacou at reuters.com
Fri Jun 6 05:45:25 EDT 2003


Hi.

> Data Structure Compatibility
> ====================
> Object definitions will not compile in C so it is not 
> possible to directly 
> pass pointers to objects between C and C++. The rules 
> governing the layout 
> of a struct in C++ are consistent with those of C, however, so it is 
> therefore safe to pass pointers to structures back and forth 
> between C and 
> C++. Adding non virtual functions to the C++ version of the 
> struct does not 
> change the structure layout, so pointers to structs with non virtual 
> functions will transfer between C and C++.

About 7 years ago, in my previous job, we started adding C++ code to an
existing, large application written entirely in C up till then. We had
success deriving our C++ classes from the C structs. We could even pass
C++ objects to existing C functions that expected C structs. Any
disadvantages doing it that way?

> Adding virtual functions, 
> however, causes structs to use a different memory layout, and 
> transfer is 
> no longer possible.

Is this necessarily true? If you slice a derived class that has virtual
functions into a POD, C struct (and pass it to a C function) won't the
resulting struct have the same memory layout as the original?

Regards,
Klitos
[ *** LongSig auto truncated *** ]



More information about the Effective-cpp mailing list