Slater Slater - 1 year ago 80
C++ Question

Union Behaviour

Is it possible to get the following behavior out of a Union?

class A : public Base //Base is an abstract base class.
A( int );
virtual void foo() //A virtual function from Base.
//I don't want to have to specify if it's oneOption or twoOption.
// I would like it to just call whichever one's is defined in mData.;
union B
C oneOption; //A class which inherits from Base.
D twoOption; //Another class which inherits from Base.
} mData;

Basically, I would like to have a class containing a Union of derived classes. Then I would like to implement all the virtual functions base class in terms of my Union.

I can try to rephrase this if it's too confusing.


Answer Source

Technically you can, the syntax is correct and the compiler will let you treat both instance variables as you'd expect (with the same constraints that applies in general to unions).

In practice it seems unnecessary when there is mutual exclusion, you can easily use a pointer to an instance:

CommonAncestor *mData;

I can see many maintainability issues by using constructs that were meant to be used when polymorphism didn't exist in the language.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download