Prashanth Ellina wrote:
I have a feeling that [Obect Oriented Programming] can be done in C also.
Correct.
I have used a structure to hold member variables and function pointers.
Pointers to *callback* functions.
The structure is used as a class to create new 'objects'.
But I hit a problem.
How do I access these 'member variables' from the function
that is pointed to by the function pointer in the structure.
You must pass a pointer to the function explicitly.
I would really appreciate help with this
and a code sample will be wonderful.
typedef struct X {
int i;
const
struct X* (*f)(const struct X*);
} X;
const
X* X_actual_f(cons t X* this) {
fprinf(stdout, "this->i = %d\n", this->i);
return this;
}
inline static
X X_create(int i) {
X value;
value.i = i;
value.f = X_actual_f;
return value;
}
But actual implementations of run-time polymorphism
don't store pointers to functions in the object itself.
They store a pointer to a virtual function table
which is initialized in the class definition so that
the virtual functions are associated with the *class*
and *not* any object which is an instance of that class.
typedef struct X {
int i;
const
void* pV; // virtual function table pointer
} X;
const
X* X_actual_f(cons t X* this) {
fprinf(stdout, "this->i = %d\n", this->i);
return this;
}
struct vTable_t {
X* (*f)(const X*);
} vTable_t;
vTable_t X_vTable = { X_actual_f; };
X X_create(int i) {
X value;
value.i = i;
value.pV = (void*)(&X_vTab le);
return value;
}
const
X* X_virtual_f(con st X* this) {
return ((vTable_t*)(th is->pV))->f(this);
}
You call X_virtual_f(con st X*) instead of X_actual_f(cons t X*)
so that it will work for classes
typedef struct Y {
X x;
// . . .
} Y;
const
X* Y_actual_f(cons t Y*);
derived from X
but call Y_actual_f(cons t Y*) instead of X_actual_f(cons t X*).
Go to Google Groups:
http://groups.google.com/
and search for
run-time polymorphism in C (long)
in the comp.lang.c newsgroup. You should find:
From: E. Robert Tisdale (E.************ **@jpl.nasa.gov )
Subject: run-time polymorphism in C (long)
Newsgroups: comp.lang.c
Date: 2004-05-12 22:55:28 PST