Class vs Struct in C++: Key Differences and Which to Use

Class vs Struct in C++: Key Differences and Which to Use
In C++, the only language-level difference between a class and a struct is the default access level. Members and base classes of a class are private by default, while members and base classes of a struct are public by default. Both can have constructors, member functions, inheritance, and virtual functions. By convention, use a struct for simple passive data and a class for types that protect rules (invariants) and hide their internals.

Almost every C++ beginner asks the same question: if a struct can hold functions and a class can hold plain data, why does the language keep both keywords?

The class vs struct in C++ debate confuses people because the technical answer is short, while the practical answer needs a little more thought. The language treats the two almost identically. The keyword you pick mainly tells the next engineer what kind of type they are about to read.

In this guide you will learn what a class and a struct are, every real difference between them, and a simple rule for choosing one. The examples come from embedded work, such as register maps on an STM32 and driver classes on an ESP32. We also bring in the points working C++ developers raise in community discussions and correct a few common myths along the way.

What Is a Class in C++?

A class is a user-defined type that bundles data members and member functions. By default, everything inside it is private, so outside code can use only the parts you mark public.

class Thermostat {
    float target_c;                 // private by default
public:
    explicit Thermostat(float t) : target_c(t) {}
    float target() const { return target_c; }
};

Key points about a class:

  • Members and base classes are private by default.
  • It supports constructors, destructors, inheritance, virtual functions, templates, and operator overloading.
  • It is built for encapsulation: the constructor establishes the rules and the public functions keep them true.
  • The class keyword is also accepted in template parameter lists, as in template .

registor_now_P

What Is a Struct in C++?

A struct is also a user-defined type that bundles data and functions. By default, everything inside it is public, which makes it a natural fit for simple records.

#include 

struct SensorReading {
    std::uint32_t timestamp_ms;
    std::int16_t  temperature_x100;   // 25.37 C stored as 2537
    std::uint16_t humidity_x100;
};

Key points about a struct:

  • Members and base classes are public by default.
  • It has every feature a class has: constructors, member functions, inheritance, virtual functions, and templates.
  • It comes from C, which is why it remains the usual choice for C-compatible data and hardware layouts.
  • It is commonly used for aggregates and simple value types.

A quick myth check. Some beginners read that a struct is just a collection while a class is the real data structure. That is not accurate. You can build a linked list, a binary tree, or a stack with either keyword, and the C++ standard calls both of them class types.

How the Compiler Sees Them

The C++ standard defines a class-key, which is one of class, struct, or union. All three declare a class type. In practice this means:

  • Same layout rules: sizeof, alignment, and padding follow the same rules for both keywords. The keyword alone never changes memory layout.
  • Same code generation: A function inside a struct compiles the same way as one inside a class.
  • Only defaults differ: The class-key sets the default member access and the default inheritance access, nothing more.
  • Unions also default to public, but a union cannot be a base class and cannot have one.

Key Differences Between Structure and Class

Featurestructclass
Default member accesspublicprivate
Default inheritancepublicprivate
Constructors and destructorsYesYes
Member functions and operator overloadingYesYes
Inheritance and virtual functionsYesYes
Allowed in a template parameter such as template No (use class or typename)Yes
Memory layout and sizeof rulesSameSame
SpeedIdenticalIdentical
Typical conventionPassive data, aggregates, C-compatible layoutsBehaviour, invariants, encapsulation

What these differences mean in day-to-day code:

  • Default access is the one difference you will actually see. Forget a public: label in a class and your members stay hidden.
  • Default inheritance depends on the derived type’s keyword. struct D : Base {} inherits publicly, while class D : Base {} inherits privately, even when Base is declared with the other keyword.
  • Template parameters accept class or typename, and the two mean the same thing. The struct keyword is not allowed there.
  • Convention carries the rest of the weight. Even the standard’s older vocabulary, such as POD struct and standard-layout type, reflects the link between struct and C-style data.

Struct in C vs Struct in C++ vs Class in C++

Beginners often assume a struct works the same in both languages. It does not.

Featurestruct in Cstruct in C++class in C++
Member functionsNoYesYes
Access specifiersNoYesYes
Default accessEverything accessiblepublicprivate
Constructors and destructorsNoYesYes
InheritanceNoYesYes
Declare a variable without repeating structNo (needs the keyword or a typedef)YesYes
Typical usePlain data, register mapsPlain data and light helpersEncapsulated types and drivers

A C++ struct is not automatically incompatible with C. If it stays standard-layout (no virtual functions, the same access level for all data members, and a simple inheritance chain), you can still share it with C code through headers wrapped in extern "C".

Advantages and Limitations

Struct

