C++ unrestricted union workaround

Posted by Chris on Stack Overflow See other posts from Stack Overflow or by Chris
Published on 2010-10-07T18:40:11Z Indexed on 2012/10/08 15:38 UTC
Read the original article Hit count: 116

#include <stdio.h>

struct B { int x,y; };

struct A : public B {
    // This whines about "copy assignment operator not allowed in union"
    //A& operator =(const A& a) { printf("A=A should do the exact same thing as A=B\n"); }
    A& operator =(const B& b) { printf("A = B\n"); }
};

union U {
    A a;
    B b;
};

int main(int argc, const char* argv[]) {
    U u1, u2;
    u1.a = u2.b;    // You can do this and it calls the operator =
    u1.a = (B)u2.a; // This works too
    u1.a = u2.a;    // This calls the default assignment operator >:@
}

Is there any workaround to be able to do that last line u1.a = u2.a with the exact same syntax, but have it call the operator = (don't care if it's =(B&) or =(A&)) instead of just copying data? Or are unrestricted unions (not supported even in Visual Studio 2010) the only option?

© Stack Overflow or respective owner

Related posts about c++

Related posts about variable-assignment