C++ Structure Definition
In C++, a structure is a user-defined data type that groups together related data items of different data types. A structure can contain any combination of primitive data types, other structures, pointers, and arrays.
To define a structure in C++, you can use the struct
keyword followed by the name of the structure and a set of braces that enclose the structure members. For example:
struct Person { std::string name; int age; double height; };
In this example, we define a Person
structure that contains three members: a std::string
object named name
, an integer variable named age
, and a double variable named height
.
Once the structure is defined, you can create variables of that structure type by using the struct
keyword followed by the structure name, as shown below:
Person p1; // create a variable of type Person
You can also initialize the members of the structure at the time of creation using a set of braces that contain the member values, as shown below:
Person p2 = {"John", 25, 1.75}; // create a variable of type Person and initialize its members
You can access the members of a structure variable using the dot operator (.) followed by the member name, as shown below:
p1.name = "Jane"; p1.age = 30; p1.height = 1.65;
In this example, we set the values of the name
, age
, and height
members of the p1
variable.