How to Initialize a Struct

beginner c++11 classes

Related: Constructors

In C++ we initialize a struct with values between curly braces({}).

#include <string>
#include <iostream>

struct Point {
  float x, y, z;
};

struct Person {
  std::string name;
  int age;
  bool married;
};

int main() {
  Point origin{0, 0, 0};
  std::cout << origin.x << ", " << 
               origin.y << ", " << 
               origin.z << "\n";

  Point elsewhere{3.0f, 4.0f, 5.0f};
  std::cout << elsewhere.x << ", " << 
               elsewhere.y << ", " << 
               elsewhere.z << "\n";

  Person maria{"Maria", 42, true};
  std::cout << maria.name << ": " << maria.age << "\n";
  Person nushi{"Nushi", 12, false};
  std::cout << nushi.name << ": " << nushi.age << "\n";
}
0, 0, 0
3, 4, 5
Maria: 42
Nushi: 12

You can specify default values right in the declaration of the struct. Note that if you do this C++ generates a default constructor for you meaning the previous method of initializing fields with values between curly braces(“{}”) is disabled. Here’s an example:

#include <string>
#include <iostream>

struct Point {
  float x = 0, y = 0, z = 0;
};

struct Person {
  std::string name = "John Doe";
  int age = 25;
  bool married = true;
};

int main() {
  Point origin;
  std::cout << origin.x << ", " << 
               origin.y << ", " << 
               origin.z << "\n";

  Person unknown;
  std::cout << unknown.name << ": " << unknown.age << "\n"; 
}
0, 0, 0
John Doe: 25

For more C++ By Example, click here.