2

An example is as follows:

struct X {
    union {
        X* px;
        void* pv;
    } U;
    X();
};
X::X() : /* How to initialize px here? */
{}

My question is: how to initialize a union sub-object from the mem-initializer-list of a constructor of a class?

jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
ZhangXiongpang
  • 280
  • 2
  • 7
  • possible duplicate of [Can I initialize a union in a mem-initializer?](http://stackoverflow.com/questions/13056366/can-i-initialize-a-union-in-a-mem-initializer) – ecatmur Oct 21 '13 at 10:31

2 Answers2

3

You need to give the union a constructor as well:

struct X {
    union U_T {
        X* px;
        void* pv;
        U_T(X* ptr) : px(ptr)
        {}
    } U;
    X(X* ptr);
};
X::X(X* ptr) : U(ptr)
{}

Note that this is not necessary if all you want to do is initialize to 0. The compiler generated default constructor of the union will already do that for you. In that case, simply define your variables as follows instead to get value-initialization:

X x = X();
ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
  • If you're not stuck in the past, then you can use brace-initialisation to initialise the first union member, without all that messing around with constructors. – Mike Seymour Oct 21 '13 at 11:12
1
X::X(X * x) : U{x} {}

Unless you're stuck with pre-2011 initialisation, or need to initialise something other than the first union member; then you'll need a constructor for the union, as suggested by another answer.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644