C++ composition and RAII

RAII ties resource lifetime to object lifetime. A vector member manages its own allocation and releases it when its containing object is destroyed.

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';
}
Read the full lesson