C++ Structures (struct)

In C++, a structure (or struct) allows multiple related variables to be grouped together under one name. This makes organizing and managing complex data more efficient than using individual variables.

Tutorials dojo strip

Defining a Structure

Unlike arrays, structures can store multiple data types, including int, string, and bool.

Example: Declaring a Structure

C++

This structure groups an engine size (int) and a model name (string) under motorcycle.

Assigning and Accessing Structure Members

Use the dot (.) operator to assign values and access structure members.

Example: Assigning and Printing Structure Members

C++

Output:

C++

Using One Structure for Multiple Variables

To create multiple instances of the same structure, separate structure variables with commas (,).

Example: Two Motorcycles Using One Structure

C++

Output:

C++

Named Structures

To make a structure reusable anywhere, give it a name after the struct keyword.

Example: Creating a Named Structure

C++

To declare a variable using this structure:

C++

Example: Using a Named Structure

C++

Tutorials dojo strip