cpp-structs

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

  • 5 min

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 mainly used to represent data that should 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.

If you want to learn more, check out the Introduction to Programming Course

Structs Syntax

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

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

    // Method, property definitions, etc.
};
Copied!
  • StructureName: The unique name given to the structure.
  • DataType: Specifies the data type of the fields within the structure.

Basic Example

The following 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;
}
Copied!

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);
Copied!

Accessing Fields

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

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

Initializing Structs

structs can be initialized in several ways, including list initialization and using constructors.

List Initialization

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

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) {}
};
Copied!

Nesting Structs

structs can be nested inside 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;
};
Copied!

In the example,

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

Practical Examples