Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using inheritance within a union

I was was wondering if anyone knows if it's possible to use inheritance within a union somehow.

In the example below, the TestFails union will not contain the a variable within the Base struct, while TestWorks does work.

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

like image 612
Artoo Avatar asked Dec 03 '15 20:12

Artoo


1 Answers

The answer is no. There are a lot of dark corners in c++ but this is not one them :)

classes and structs have inheritance. unions do not.

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

If you try to place a struct inside your union you will need add the extra scope of the new struct in order to access its value.

Exactly as AndyG's answer shows this:

union TestFails
{
    struct foo: public Base {};
    foo f;
    int b;
};

TestFails fails;
fails.f.a = 42;
std::cout << fails.f.a << std::endl;

If you omit a variable named and create an unnamed scope which is done with namespaces occasionally then the data can not be accessed externally (which is the point of this in the first place)

like image 140
Dan Avatar answered Oct 20 '22 02:10

Dan