Search code examples
c++inheritanceunions

Overlay subclass union ontop of superclass union


I'm wondering if it's possible to append members to a C++ union in a subclass.

class A { 
    ...
    union { int a; int b; };
 };

 class B : public A {
     ...
     int c; //<- Can this use the same storage as the union?
 };

A more concrete example would be the idea of a tagged union, where you'd like to have a subclass that adds a type to the union.


Solution

  • You said,

    I'm wondering if it's possible to append members to a C++ union in a subclass.

    The language does not allow extending a union. Appending members to a union is not possible.

    What's worse, unlike classes and structs, which can be extended by creating sub-classes(structs), unions cannot have base classes. They may not be used as base classes either.