2

I have the following C++ code (in VS2017):

struct OptionA
{
    std::string s1;
};

struct OptionB
{
    std::string s2;
};

struct Inner
{
    int b;
    union {
        OptionA optA;
        OptionB optB;
    }Options;

};

struct Outer
{
    int a;
    Inner b;
}

When I tried to declare this struct:

int main()
{
   Outer obj; 
};

I get the compilation error:

error C2280: 'Outer::Outer(void)': attempting to reference a deleted function

This way of declaring a struct should work fine. I feel this error is something to do with the constructor of the structure.

How do I solve this issue ?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
codeLover
  • 3,720
  • 10
  • 65
  • 121

2 Answers2

4

Your problem is with

union {
    OptionA optA;
    OptionB optB;
}Options;

in Inner. Both OptionA and OptionB are not trivially constructable so when you make a union of them it deletes the constructor of the union. This means Options is not default constructable and therefore Inner is not either since you don't provide a default constructor.

You are going to need to provide your own constructor and destructor for the union to handle constructing and destructing the proper member. You can see how to make a tagged union to properly destruct the union here

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
3

According to this:

If a union contains a non-static data member with a non-trivial special member function (copy/move constructor, copy/move assignment, or destructor), that function is deleted by default in the union and needs to be defined explicitly by the programmer.

So you need to define both constructor and destructor for your union in Inner. But because it is an anonymous union, you have to give it a name first:

struct Inner
{
    int b;
    union A {
        A();
        ~A();
        OptionA optA;
        OptionB optB;
    } Options;
};