0

I have problem with initializating members of structures inside union. Union is a class member. I would like to initialize int members a 0 value. I found some similar solutions, but they didn't help me to solve my problem. I mean solution like initialization list or other, not m_union.structure1.value_s1 = 0

I suppose I need to create constructors inside structures? How should it look? Could I initialize all members inside union's body? To not do that in class constructor after creating a class member?

typedef union U1
{
    struct S1
    {
        int value_s1;

    }structure1;

    struct S2
    {
       int value_s2;
       int number_s2;

    }structure2;

    struct S3
    {
       int value_s3;
       int number_s3;

    }structure3;

}UNION_TYPE;


class Test_Class
{
public:
    Test_Class();
    UNION_TYPE m_union;
};


Test_Class::Test_Class()
{

}
timrau
  • 22,578
  • 4
  • 51
  • 64
Wrthyn
  • 1
  • Have you considered adding a constructor to your union? – user4581301 Dec 12 '18 at 18:31
  • Unrelated: There's usually no need for the `typedef` trick in C++. `union UNION_TYPE { ... };` is enough to get `UNION_TYPE m_union;` working. – user4581301 Dec 12 '18 at 18:34
  • Yes I tried, but without result. I didn't create this union and I prefer to not modify this typedef, I see in this situation it's not needed. – Wrthyn Dec 12 '18 at 19:33
  • Was going to write up an answer, but as always someone's beaten me to it: https://stackoverflow.com/questions/321351/initializing-a-union-with-a-non-trivial-constructor – user4581301 Dec 12 '18 at 19:58
  • Sidenote: The layout suggests C-style thinking, and C++ does not give the same guarantees about unions that C does. Be particularly careful with unions containing non-POD data. – user4581301 Dec 12 '18 at 20:01
  • Thanks very much :) I saw this post before I asked a question, but didn't saw a solution there. So for POD data, memset is solution for my problem and it guarantees that all POD data types will be initialized with 0 by this ```U1() { memset( this, 0, sizeof( U1 ) ); }```? Did I understood well? – Wrthyn Dec 16 '18 at 20:52
  • That looks good to me. – user4581301 Dec 17 '18 at 18:29

0 Answers0