- Class Envy
- Inherited Fear
- The Forgotten Benefit: Debugging
- Hope for C Programmers
- Conclusion
Hope for C Programmers
Unfortunately, some embedded projects won't have a C++ compiler, or the CPU selection will preclude the use of C++. Yet, even in these circumstances, you don't necessarily have to abandon object-oriented programming principles. For example, in your public functions, you can mandate that the caller pass in a handle (a this pointer) returned from a simulated constructor function. This technique permits other functions to access class-specific resources that are invisible to external parties (see Listings 1 and 2). Although this trick isn't as elegant or as flexible as a true C++ class, it will let you model object-oriented concepts.
Listing 1 A Typical C++ Class
class Blob { void getBlobInfo( int attribute, int *pGetInfo); void setBlobInfo( int attribute, int setInfo); } ;
Listing 2 illustrates how C can model the C++ Blob class methods in Listing 1. The newBlob() function (or simulated constructor) returns a handle (this pointer) that's required for all related functions in that API set.
Listing 2 Modeling the Listing 1 Class in C
typedef void * BlobHandle; BlobHandle newBlob( void ); void deleteBlob( BlobHandle ); void getBlobInfo( BlobHandle handle, int attribute, int *pGetInfo); void setBlobInfo( BlobHandle handle, int attribute, int setInfo);