Advantages

  • Less typing for plain data, since members are public by default.
  • Easy brace initialization when the type is an aggregate.
  • Tells every reader ‘passive data’, which speeds up code reviews.
  • Natural fit for register maps, packets, and C-compatible headers.
  • Often trivially copyable, so it is cheap to copy and easy to place in flash as constant data.

Limitations

  • Nothing stops outside code from putting the object into an invalid state.
  • Adding lots of logic to a struct breaks the convention and confuses readers.
  • Public data makes refactoring harder, because every caller may depend on the field names.

Class

Advantages

  • Private data lets you enforce invariants, such as an index that must stay inside a buffer.
  • A small public interface lets you change the internals without touching callers.
  • Constructors can guarantee a safe starting state, for example configuring a peripheral before use.
  • Tells readers the type has behaviour and rules.

Limitations

  • Simple data holders become verbose when wrapped in getters and setters.
  • Forgetting public: before a base class creates private inheritance, which surprises beginners.
  • Hidden state can make hardware drivers harder to inspect unless you add debug accessors.

Real-World Applications

Engineers pair the two keywords constantly. A struct carries the data, and a class guards the behaviour around it.

  • Automotive: A CAN frame (identifier, length, data bytes) is a struct passed between layers. A diagnostics session manager or a cruise-control state machine is a class.
  • Medical: A patient vitals sample is a struct. An infusion pump controller is a class that never allows a dose rate outside safe limits.
  • Consumer electronics: Button events and display coordinates are structs. A display driver that owns the SPI bus is a class.
  • Industrial automation: A PLC tag description is a struct. A PID controller with gain limits and output saturation is a class.
  • Aerospace: A telemetry packet is a struct. An attitude estimator that holds filter state is a class.
  • Robotics: A pose (x, y, heading) is a struct. A motor controller that enforces current limits is a class.
  • IoT and smart home: A sensor message is a struct. A Wi-Fi or MQTT connection manager is a class.
  • Wearables: An accelerometer sample is a struct. A BLE service that tracks connection state is a class.

Explore Courses - Learn More

Which One Should You Use?

Work through these questions in order. The first clear ‘yes’ usually settles it.

  1. Does the type have an invariant? An invariant is a rule that must always hold, such as a head index staying below the buffer size. If yes, use a class.
  2. Does it hide hardware state, own a resource, or need a controlled interface? If yes, use a class.
  3. Can every member change independently without breaking anything? If yes, use a struct.
  4. Must it match a fixed memory layout, such as a register block, a packet, or a C header? If yes, use a struct and keep it standard-layout.
  5. Does it carry a lot of behaviour, like a driver, a state machine, or a manager? If yes, use a class.
  6. Does your project have a coding standard? Follow it, even if it differs from this list.

The C++ Core Guidelines express the same idea. Use a class when there is an invariant and a struct when the data members can vary independently (rule C.2), and use a class if any member is non-public (rule C.8). Some standards are stricter. The AUTOSAR C++14 guidelines restrict struct to passive types with only public data, so check rule A11-0-2 in the version your project follows.

Simple rule to remember: a struct is data. A class is data plus rules.

Here is how that rule looks on a typical embedded project:

What you are modellingBetter choiceWhy
GPIO or UART register blockstructMirrors the hardware layout exactly
CAN frame (ID, length, 8 data bytes)structPlain data passed between layers
Calibration constants stored in flashstructPassive values that work well with constexpr
UART receive ring bufferclassIndex rules must always stay true
LED or motor driverclassHides pins and configuration
PID controllerclassHolds state and limits its own output

Code Examples

These five examples build from the basic rules to a realistic embedded pattern. Each one compiles with a standard C++ compiler, apart from the hardware addresses in Example 4, which are specific to STM32F4 devices.

Example 1: Default access

#include 

struct PointS {
    int x;                  // public by default
    int y;
};

class PointC {
    int x;                  // private by default
    int y;
};

int main() {
    PointS a{10, 20};       // OK: public members, aggregate initialization
    std::cout << a.x << ' ' << a.y;

    PointC b;
    // b.x = 5;             // error: 'PointC::x' is private within this context
    (void)b;
    return 0;
}

Example 2: Default inheritance

struct Base {
    void hello() {}
};

struct D1 : Base {};        // public inheritance by default
class  D2 : Base {};        // private inheritance by default

int main() {
    D1 d1;
    d1.hello();             // OK

    D2 d2;
    // d2.hello();          // error: Base is an inaccessible base of D2
    (void)d2;
    return 0;
}

Example 3: A class can be an aggregate, and a struct may not be

class Config {              // class keyword, but all members are public
public:                     // and there is no constructor
    int baud;
    int parity;
};

struct Locked {             // struct keyword, but one member is private
private:
    int secret;
public:
    int open;
};

