Using inheritance in a union

I was wondering if anyone knows if it is possible to somehow use inheritance within the union.

In the example below, the TestFails union TestFails not contain the variable a in the Base structure, but TestWorks works.

 struct Base { int a; }; union TestFails { struct : public Base {}; int b; }; union TestWorks { struct { int a; }; int b; }; int main() { TestWorks works; works.a = 0; TestFails fails; fails.a = 0; return 0; } 

You can test the code here: http://ideone.com/dUzpOR

+7
c ++ inheritance unions
source share
3 answers

First of all, your assumption that TestWorks is not working properly. This is not standard C ++ - just an extension for it - it is called an unnamed anonymous structure - and when you compile with pedantic parameters, you get:

prog.ccβˆ—:27: error: ISO C ++ prohibits anonymous structures [-Wpedantic]
struct: public Base {};

  ^ 

prog.cc:11:22: error: ISO C ++ prohibits anonymous structures [-Wpedantic]
struct {int a; };

To solve your problem - just name these anonymous structures:

 union TestFails { struct : public Base {} s; // ^ int b; }; union TestWorks { struct { int a; } s; // ^ int b; }; 
+1
source share

The answer is no. There are many dark corners in C ++, but this is not one of them :)

classes and structures have inheritance. no unions.

The only way to accomplish what you are trying ... is reorganizing your unions into structures (I say that structs are only because they have a public domain by default, so you don't need to declare them public)

If you try to place a structure within your union, you will need to add an additional area of ​​the new structure in order to access its value.

Just as AndyG's answer shows this:

 union TestFails { struct foo: public Base {}; foo f; int b; }; TestFails fails; fails.fa = 42; std::cout << fails.fa << std::endl; 

If you omit the specified variable and create an unnamed scope that sometimes runs with namespaces, then data cannot be accessed from outside (which is the point of this in the first place).

+1
source share

Not sure if this helps, but it works:

 struct Base { int a; }; struct Foo : Base { int b;}; union TestFailsNot { Base base; Foo foo; int b; }; int main() { TestFailsNot failsNot; failsNot.foo.a = 0; failsNot.base.a = 3; // maybe not what you want to do, but it works } 
0
source share

All Articles