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.
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:
class keyword is also accepted in template parameter lists, as in template .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:
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.
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:
sizeof, alignment, and padding follow the same rules for both keywords. The keyword alone never changes memory layout.| Feature | struct | class |
|---|---|---|
| Default member access | public | private |
| Default inheritance | public | private |
| Constructors and destructors | Yes | Yes |
| Member functions and operator overloading | Yes | Yes |
| Inheritance and virtual functions | Yes | Yes |
Allowed in a template parameter such as template | No (use class or typename) | Yes |
Memory layout and sizeof rules | Same | Same |
| Speed | Identical | Identical |
| Typical convention | Passive data, aggregates, C-compatible layouts | Behaviour, invariants, encapsulation |
What these differences mean in day-to-day code:
public: label in a class and your members stay hidden.struct D : Base {} inherits publicly, while class D : Base {} inherits privately, even when Base is declared with the other keyword.class or typename, and the two mean the same thing. The struct keyword is not allowed there.Beginners often assume a struct works the same in both languages. It does not.
| Feature | struct in C | struct in C++ | class in C++ |
|---|---|---|---|
| Member functions | No | Yes | Yes |
| Access specifiers | No | Yes | Yes |
| Default access | Everything accessible | public | private |
| Constructors and destructors | No | Yes | Yes |
| Inheritance | No | Yes | Yes |
Declare a variable without repeating struct | No (needs the keyword or a typedef) | Yes | Yes |
| Typical use | Plain data, register maps | Plain data and light helpers | Encapsulated 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
Limitations
Advantages
Limitations
public: before a base class creates private inheritance, which surprises beginners.Engineers pair the two keywords constantly. A struct carries the data, and a class guards the behaviour around it.
Work through these questions in order. The first clear ‘yes’ usually settles it.
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 modelling | Better choice | Why |
|---|---|---|
| GPIO or UART register block | struct | Mirrors the hardware layout exactly |
| CAN frame (ID, length, 8 data bytes) | struct | Plain data passed between layers |
| Calibration constants stored in flash | struct | Passive values that work well with constexpr |
| UART receive ring buffer | class | Index rules must always stay true |
| LED or motor driver | class | Hides pins and configuration |
| PID controller | class | Holds state and limits its own output |
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.
#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;
}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;
}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;
}#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
}
}#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
}
}PointS lets you read a.x directly, while PointC rejects b.x because its members are private by default.struct or class.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.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.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.
union also defaults to public access. In a template parameter list you must write class or typename, never struct.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.class entirely and write struct with an explicit private: label. That is legal. A consistent team convention matters more than the choice itself.SensorReading as a struct and SensorDriver as a class.constexpr utilities.std::uint32_t for hardware and protocol structs, so the layout does not depend on the platform.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.volatile to hardware register members, not to whole structs of ordinary data.explicit to block surprising implicit conversions.public every time you inherit with a class, so the intent is visible.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.
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.
Indian Institute of Embedded Systems – IIES