KK2491
KK2491

Reputation: 508

C++ Unintialized struct member - field does not exist

I have the below structures in my C++ code.

struct XYZ {
  double x;
  double y;
  double z;
};

struct Data {
  XYZ xyz_point;
  double item_1;
  double item_2;
  double item_3;
};

In my code I create a vector of structure Data.

std::vector<Data> data_vector;

for (i = 0; i < 5; i++) {
   Data data_point_1;
   data_point_1.xyz_point.x = 10.0;
   data_point_1.xyz_point.y = 11.0;
   data_point_1.xyz_point.z = 12.0;
   data_point_1.item_1 = 13.0;
   data_point_1.item_2 = 14.0;
   data_point_1.item_3 = 15.0;
   data_vector.push_back(data_point_1);
}

Code build successful without any errors, however during the CPP_Check I get the below warnings/error. data_point_1 does not have the field x, y and z.

[test.cc:122]: (error: uninitStructMember) Uninitialized struct member: data_point_1.x
[test.cc:122]: (error: uninitStructMember) Uninitialized struct member: data_point_1.y
[test.cc:122]: (error: uninitStructMember) Uninitialized struct member: data_point_1.z

Could you please help me to resolve this.

Thank you,

Upvotes: 4

Views: 664

Answers (1)

Bathsheba
Bathsheba

Reputation: 234875

push_back requires a default constructor. The compiler is able to supply that, but it doesn't initialise the doubles.

CPP_Check is spotting that.

One fix is to use emplace_back instead with the initialiser-list syntax. That doesn't require a default constructor. Another option is to supply a default constructor that initialises the members.

Upvotes: 5

Related Questions