learning fellow
learning fellow

Reputation: 97

initialize a structure in constructor initializer list in C++

// I have a structure

 typedef struct
 {
    uint8_t* data;
    uint16_t data_ln;
 } Struc_Data;

//a derived type from this struct

 Struc_Data    tx_struct;

// i have to initialize this 'tx_struct' in constructor initializer list, i am not getting how

 Constr::Constr( ):
    tx_struct  (reinterpret_cast<uint8_t*>(nullptr), 0U)  //this does not work
 {

 }

Upvotes: 0

Views: 4950

Answers (2)

juanchopanza
juanchopanza

Reputation: 227438

Struc_Data is an aggregate, so value-initialization will do if you want to zero-initialize the members:

Constr::Constr( ): tx_struct() {} // or tx_struct{}

Otherwise, use curly-brace initialization:

Constr::Constr( ): tx_struct{nullptr, 42U} {}

Here's a simplified, compiling example:

#include <stdint.h>

typedef struct
{
  uint8_t* data;
  uint16_t data_ln;
} Struc_Data;

struct Foo
{
  Foo() : tx_struct{nullptr, 0U} {}
  Struc_Data tx_struct;
};

Note that in C++ it is unusual to use the typedef syntax for class definitions. The preferred form is

struct Struc_Data { .... };

Upvotes: 2

R Sahu
R Sahu

Reputation: 206627

Another solution:

  1. Change the C style struct to a C++ style struct.
  2. Define a constructor with the required arguments.

    struct Struc_Data
    {
      Struc_Data(uint8_t* data1, uint16_t data2) : data(data1), data_In(data2) {}
      uint8_t* data;
      uint16_t data_ln;
    };
    

Upvotes: 0

Related Questions