Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

struct — defining a class type

The struct keyword declares a class type that can combine data and member functions. Unlike class, its default member access and default inheritance are public. Using struct alone does not guarantee that the type is an aggregate.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

struct Name { /* members */ };
struct Name;
struct Derived : Base { /* members */ };

struct declares a class type, not merely a container for data. The definition struct Name { /* members */ }; can contain data members, member functions, and constructors. The semicolon ends the declaration shown. Writing struct Name; is a forward declaration: it introduces the type name without defining its members.

The key differences from class are the default access rules. Members of a struct are public by default, whereas members of a class are private by default. Likewise, inheritance in struct Derived : Base { }; defaults to public; with class, it would default to private. The labels public:, protected:, and private: explicitly control access to subsequent members.

In the example, Rectangle is an aggregate: Rectangle rectangle{3, 4}; initializes width and height in declaration order. An ordinary member function such as area() does not prevent aggregate status. Not every struct is an aggregate, however: a user-declared constructor, a private or protected direct non-static data member, or a virtual function, among other features, rules it out. A derived struct can still be an aggregate if its public, non-virtual base has a private non-static data member, provided the derived type meets the other aggregate requirements. The public member can be changed through rectangle.width; after assigning 5, area() returns 20.

This entry targets C++23. The supplied sources present an evolving working draft, not a frozen C++23 edition. The example is intended for local compilation with -std=c++23. The displayed source was run unchanged in an isolated environment, and its standard output matched the stated output exactly. No production runtime has been attested.

Examples

#include <iostream>

struct Rectangle {
    int width;
    int height;

    int area() const {
        return width * height;
    }
};

int main() {
    Rectangle rectangle{3, 4};
    rectangle.width = 5;
    std::cout << rectangle.area() << '\n';
}

Result

20

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources