All Recipes
Home/Other Features/Designated Initializers
beginner

Designated Initializers

Initialize struct members by name

Example Code

cpp
#include <iostream>
#include <string>
struct Config {
std::string host = "localhost";
int port = 8080;
bool ssl = false;
int timeout = 30;
int max_connections = 100;
};
struct Point3D {
double x = 0;
double y = 0;
double z = 0;
};
int main() {
// Designated initializers - clear and self-documenting
Config server_config{
.host = "api.example.com",
.port = 443,
.ssl = true,
// timeout uses default value
.max_connections = 1000
};
std::cout << "Host: " << server_config.host << std::endl;
std::cout << "Port: " << server_config.port << std::endl;
std::cout << "Timeout: " << server_config.timeout << std::endl; // 30
// Partial initialization
Point3D point{.y = 5.0}; // x=0, y=5, z=0
std::cout << "Point: (" << point.x << ", "
<< point.y << ", " << point.z << ")" << std::endl;
return 0;
}

Explanation

Designated initializers allow initializing struct members by name, making code clearer and less error-prone. Members must be initialized in declaration order, and unspecified members use their default values.

Key Points

  • 1Use .member_name = value syntax
  • 2Members must be in declaration order
  • 3Skipped members use default values
  • 4Makes code self-documenting