Hi, I was just looking for some thoughts from all of you about object oriented programming in C. I have been reading the book Object Oriented Programming with ANSI by Axel-Tobias Schreiner which I'm really enjoying but I get the feeling that implementing OO in C is more work than it's worth. For example in the second chapter, he implements a simple String class that holds a pointer to the overall base class "Class" and a pointer to a char data type:
Code:
struct String {
const void * class; /* must be first */
char * text;
};
The class variable will point to a struct Class type:
Code:
struct Class {
size_t size; // size of class e.g holds size of string class
void * (* ctor) (void * self, va_list * app); // constructor
void * (* dtor) (void * self); // destructor
void * (* clone) (const void * self); // clone function
int (* differ) (const void * self, const void * b);
};
To set the String class up with the necessary constructors, destructors, etc, he creates an instance of the struct Class type, the instance has functions created for the string type and they are used to assign the function pointers in the struct Class.
Code:
static const struct Class _String = {
sizeof(struct String),
String_ctor, String_dtor,
String_clone, String_differ
};
The address of this is passed into a "new" function that allocates the memory for the class and calls the constructor. With this approach he also created another function called differ that was used as a polymorphic function which basically calls the specific classes differ function, in the case of the String class, it would call String_differ.
I guess my problem with this, is the fact that there seems to me that there is a lot of unnecessary functions and pointers introduced by this approach. I'm wondering if this approach creates more overhead compared to creating the functions necessary for each class and just passing in the class specific to those functions. In essence that is what Axel-Tobias Schreiner is doing anyway, expect there is no creation of function pointers and it seems there will be less overhead as the "global" differ function used with all objects won't need to be used either.
I know this is just an example of OOP in C, but it does seem a bit of a waste of time to create all these function pointers and polymorphic functions, just so you can access the functions like methods in a "real" class. Just wondering what you all think about this?
Also, is this how classes were first implemented in C++ ( when it was known as C with Classes )?