Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Unions and Polymorphism [duplicate]

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?

like image 895
AFS Avatar asked Oct 07 '22 18:10

AFS


1 Answers

GNU and IBM support the transparent_union extension:

typedef union __attribute__((transparent_union)) {
        A a;
        B b;
} C;

and then you can use As or Bs or Cs transparently:

A foo1;
B foo2;
C foo3;
myMethod(foo1);
myMethod(foo2);
myMethod(foo3);

See The transparent_union type attribute (C only).

like image 180
hroptatyr Avatar answered Oct 10 '22 10:10

hroptatyr