What is the method for assigning a value to a C++ struct?
In C++, you can assign values to a struct using the following methods:
- Assign values to members one by one: Values can be assigned one by one by directly accessing the members of the structure. For example:
struct Person {
std::string name;
int age;
};
Person person;
person.name = "Alice";
person.age = 25;
- Initializing lists: It is possible to initialize all members of a struct variable at once using an initialization list when defining it. For example:
Person person = {"Bob", 30};
- Using the struct assignment operator: You can use the assignment operator (=) to assign the value of one struct variable to another struct variable. For example:
Person person1 = {"Charlie", 35};
Person person2;
person2 = person1;
Please note that if a structure contains pointers or dynamically allocated memory, special care should be taken when handling assignment operations to avoid issues such as memory leaks or dangling pointers.