int main() {
    Config c{115200, 0};                  // OK: Config is still an aggregate
    Config c2{.baud = 9600, .parity = 0}; // OK in C++20: designated initializers
    // Locked l{1, 2};                    // error: Locked is not an aggregate
    (void)c;
    (void)c2;
    return 0;
}

Example 4: Register map as a struct, driver as a class (STM32F4 style)

#include 

// struct: mirrors the hardware register block, no rules, no hidden state
struct GpioRegs {
    volatile std::uint32_t MODER;     // 0x00
    volatile std::uint32_t OTYPER;    // 0x04
    volatile std::uint32_t OSPEEDR;   // 0x08
    volatile std::uint32_t PUPDR;     // 0x0C
    volatile std::uint32_t IDR;       // 0x10
    volatile std::uint32_t ODR;       // 0x14
    volatile std::uint32_t BSRR;      // 0x18
};

constexpr std::uintptr_t kGpioaBase      = 0x40020000UL;  // STM32F4 series
constexpr std::uintptr_t kRccAhb1enrAddr = 0x40023830UL;

// class: owns the configuration of one pin and keeps it valid
class Led {
public:
    Led(GpioRegs* port, std::uint8_t pin)
        : port_(port), pin_(static_cast(pin & 0x0FU)) {  // invariant: pin 0..15
        port_->MODER &= ~(0x3U << (pin_ * 2U)); port_->MODER |=  (0x1U << (pin_ * 2U)); // output mode } void on() { port_->BSRR = (1U << pin_); } void off() { port_->BSRR = (1U << (pin_ + 16U)); } void toggle() { port_->ODR ^= (1U << pin_); }

private:
    GpioRegs*    port_;
    std::uint8_t pin_;
};

int main() {
    // Enable the GPIOA clock before touching its registers
    *reinterpret_cast(kRccAhb1enrAddr) |= 1U;

    auto* gpioa = reinterpret_cast<GpioRegs*>(kGpioaBase);
    Led led(gpioa, 5);        // PA5 drives the user LED on many Nucleo boards
    led.on();

    for (;;) {
        // application loop
    }
}

Example 5: Plain data in a struct, rules in a class

#include 
#include 

struct SensorReading {                 // passive data: any field can change freely
    std::uint32_t timestamp_ms;
    std::int16_t  temperature_x100;
    std::uint16_t humidity_x100;
};

template 
class RingBuffer {                     // invariant: count_ <= N and indexes < N static_assert(N > 0U, "N must be positive");
public:
    bool push(const T& item) {
        if (count_ == N) { return false; }   // full: reject, never overwrite silently
        data_[head_] = item;
        head_ = (head_ + 1U) % N;
        ++count_;
        return true;
    }

    bool pop(T& out) {
        if (count_ == 0U) { return false; }
        out = data_[tail_];
        tail_ = (tail_ + 1U) % N;
        --count_;
        return true;
    }

    std::size_t size() const { return count_; }

private:
    T           data_[N]{};
    std::size_t head_  = 0U;
    std::size_t tail_  = 0U;
    std::size_t count_ = 0U;
};

RingBuffer<SensorReading, 8> g_samples;     // statically allocated, no heap

void on_sample_ready(std::uint32_t t, std::int16_t temp, std::uint16_t hum) {
    if (!g_samples.push({t, temp, hum})) {
        // buffer full: count the drop instead of corrupting older data
    }
}

Code Explanation

  • Example 1 shows the single most important difference. PointS lets you read a.x directly, while PointC rejects b.x because its members are private by default.
  • Example 2 shows default inheritance. The same base class behaves differently depending on whether the derived type uses struct or class.
  • Example 3 shows that the keyword does not decide aggregate initialization. The rules do: no private or protected data members, no virtual functions, and no user-declared constructors in C++20. A public-only class passes. A struct with one private member fails.
  • Example 4 uses a struct because the register block has no rules to enforce, only offsets that must match the reference manual (RM0090 for STM32F405/407/415/417/427/429 devices). Every member is volatile, so the compiler performs each read and write. The Led class masks the pin number so it can never exceed 15, and it writes BSRR so setting or clearing a pin is a single write instead of a read-modify-write. The reinterpret_cast from an integer address is the standard practice for memory-mapped registers, though its exact result is implementation-defined.
  • Example 5 keeps SensorReading as passive data and puts head_, tail_, and count_ behind a class boundary. If those indexes were public, any function could corrupt the buffer. The class also refuses to overwrite data when full.
  • Interrupt safety: The ring buffer above is not safe for an ISR producer and a main-loop consumer as written. For that pattern, use a single-producer, single-consumer design with atomic indexes, or protect the critical sections.

What Experienced C++ Developers Say

Developer discussions on forums such as Reddit are full of useful points on this exact question. These are the ones that hold up in real projects.

