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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With