C++ composition and RAII
Let owned members manage their resources automatically.
On this page
Classes, constructors, and vector.
- Let owned members manage their resources automatically.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
RAII ties resource lifetime to object lifetime. A vector member manages its own allocation and releases it when its containing object is destroyed.
GradeBook has a collection of scores. This composition avoids exposing raw allocation or requiring a manual cleanup method.
Code example
#include <iostream>
#include <vector>
class GradeBook {
std::vector<int> scores_;
public:
void add(int score) { scores_.push_back(score); }
int total() const {
int sum = 0;
for (int score : scores_) sum += score;
return sum;
}
};
int main() {
GradeBook book;
book.add(80);
book.add(90);
std::cout << book.total() << '\n';
}170
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
#include <iostream>#include <vector>class GradeBook { std::vector<int> scores_;public: void add(int score) { scores_.push_back(score); } int total() const { int sum = 0; for (int score : scores_) sum += score; return sum; }};int main() { GradeBook book; book.add(80); book.add(90); std::cout << book.total() << '\n';}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Construct an empty vector member. | scores_ = [] | — | |
| Append the first value. | scores_ = [80] | — | |
| Append the second. | scores_ = [80, 90] | — | |
| Accumulate 80 then 90. | sum: 0 -> 80 -> 170 | — | |
| Print the total. When main ends, the vector cleans up its storage. | sum: 0 -> 80 -> 170 | 170 |
Behind the scenes
How C++ processes this code
The C++ compiler produces a native executable. Execution enters main, where objects and function calls perform the work.
Cost and common mistakes
Amortized O(1) append, O(n) total calculation, O(n) storage.
- Do not manually delete storage managed by vector.
- Scores and totals need validation and wider types for large production datasets.
Try it yourself
Create an empty GradeBook and call total.
Reveal answer and reasoning
It returns 0 because the loop has no iterations.