  • There is a clear consensus: Nearly everyone agrees the only language-level difference is default access, for members and for inheritance.
  • Convention carries meaning: Most developers read a struct as ‘mostly data’ and a class as ‘behaviour and rules’. A struct packed with logic confuses readers, even though the compiler accepts it.
  • The C-compatibility argument is history, not the whole story: Structs do exist partly for C compatibility. Modern C++ still uses them for aggregates, return values, and simple value types.
  • Aggregate initialization needs care: One often-repeated claim says structs get a brace-initializer constructor and classes do not. The accurate rule is about aggregates: no private or protected data members, no virtual functions, and no virtual, private, or protected base classes, plus a constructor rule that tightened between C++11 and C++20. A class that is fully public qualifies, and a struct with a private member does not. Check cppreference for the exact wording in your standard.
  • Two edge cases catch people: A union also defaults to public access. In a template parameter list you must write class or typename, never struct.
  • Forward declarations should match definitions: Declaring struct Sensor; and later defining class Sensor { ... }; is legal, but MSVC and Clang can warn about the mismatch. On MSVC the keyword can also appear in decorated names, so mismatches occasionally surface as linker surprises.
  • Opinions differ on style: A few developers avoid class entirely and write struct with an explicit private: label. That is legal. A consistent team convention matters more than the choice itself.
  • A good practical split: One developer’s example uses a struct for a small player record in a board game and a class for the board, because the board has operations that work across the whole thing. In embedded terms, that is SensorReading as a struct and SensorDriver as a class.
  • Terminology is part of the confusion: A data structure is a way of organizing data, such as a linked list or a tree. Both keywords can build one, so the question is never ‘which keyword makes a data structure’.

Best Practices

  • Write the rule down. Add one sentence to your coding standard, such as ‘struct for passive data, class for anything with invariants’, and apply it everywhere.
  • Keep structs passive. All public data, no invariants, and at most small helpers such as comparison operators or constexpr utilities.
  • Give classes a real interface. Private data, a constructor that creates a valid object, and public functions that keep it valid. Avoid a getter and setter for every field, because that is a struct in disguise.
  • Use fixed-width types such as std::uint32_t for hardware and protocol structs, so the layout does not depend on the platform.
  • Check layouts at compile time. Use static_assert(sizeof(GpioRegs) == 28) or offsetof checks against the reference manual, and std::is_standard_layout_v plus std::is_trivially_copyable_v for C-shared types.
  • Apply volatile to hardware register members, not to whole structs of ordinary data.
  • Mark single-argument constructors explicit to block surprising implicit conversions.
  • Write public every time you inherit with a class, so the intent is visible.
  • Match forward declarations to the real definition keyword.
  • Prefer vendor headers such as CMSIS device files for register maps instead of rewriting them by hand.
  •  

Talk to Academic Advisor

Conclusion

Class vs struct in C++ comes down to one technical fact and one human decision. The fact: only the default access changes, from private in a class to public in a struct. The decision: choose the keyword that tells your reader the truth about the type.

Use a struct for passive data such as register blocks, packets, and sensor readings. Use a class when the type has rules to protect, hardware to hide, or behaviour to offer. Whatever your team picks, apply it consistently and write it into the coding standard.

To keep building these skills on real hardware, explore the embedded systems training at the Indian Institute of Embedded Systems (IIES), Bangalore.

FAQs

The only language-level difference is default access. Class members and base classes are private by default, while struct members and base classes are public by default. Both support constructors, member functions, inheritance, and virtual functions. Developers usually choose a struct for simple data and a class for types that enforce rules and hide internal state.

Yes. A C++ struct can have constructors, destructors, member functions, operator overloads, inheritance, virtual functions, and templates, exactly like a class. This is different from C, where a struct can only hold data members. By convention, keep structs simple so readers know at a glance that the type is mostly plain data.

Use a class when the type has an invariant, hides data, or owns a resource or hardware peripheral. Use a struct for passive data whose members can change independently, such as sensor readings, packets, and register maps. The C++ Core Guidelines follow the same rule, and your team’s coding standard has the final say.

No. The compiler generates the same code for both because they are the same kind of type, and size, alignment, and memory layout rules are identical. Performance depends on what you put inside, such as virtual functions, padding, and copying cost, and not on the keyword you choose.

Not entirely. C++ structs gain member functions, access specifiers, constructors, inheritance, and templates, and you can declare variables without repeating the struct keyword. A C++ struct stays C-compatible only if it remains standard-layout, so avoid virtual functions and mixed access levels in types you share with C code.

Author

Embedded Systems and IOT Trainer– IIES

Updated On: 28-11-26


10+ years of hands-on experience delivering practical training in Embedded Systems and it's design