C Unions and polymorphism

Possible duplicate:
How to model OO-style polymorphism in C?

I am trying to use unions to create polymorphism in C. I am doing the following.

typedef struct{ ... ... } A; typedef struct{ ... ... } B; typedef union{ A a; B b; }C; 

My question is: how can I get a method that accepts type C, but also allows the use of A and B. I want the following to work:

If I define a function:

 myMethod(C){ ... } 

then I want this to work:

 main(){ A myA; myMethod(myA); } 

This is not true. Any suggestions?

+3
source share
3 answers

GNU and IBM support the transparent_union extension:

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

and then you can use A or B or C transparently:

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

See Attribute of type transparent_union (C only) .

+3
source

You must use explicit type conversion:

 A myA; myMethod((C) myA); 
0
source

The short answer is that in C you cannot.

In C ++, you can overload myFunction() and provide several implementations.

In C, you can only have one myFunction() . Even if you could declare a function so that it could accept A , B or C (for example, as void* ), it would not be possible to find out which one it was supplied from.

0
source

Source: https://habr.com/ru/post/916477/


All Articles