Classes
A class is a user-defined type that bundles data together with the functions allowed to operate on that data. Keeping the data private lets the class guarantee facts about itself that no outside code can break.
Detailed Explanation
Think of a class as a type you invent because the language does not ship one that matches your problem. A playlist, a bank transfer, a parsed HTTP request: none of these are int or double, so you describe them yourself.
Before classes, a program kept a bag of fields and a loose set of functions that agreed, informally, to operate on it. Nothing enforced that agreement. Any line anywhere could set a field to a nonsense value, and finding the culprit meant reading the whole program. A class closes that hole by making the data reachable only through functions you wrote.
class and struct are the same construct. The only difference is the default access level: members of a class are private unless you say otherwise, members of a struct are public. (Default inheritance access differs too, for the same reason.) The convention most codebases follow is struct for a passive bundle of fields with no rules, class when the type has to protect something.
A class has three kinds of member. Data members are the per-object state. Member functions operate on that state and receive a hidden pointer named this pointing at the object they were called on. Static members belong to the class rather than to any object: one shared copy, no this, reachable as Playlist::maxTracks.
The usual physical layout splits a class across two files. The class definition goes in a header, because every caller needs to know the member list and the object's size to compile at all. The member function bodies go in a .cpp file, so editing a function body recompiles one translation unit instead of every file that included the header. Functions written inside the class body are implicitly inline and stay in the header.
The real payoff is the invariant: a statement about the object that is true from the end of construction until the start of destruction. Suppose a Playlist stores a vector of tracks and a cached total duration. The invariant is that the cached number equals the sum of the track durations. Make those members public and any code can change one without the other, and the class is now lying. Make them private and every path that modifies state goes through your functions, so there is exactly one place to get it right.
Layout is predictable and flat. A class object is a contiguous block holding its non-static data members in declaration order, plus padding inserted for alignment, plus a vtable pointer if the class declares virtual functions. sizeof(Playlist) is a compile-time constant. There is no hidden object header the way a JVM object has one.
Crucially, a class in C++ is a value type. Playlist b = a; copies the entire playlist, tracks and all. In Java the same line gives you two names for one object. That single difference drives most of what follows in C++: copies can be expensive, so the language gives you copy and move operations to control them.
Code Examples
playlist.h — the definition callers need in order to compile
// playlist.h — the definition callers need in order to compile
#include <string>
#include <vector>
class Playlist {
public:
static constexpr int maxTracks = 500; // shared by all playlists, no object needed
explicit Playlist(std::string name);
void add(const std::string& title, int seconds);
int totalSeconds() const { return totalSeconds_; } // implicitly inline
std::size_t size() const { return tracks_.size(); }
private:
struct Track { // a passive bundle, so struct is the honest choice
std::string title;
int seconds;
};
std::string name_;
std::vector<Track> tracks_;
int totalSeconds_ = 0; // invariant: equals the sum of tracks_[i].seconds
};playlist.cpp — bodies live here so edits recompile one file
// playlist.cpp — bodies live here so edits recompile one file
#include "playlist.h"
#include <stdexcept>
Playlist::Playlist(std::string name) : name_(std::move(name)) {}
void Playlist::add(const std::string& title, int seconds) {
if (seconds <= 0) throw std::invalid_argument("track length must be positive");
tracks_.push_back(Track{title, seconds});
totalSeconds_ += seconds; // the only place the cached total changes
}
int main() {
Playlist favourites("Favourites");
favourites.add("Kashmir", 508);
Playlist backup = favourites; // a full copy, not a second name for the same object
favourites.add("Roundabout", 504);
// backup.size() is still 1 — value semantics, unlike Java references
}Common Gotchas
`class` versus `struct` is not a design rule the compiler enforces
the only real difference is default access. Choosing `struct` and then adding private members and invariants compiles fine but misleads every reader who relies on the convention.
Changing a private member still breaks callers at the binary level
the class definition lives in the header, so adding a data member changes `sizeof` and the layout. Anything compiled against the old header and not recompiled has undefined behavior. The Pimpl idiom exists to hide layout behind a stable pointer.
Member declaration order affects size
members are laid out in declaration order with padding for alignment, so `char, int, char` can be larger than `char, char, int`. Group same-sized members when a type is stored in large arrays.
A class is copied by default
unless you say otherwise, the compiler gives your class a copy constructor and copy assignment that copy every member. For a class holding a raw owning pointer, that default is a double free.