Possible Duplicate:
How can I simulate OO-style polymorphism in C?
I'm trying to use unions to create polymorphism in C. I do the following.
typedef struct{
...
...
} A;
typedef struct{
...
...
} B;
typedef union{
A a;
B b;
}C;
My question is: how can I have a method that takes type C, but allows for A and B's also. I want the following to work:
If I define a function:
myMethod(C){
...
}
then, I want this to work:
main(){
A myA;
myMethod(myA);
}
It doesn't. Any suggestions?
GNU and IBM support the transparent_union
extension:
typedef union __attribute__((transparent_union)) {
A a;
B b;
} C;
and then you can use A
s or B
s or C
s transparently:
A foo1;
B foo2;
C foo3;
myMethod(foo1);
myMethod(foo2);
myMethod(foo3);
See The transparent_union type attribute (C only).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With