I'm trying to do OOP on C (just for fun) and I've come up with a method to do data abstraction by having a struct with the public part and a larger struct with the public part first and then the private part. This way I create in the constructor the whole struct and return it casted to the small struct. Is this correct or could it fail?
Here is an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// PUBLIC PART (header)
typedef struct string_public {
    void (*print)( struct string_public * );
} *string;
string string_class_constructor( const char *s );
void string_class_destructor( string s );
struct {
    string (*new)( const char * );
    void (*delete)( string );
} string_class = { string_class_constructor, string_class_destructor };
// TEST PROGRAM ----------------------------------------------------------------
int main() {
    string s = string_class.new( "Hello" );
    s->print( s );
    string_class.delete( s ); s = NULL;
    return 0;
}
//------------------------------------------------------------------------------
// PRIVATE PART
typedef struct string_private {
    // Public part
    void (*print)( string );
    // Private part
    char *stringData;
} string_private;
void print( string s ) {
    string_private *sp = (string_private *)( s );
    puts( sp->stringData );
}
string string_class_constructor( const char *s ) {
    string_private *obj = malloc( sizeof( string_private ) );
    obj->stringData = malloc( strlen( s ) + 1 );
    strcpy( obj->stringData, s );
    obj->print = print;
    return (string)( obj );
}
void string_class_destructor( string s ) {
    string_private *sp = (string_private *)( s );
    free( sp->stringData );
    free( sp );
}
 
     
     
     
     
     
     
     
     
    