Page Content

Tutorials

Structures In C++ (struct): Defining Custom Data Types

Structures in C++

The fundamental mechanism for combining related data pieces into a single, user-defined data type in C++ is called a structure (struct). They make your code more logically organized and manageable by enabling you to containerize data that makes sense together, like the characteristics of a book or an employee.

The concept, application, and salient characteristics of structures are explained in detail below:

Defining a Structure

The term “struct” is used to specify a structure. The declaration states the structure’s members inside curly brackets {} and gives the structure’s name, which is frequently referred to as a “tag”. A semicolon (;) must be used to end the structure declaration, in contrast to control blocks for functions or loops.

Example Syntax:

struct [structure tag]
{
    member definition;
    member definition;
    ...
    member definition;
} [one or more structure variables (optional)];

For example, dollars and cents could be grouped to build a framework for US currency:

struct USCurrency {
    int dollars;
    int cents;
};

A time_of_day structure with hours, minutes, and seconds is an additional illustration:

struct time_of_day {
    int hour;
    int min;
    int sec;
};

Structure Members

The members, elements, or fields are the variables that are contained within a structure. Members of structures, as opposed to arrays, can have a variety of data types. While a Sales_data struct might include a double, an unsigned int, and a std::string, USCurrency, for instance, has two int members. It is possible for structures to be nested that is, to contain other structures.

Defining Structure Variables (Objects/Instances)

A structure definition provides a blueprint without allocating memory or variables. Before creating an instance of a structure, you must declare a structure variable.

In C++, you can declare a structure’s type variables by name without the struct keyword:

USCurrency myMoney; // Declares a variable 'myMoney' of type USCurrency 
time_of_day start_work; // Declares a variable 'start_work' of type time_of_day 

It’s still legal to use the C-style declaration struct USCurrency myMoney; in C++.

Accessing Structure Members

You can use the dot operator (.) to access individual members of a structure.

As an example:

USCurrency myMoney;
myMoney.dollars = 10;
myMoney.cents = 50; // Accessing 'dollars' and 'cents' members of 'myMoney' 

It is necessary to utilise the arrow operator (->) when working with a pointer to a structure. As an example:

struct Books *book_pointer; // Declares a pointer to a Books structure 
book_pointer = &Book1;     // Assigns the address of Book1 to book_pointer 
book_pointer->title;       // Accesses the 'title' member using the arrow operator 

Initializing Structure Members

Several methods exist for initializing structure members:

  • Direct Assignment: By assigning a value and using the dot operator to access each member, as demonstrated above.
  • Initializer List (Braced List {}): An instance of a struct can be initialized with curly braces {}. In their declared sequence, the values in the braces should correspond to the struct’s members.
    • The values that you supply are initialised to zero if you supply fewer values than members.
    • All members have their values set to zero if you don’t supply any.
    • An error occurs when there are more initialisers than members.
  • Additionally, instances of nested record types are initialised using this curly brace syntax:

Example: A Simple Structure

#include <iostream> // For std::cout and std::endl
#include <string>   // For std::string (though not used in Point, good practice for structs)
// Define a structure named Point
struct Point {
    int x;
    int y;
};
int main() {
    std::cout << "--- Demonstrating a simple Point struct ---" << std::endl;
    // Declare a Point variable and initialize using direct assignment
    Point p1; // Declares a variable 'p1' of type Point
    p1.x = 10; // Accessing 'x' member of 'p1' using dot operator
    p1.y = 20; // Accessing 'y' member of 'p1' using dot operator
    std::cout << "Point p1: x = " << p1.x << ", y = " << p1.y << std::endl;
    // Declare another Point variable and initialize using an initializer list
    Point p2 = {30, 40}; // Initializes x=30, y=40 [conversation history]
    std::cout << "Point p2: x = " << p2.x << ", y = " << p2.y << std::endl;
    // Demonstrating zero-initialization with an empty initializer list
    Point p3 = {}; // Initializes all members to zero (0, 0) [conversation history]
    std::cout << "Point p3 (zero-initialized): x = " << p3.x << ", y = " << p3.y << std::endl;
    std::cout << std::endl;
    return 0;
}

Output

--- Demonstrating a simple Point struct ---
Point p1: x = 10, y = 20
Point p2: x = 30, y = 40
Point p3 (zero-initialized): x = 0, y = 0

Structures vs. Classes

Structures are essentially a class type in C++. Classes and structs are identical technically except for the default member access level:

  • A struct’s members are by default public.
  • A class’s members are automatically private.

Although structures can hold member functions as well as data, it is standard programming practice to use struct for Plain Old Data (POD) types. These are classes that usually have no user-defined constructors or in-class initializers, just public data members. Class is often preferred for private members due to style.

C++ structs offer a strong and versatile approach to join multiple data types, improving code readability and structure.

You can also read What Is The Relationship Between Pointers And Arrays In C++

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index