justik
justik

Reputation: 4255

Structure in structure, initialization

How to initialize an inner structure inside the outer structure?

struct TOuter
{
   struct TInner
   {
       bool b1, b2;
       TInner () : b1 (false), b2(false) {}
   };

   bool b3;

   TOuter (): TOuter::TInner(), b3(true) {} // Error
};

Upvotes: 2

Views: 316

Answers (2)

Rei
Rei

Reputation: 69

You should create an instance of TInner inside TOuter.

struct TOuter
{
   struct TInner
   {
       bool b1, b2;
       TInner () : b1 (false), b2(false) {}
   };

   TInner inner;
   bool b3;

   TOuter (): inner(), b3(true) {}
};

You can also do it by writing the variable name right after the struct like this:

    struct TInner
    {
        bool b1, b2;
        TInner () : b1 (false), b2(false) {}
    } inner;

Upvotes: 0

jpalecek
jpalecek

Reputation: 47762

In this case, you have no object of the TInner struct, so there's no need to initialize anything.

Other than that, it's just the same as with any other class/struct type:

struct TOuter
{
   struct TInner
   {
       bool b1, b2;
       TInner () : b1 (false), b2(false) {}
   };

   bool b3;

   TInner foo;

   TOuter (): foo(), b3(true) { // member variable
     TInner x; // local variable
   }
};

TOuter::TInner out; // need qualified name, bc. TInner is not in scope
...
bar(TOuter::TInner()); // temporary

Upvotes: 2

Related Questions