# I have tried finding an answer to this, but most people just explain
# classes as a more modular way to program. It seems to me that
# (forgetting OO programming which I don't quite understand) the
# structures in C are the same as classes in another language such as C++
# or Java only missing the ability to make the data private.
#
# I've never had this explained sufficiently and would appreciate a good
# answer. It doesn't need to be Mickey Mouse, but I'm not a programmer either.
An object class is tightly coupled combination of data and code, operations on
data are included with and linked to the data. A C structure is typically just
data; when a C structure includes function pointers, the language does not
couple the functions to the structure containing them: it is the responsibility
of the programmer to do so.
You can simulate single inheritance in C with a disciplined use of functions
whose first parameters are always, perhaps, a pointer to the structure of data
and a static structure of function pointers.
A is a class with data members x, y, z and functions X, Y, Z.
B is a subclass with data members p, q, r and functions P, Q, X.
typedef struct A A; typedef struct A_Behaviour A_Behaviour;
typedef struct B B; typedef struct B_Behaviour B_Behaviour;
int A_X(A *this,int i);
int A_Y(A *this,int j);
int A_Z(A *this,int k);
int B_P(B *this,int i);
int B_Q(B *this,int j);
int B_X(B *this,int k);
struct A_Behaviour {
int (*X)(A *this,int i);
int (*Y)(A *this,int j);
int (*Z)(A *this,int k);
};
struct A {
Root super;
A_Behaviour *behaviour;
int x;
int y;
A *z;
};
static A_Behavior = {A_X,A_Y,A_Z};
void new_A(A *a) {
new_Root(&a->super); a->behaviour = &A_behaviour;
a->x = 0; a->y = 0; a->z = 0;
}
struct B_Behaviour {
int (*P)(B *this,int i);
int (*Q)(B *this,int j);
int (*X)(B *this,int k);
};
struct B {
A super;
B_Behaviour *behaviour;
int p;
A *q;
B *r;
};
static B_Behavior = {B_P,B_Q,B_X};
void new_B(B *b) {
new_A(&b->super); b->behaviour = &B_behaviour;
b->p = 0; b->q = 0; b->r = 0;
}
For an object of class B, you call method
b->P with b->behaviour->P(b,i)
b->Q with b->behaviour->Q(b,j)
b->X with b->behaviour->X(b,k)
b->Y with b->super.behaviour->Y(&b->super,j)
b->Z with b->super.behaviour->Z(&b->super,k)
--
Derk Gwen
http://derkgwen.250free.com/html/index.html
I love the smell of commerce in the morning.