3

I have the next structs:

struct B
{
   int a;
   int b;
};

struct D: public B
{
   int c;
};

I want to initialize some variable of struct D in compile time, like if I would initialize the struct B it would looks like:

B b1 = { value_of_a, value_of_b };

I tried to do this in next ways, but it didn't compile:

D d1 = { { value_of_a, value_of_b } , value_of_c };
D d2 = { value_of_a, value_of_b , value_of_c };

If I change the struct to:

struct D
{
   B bb;
   int c;
};

it compiles with "d1" and "d2" initialization.

So, the question is how I can initialize the derived struct? And if there is now rule for initializing derived struct, what is the reasons?

Thank you.

Vugar
  • 99
  • 1
  • 5
  • 1
    Please just use [**Member Initialization list**](http://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor/8523361#8523361) in C++. – Alok Save May 12 '12 at 14:30
  • But that list goes to a constructor method. OP is asking how to set the values outside a constructor, i.e. for a single instance instead of all the instances. – Antti Huima May 12 '12 at 14:34
  • What is the real objective here? Are you concerned about the initialization time? – Vaughn Cato May 12 '12 at 14:41
  • Exactly, I need to initialize it outside the constructor in compile time. – Vugar May 12 '12 at 14:42

1 Answers1

1

Your D that derives from B isn't an aggregate (because it has a base class), so you can't initialise it using the aggregate initialisation syntax. You need to use a constructor and initialisation list.

Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80
  • 1
    See this link (for Visual C++) http://msdn.microsoft.com/en-us/library/0s6730bb%28v=vs.71%29.aspx – A B May 12 '12 at 15:39