C++ Structure

A structure is a user-defined data type in C++ that enables you to collectively refer to variables of various data kinds. A structure and a class are comparable, however there are some distinctions in terms of access control and member visibility by default.

Basic syntax of structure:

struct structureName {
    dataType1 member1;
    dataType2 member2;
    dataType3 member3;
    // ...
} objectName;

Example:

struct Point {
   int x;
   int y;
};

This defines a structure named “Point” that contains two integer variables: “x” and “y”. You can declare variables of this structure type as follows:

Point p1;
Point p2 = {5, 10};

In the first line, a variable of type “Point” named “p1” is declared. In the second line, a variable of type “Point” named “p2” is declared. Its “x” and “y” members are initialized to 5 and 10, respectively.

A structure’s members can be accessed by using the dot (.) operator:

p1.x = 3;
p1.y = 7;

This sets the “x” and “y” members of “p1” to 3 and 7, respectively.

You can also pass structures as function arguments:

void printPoint(Point p) {
   cout << "(" << p.x << ", " << p.y << ")" << endl;
}

Here, the “printPoint” function takes a “Point” argument and prints its “x” and “y” members.

Structures can also contain other structures as members:

struct Rectangle {
   Point topLeft;
   Point bottomRight;
};

This defines the “topLeft” and “bottomRight” elements of the “Rectangle” structure, both of which are “Point” members.

In general, structures make it simpler to organise and pass around data in your programmes by allowing you to group relevant data under a single name.