`struct` — C++ Keyword

`struct` — C++ Keyword

The struct keyword in C++: defines a class type with default public member access.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

struct

Defines a class type where members and base classes are public by default. Otherwise identical to class.

Syntax

struct Name { member-declarations };
struct Name : Base { ... };

Example

#include <print>

struct Point {
    double x;
    double y;

    double length() const {
        return x * x + y * y;  // squared for brevity
    }
};

struct ColorPoint : Point {
    int color = 0;
};

int main() {
    Point p{3.0, 4.0};
    std::println("length²: {}", p.length());   // 25

    ColorPoint cp{{1.0, 2.0}, 0xFF0000};
    std::println("x={} color={}", cp.x, cp.color);
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}