Quiz
Warm-up from lesson 6-2: the Probe struct printed a message when main ended, without being called. Which mechanism did that?
Real programs are about domain data: a player, an order, a 2D point. Classes exist to bundle that data with the operations that keep it valid, so the rest of the program cannot corrupt it. Nearly every type you have used so far — std::string, std::vector, even std::cout's stream — is a class somebody wrote exactly this way, and this unit teaches you to write your own.
Bundling data: struct
A struct groups related variables into one new type:
struct Point { double x; double y; }; Point p; // a Point of your own p.x = 3.0; // members accessed with a dot p.y = 4.0;
Like Python's classes, but with every member's type declared. struct and class in C++ are nearly the same keyword. The only built-in difference: struct members are public (accessible from anywhere) by default, class members are private (accessible only from the type's own functions) by default. Convention: struct for simple open data bundles, class when you want to protect invariants — conditions that must stay true for the object's entire lifetime, such as "a bank balance is never negative" or "this vector's size never exceeds its capacity" (the next lesson shows how the protection works).
Constructors
A constructor runs when the object is created, guaranteeing it starts valid. It has the class's name and no return type:
struct Point { double x, y; Point(double px, double py) : x(px), y(py) {} }; Point p(3.0, 4.0); // constructor called here
The : x(px), y(py) part is the member initializer list, the idiomatic place to initialize members (it initializes directly instead of assigning after the fact). Once you define any constructor, creating a Point without arguments stops compiling unless you also provide a no-argument constructor.
Code exercise · cpp
Run this. A struct with a constructor and a method that uses its own members.
Quiz
What is the ONLY built-in difference between struct and class in C++?
Code exercise · cpp
Your turn. Define a struct Rectangle with double members w and h, a constructor taking both, and methods area() and perimeter(). Expected output: `area: 12` then `perimeter: 14`.
Code exercise · cpp
Your turn: give Student a constructor taking (name, score) that uses a member initializer list, then create Ada with 95 and Linus with 88 and print each as shown. Expected: Ada 95 Linus 88