C++ composition and RAII

Let owned members manage their resources automatically.

C++
#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';
}
Output
170

Explanation

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.

Explore the dry run
Guided walkthroughReady
1#include <iostream>
2#include <vector>
3class GradeBook {
4 std::vector<int> scores_;
5public:
6 void add(int score) { scores_.push_back(score); }
7 int total() const {
8 int sum = 0;
9 for (int score : scores_) sum += score;
10 return sum;
11 }
12};
13int main() {
14 GradeBook book;
15 book.add(80);
16 book.add(90);
17 std::cout << book.total() << '\n';
18}

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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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

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.

Further reading