C++ · Course navigation

C++ composition and RAII

Let owned members manage their resources automatically.

On this page
Before you start

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

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
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

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.

Further reading