Velocity Reviews > struct and function-pointer casting

# struct and function-pointer casting

Maurice
Guest
Posts: n/a

 04-29-2005
Hi,

Is it legal to cast from void(*)(A*) to void(*)(B*)?
Is it legal to cast from struct Derived{Base b; ...} to struct Base?

I'm trying to get some inheritance and polymorphism in C
and I end up with the following code:

struct Base {
void(*func)(struct Base*);
};

struct Derived {
struct Base base;
/* ... */
};

void derived_func(struct Derived* d) {}

int main() {
struct Derived d = {{derived_func} /*...*/ };

struct Base* b = &d;
b->func(b);
}

Thank you.

Eric Sosman
Guest
Posts: n/a

 04-29-2005

Maurice wrote:
> Hi,
>
> Is it legal to cast from void(*)(A*) to void(*)(B*)?
> Is it legal to cast from struct Derived{Base b; ...} to struct Base?
>
> I'm trying to get some inheritance and polymorphism in C
> and I end up with the following code:
>
> struct Base {
> void(*func)(struct Base*);
> };
>
> struct Derived {
> struct Base base;
> /* ... */
> };
>
> void derived_func(struct Derived* d) {}
>
> int main() {
> struct Derived d = {{derived_func} /*...*/ };
>
> struct Base* b = &d;
> b->func(b);
> }

No; the type of `derived_func' does not match the
type of the `func' element in `struct Base', so the
compiler should object to the initialization. One
simple fix is

void derived_func(struct Base *b) {
struct Derived *d = (struct Derived*)b;
...
}

The conversions of the struct pointers are all right:
any struct pointer can be converted to and from a pointer
to the struct's first element (unless that element is a
bit-field; you can't point to a bit-field).

--
http://www.velocityreviews.com/forums/(E-Mail Removed)

Maurice
Guest
Posts: n/a

 04-30-2005
Eric Sosman <(E-Mail Removed)> wrote:
> No; the type of `derived_func' does not match the
> type of the `func' element in `struct Base', so the
> compiler should object to the initialization. One
> simple fix is
>
> void derived_func(struct Base *b) {
> struct Derived *d = (struct Derived*)b;
> ...
> }

Ok, not as neat as it would be in my code but I think I can
live with it.

> The conversions of the struct pointers are all right:
> any struct pointer can be converted to and from a pointer
> to the struct's first element (unless that element is a
> bit-field; you can't point to a bit-field).

That is good.