A quick and easy explanation of Structures

Structures originally came from the C language and are declared using the keyword “struct”. In C++, the same principle applies as a group of data elements, which are grouped together under one name. Strucutres are very similiar to classes but all the variables in a structure can be accessed.

The variables in a structure are known as elements, and the elements can have different variable types and different lengths. An example of a struct is:

<pre>struct groceries
// members of the struct
string name;
int weight;
double price;
} chips, drinks;      // Objects of the structure

Once the members of the struct are defined, you can access the members directly by using a “.” between the object name and the member name. In the body of the code, the objects and members are being set values and are then outputted on the program.

<pre>int main()
    // Set data for members of the struct
    chips.name = "Smith Chips";
    chips.weight = 500;
    chips.price = 3.00;

    drinks.name = "Coke";
    drinks.weight = 500;
    drinks.price = 2.50;

    // Output the values of the members
    cout << chips.name << "\n";
    cout << chips.weight << "\n";

    cout << chips.price << "\n" << "\n";
    cout << drinks.name << "\n";

    cout << drinks.weight << "\n";
    cout << drinks.price << "\n";

    return 0;
Share this post