Classes, structs and enums in C++: protecting your data
When to use a struct and when a class, constructors that validate, const member functions, enum class, and splitting code into headers and source files.
Most beginner projects come down to the same question: which data belongs together, and who is allowed to change it? C++ gives you structs, classes and enums to answer it.
Structs for plain data
When a value is just a bundle of fields and any combination is fine, use a struct with public
members:
struct Reading {
std::string sensor;
std::string timestamp;
double celsius = 0.0;
};
Reading r{"freezer-2", "2026-11-03T08:00", -18.5};A parser returns a Reading; the code that summarises readings reads its fields. No getters, no
setters, no ceremony. That's the shape in
sensor readings for Frostline.
Classes that protect an invariant
An invariant is a rule that must always hold, like "stock is never negative". If the fields are public, any line of code can break it. Make them private and offer operations that keep the rule:
class Inventory {
public:
void receive(const std::string& sku, int quantity);
bool ship(const std::string& sku, int quantity); // false if not enough stock
int count(const std::string& sku) const;
private:
std::map<std::string, int> stock_;
};Now there is exactly one place to check the rule: inside ship. See
stock counts for Pantry & Co..
Constructors that validate
If an object can't exist in a broken state, nobody has to check for one later. Validate in the constructor, or in a factory function that can say no:
class Score {
public:
explicit Score(int value) : value_(value) {
if (value < 0 || value > 100) throw std::out_of_range("score must be 0-100");
}
int value() const { return value_; }
private:
int value_;
};explicit stops Score s = 250; from compiling as a silent conversion. When failure is
expected (user input), a factory that returns std::optional<Score> is often friendlier than an
exception; see error handling in C++.
const member functions
Mark every member function that doesn't change the object as const:
double average() const; // can be called on a const Gradebook&
void add_score(int score); // changes the object, so not constIt documents intent, lets you pass objects by const&, and the compiler stops you from
modifying state by accident in a "read-only" function.
enum class instead of magic numbers
When a value is one of a fixed set, say so in the type:
enum class Priority { Low, Medium, High };
std::string_view label(Priority p) {
switch (p) {
case Priority::Low: return "low";
case Priority::Medium: return "medium";
case Priority::High: return "high";
}
return "?"; // unreachable, keeps some compilers quiet
}With warnings on (-Wall), the compiler tells you when a switch forgets a value, which is
exactly the bug you want to hear about when someone adds Urgent later.
Headers and source files
The projects split each class in two:
include/<company>/inventory.hpp: the class definition, what other code may call.src/inventory.cpp: the function bodies.
// inventory.cpp
#include "pantry/inventory.hpp"
bool Inventory::ship(const std::string& sku, int quantity) { /* ... */ }Put #pragma once at the top of every header. Keep headers small: only include what the
declarations need, and include the rest in the .cpp.
Questions and answers
- What's the difference between a struct and a class in C++?
- Only the default access: struct members are public by default, class members private. By convention, use struct for plain data with no rules, and class when the members must stay consistent and only the class's own functions may change them.
- Should I use enum or enum class?
- enum class. Its values don't leak into the surrounding scope, don't convert to int by accident, and the compiler can warn when a switch misses a case.
Practise it in a project
These projects put this guide to work, with tickets, tests and code review.
Brightpath Academy
A gradebook for Brightpath Academy
Give Brightpath's teachers letter grades, averages and a class ranking, instead of a spreadsheet full of formulas.
- conditionals
- classes
- std::map
- sorting
Pantry & Co.
Stock counts for Pantry & Co.
Track stock as goods arrive and leave Pantry's warehouse, and tell the buyers what to reorder.
- classes
- invariants
- std::map
- input validation
Tasklane
The task list behind Tasklane
Build the core of Tasklane's to-do list: strict due dates, stable task IDs and an agenda in the right order.
- date validation
- enums
- stable IDs
- multi-key sorting
Frostline Cold Storage
Sensor readings summary for Frostline
Turn the raw export of Frostline's freezer sensors into a summary per freezer, and flag readings outside the safe range.
- parsing text
- structs
- std::map
- floating point
Read next
- Invariants and all-or-nothing updates: keeping data consistent
Name the rules your data must always obey, enforce them in one place, validate everything before changing anything, keep history append-only, and test invariants with random operations.