Re: void* question
- From: "Tomás Ó hÉilidhe" <toe@xxxxxxxxxxx>
- Date: Mon, 11 Feb 2008 15:15:05 GMT
Janet:
Maybe I should elaborate on the question. Basically I'm coming from
JAVA and trying to implement polymorphism via an array of function
pointers.
Rather than an array of function pointers, we simply have a struct
containing different kinds of function pointer, reason being that we
have the freedom to specify different return values and arguments for
each of the functions.
The functions all take the same arguments, but they have different
return values, e.g.
int f1(int x, int y);
double f2(int x, int y);
Yes, see, here is your problem. You should use a struct instead.
Imagine you had the following in Java:
(I don't actually know Java so I'm going to write C++ code, but
hopefully you'll get the idea)
class BaseClass {
public:
virtual void Speak(void) { WriteToScreen("I like ice-cream"); }
virtual double GetValue(void) { return 7.2; }
};
class Derived1 : BaseClass {
public:
virtual void Speak(void) { WriteToScreen("I like custard"); }
virtual double GetValue(void) { return 2.44; }
};
class Derived2 : BaseClass {
public:
virtual void Speak(void) { WriteToScreen("I like jelly"); }
virtual double GetValue(void) { return 63.8; }
};
If we wanted to implement this in C, then we'd have:
struct VTable {
void (*const Speak)(void);
double (*const GetValue)(void);
};
struct BaseClass {
VTable const *const pvt;
};
struct Derived1 {
VTable const *const pvt;
};
struct Derived2 {
VTable const *const pvt;
};
Then, if you wanted to invoke Speak on an object, you'd do:
void ExploitPolymorphism(Derived2 *const p)
{
p->pvt->Speak();
p->pvt->GetValue();
}
(And yes, the methods I've written should of course have been declared
const, but I left it out so as not to clutter things).
--
Tomás Ó hÉilidhe
.
- References:
- void* question
- From: Janet
- Re: void* question
- From: Eric Sosman
- Re: void* question
- From: Flash Gordon
- Re: void* question
- From: Jack Klein
- Re: void* question
- From: Janet
- void* question
- Prev by Date: Re: A solution for the allocation failures problem
- Next by Date: Re: A solution for the allocation failures problem
- Previous by thread: Re: void* question
- Next by thread: Re: void* question
- Index(es):
Relevant Pages
|