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?
You have to use explicit type conversion:
The short answer is that in C, you can't.
In C++, you could overload
myFunction()
and provide several implementations.In C, you can only have a single
myFunction()
. Even if you could declare the function so that it could takeA
,B
orC
(e.g. asvoid*
), it would have no way of knowing which of the three it has been supplied with.GNU and IBM support the
transparent_union
extension:and then you can use
A
s orB
s orC
s transparently:See The transparent_union type attribute (C only).