|
| 1 | +# Structs and Classes |
| 2 | + |
| 3 | +This module introduces object modeling with `struct` and `class` in C++. |
| 4 | + |
| 5 | +## Why It Matters |
| 6 | + |
| 7 | +As programs grow, related data and behavior should be grouped together. |
| 8 | +`struct` and `class` help you model real entities clearly. |
| 9 | + |
| 10 | +## Quick Run |
| 11 | + |
| 12 | +```bash |
| 13 | +g++ -std=c++17 -Wall -Wextra -pedantic example/main.cpp -o structs_and_classes_example |
| 14 | +./structs_and_classes_example |
| 15 | +``` |
| 16 | + |
| 17 | +On Windows (MSYS2 shell), run: |
| 18 | + |
| 19 | +```bash |
| 20 | +./structs_and_classes_example.exe |
| 21 | +``` |
| 22 | + |
| 23 | +## Topics Covered |
| 24 | + |
| 25 | +### `struct` vs `class` |
| 26 | + |
| 27 | +- `struct` members are `public` by default. |
| 28 | +- `class` members are `private` by default. |
| 29 | +- Both can have fields, methods, and constructors. |
| 30 | + |
| 31 | +### Constructors |
| 32 | + |
| 33 | +Constructors initialize objects when they are created. |
| 34 | + |
| 35 | +```cpp |
| 36 | +class Account { |
| 37 | +public: |
| 38 | + Account(const std::string& ownerName, double initialBalance); |
| 39 | +}; |
| 40 | +``` |
| 41 | +
|
| 42 | +### Encapsulation |
| 43 | +
|
| 44 | +Keep object state private and expose safe methods (`deposit`, `withdraw`, getters). |
| 45 | +
|
| 46 | +## Common Pitfalls |
| 47 | +
|
| 48 | +- Exposing all fields publicly in classes that should protect state. |
| 49 | +- Forgetting `const` on methods that do not modify object state. |
| 50 | +- Not validating values in constructors or mutating methods. |
| 51 | +
|
| 52 | +## Exercise Focus |
| 53 | +
|
| 54 | +- `exercises/01.cpp`: model a rectangle with a `struct` and member methods. |
| 55 | +- `exercises/02.cpp`: create a small class with private state and controlled updates. |
| 56 | +
|
| 57 | +## Checkpoint |
| 58 | +
|
| 59 | +- [ ] I can explain default access in `struct` and `class`. |
| 60 | +- [ ] I can write and use constructors. |
| 61 | +- [ ] I can protect state with private fields and public methods. |
| 62 | +- [ ] I completed both exercises. |
0 commit comments