Language: EN

cpp-structs

What are `structs` in C++ and how to use them

In C++, a struct is a data structure that allows grouping several variables under a single name.

structs are particularly useful when working with simple data types that have a predictable size and are primarily used to represent data that needs to be grouped.

In C++, a struct is practically the same as a class
The only difference is the default visibility, which is public in structs and private in classes.

Syntax of structs

The basic syntax for defining a structure in C++ is as follows:

struct StructName {
    // Field definitions
    DataType Field1;
    DataType Field2;

    // Method, property definitions, etc.
};
  • StructName: This is the unique name given to the structure.
  • DataType: Specifies the data type of the fields within the structure.

Basic example

Below is a basic example of how to define and use a structure in C++:

#include <iostream>

struct Point {
    int X;
    int Y;

    Point(int x, int y) : X(x), Y(y) {}

    void PrintCoordinates() const {
        std::cout << "Coordinates: (" << X << ", " << Y << ")" << std::endl;
    }
};

int main() {
    Point point(3, 5);
    point.PrintCoordinates(); // Prints "Coordinates: (3, 5)"
    return 0;
}

Using structs

Declaration and initialization

Structures are declared and initialized similarly to variables of other data types.

Point point;
point.X = 3;
point.Y = 5;

// Initialization using the constructor
Point anotherPoint(7, 8);

Accessing fields

The fields of a structure are accessed using the dot notation (.).

int x = point.X;
int y = point.Y;

Initialization of structs

structs can be initialized in various ways, including list initialization and the use of constructors.

List initialization

Person p = {"Luis", 30, 1.75};

Constructors in structs

Although more common in classes, structs can also have constructors.

struct Person {
    std::string name;
    int age;
    float height;

    // Constructor
    Person(std::string n, int e, float a) : name(n), age(e), height(a) {}
};

Nesting structs

structs can be nested within other structs, allowing the creation of more complex data structures.

struct Date {
    int day;
    int month;
    int year;
};

struct Person {
    std::string name;
    Date birthDate;
};

In the example,

  • We define the Date struct
  • We define the Person struct, which uses Date

Practical examples