C++ - Structures
Overview
Estimated time: 35–50 minutes
Use structs to group related data. Learn aggregate initialization, member functions, and how struct differs from class (only default access).
Learning Objectives
- Define and initialize structs using aggregate and member-init-list approaches.
- Add member functions to structs.
- Understand access defaults and how struct vs class differ.
Prerequisites
Aggregate initialization
#include <iostream>
struct Point { int x; int y; };
int main(){
Point p{3,4};
std::cout << p.x + p.y << "\n";
}
Expected Output: 7
Struct with member functions
#include <iostream>
#include <cmath>
struct Point {
int x{0}; int y{0};
double length() const { return std::hypot(x, y); }
void translate(int dx, int dy){ x += dx; y += dy; }
};
int main(){
Point p{3,4};
std::cout << p.length() << "\n";
p.translate(1,-1);
std::cout << p.x << "," << p.y << "\n";
}
Expected Output:
5
4,3
Defaulted comparisons (C++20)
#include <compare>
struct Point2 { int x{0}, y{0};
bool operator==(const Point2&) const = default;
std::strong_ordering operator<=>(const Point2&) const = default;
};
Access control in struct
struct PublicByDefault { int x{0}; }; // public members by default
struct WithPrivate {
private:
int x{0};
public:
int get() const { return x; }
};
Common Pitfalls
- Forgetting const on member functions that don’t modify state (prevents calling on const objects).
- Assuming struct and class are different types—only default access differs: struct members are public by default; class members are private by default.
Checks for Understanding
- How do struct and class differ in C++?
- When does aggregate initialization apply?
Show answers
- Only default access specifier: struct is public by default, class is private by default.
- When the type is an aggregate (no user-declared constructors, no private/protected non-static data, etc.).
Exercises
- Create a struct Rectangle with width/height and an area() const method; print its area.
- Add a translate(dx, dy) method to Rectangle to move an origin-based rectangle; print new coordinates.