Search code examples
c++structnestedinitializationc++20

How to initialize nested struct in C++?


Let's say I have following declaration in the C++:

struct Configuration {

 struct ParametersSetA {
    float param_A_01;
    float param_A_02;
        float param_A_03;
 } parameters_set_A;

 struct ParametersSetB {
    float param_B_01;
    float param_B_02;
 } parameters_set_B;

};

Then somewhere in the code I have following definition:

Configuration config = {
 
 .parameters_set_A = {
  .param_A_01 = 1.0f,
  .param_A_02 = 2.0f, 
  .param_A_03 = param_A_01 + param_A_02;
  },

 .parameters_set_B = {
  .param_B_01 = 0.50f,
  .param_B_02 = 0.75f
  }
};

My question is whether the initialization (especially as far as the param_A_03 item in the nested struct ParametersSetA) I have used above is correct in the C++?


Solution

  • The problem is that we can't use any of the unqualified names param_A_01 or param_A_02 or an expression that involves any of the two like param_A_01 + param_A_02 as initializer forparam_A_03.

    Additionally, you have incorrectly put a semicolon ; after param_A_01 + param_A_02 instead of comma , . I've corrected both of these in the below shown modified program:

    Method 1

    //create constexpr variables 
    constexpr float A1 = 1.0f;
    constexpr float A2 = 2.0f;
    Configuration config = {
     
     .parameters_set_A = {
      .param_A_01 = A1,
      .param_A_02 = A2, 
    //--------------vv---vv---->use those constexpr variable(also semicolon is removed from here)
      .param_A_03 = A1 + A2
      },
    
     .parameters_set_B = {
      .param_B_01 = 0.50f,
      .param_B_02 = 0.75f
      }
    };
    

    Working demo

    Method 2

    Other option is to use qualified names like config.parameters_set_A.param_A_01 and config.parameters_set_A.param_A_02 as shown below:

    Configuration config = {
     
     .parameters_set_A = {
      .param_A_01 = 1.0f,
      .param_A_02 = 2.0f, 
    //--------------vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv--->qualified name used here
      .param_A_03 = config.parameters_set_A.param_A_01 + config.parameters_set_A.param_A_02 
      },
    
     .parameters_set_B = {
      .param_B_01 = 0.50f,
      .param_B_02 = 0.75f
      }
    };
    

    Working demo