Chatty Containers

When an object is constructed, any objects it contains must also be constructed. When it is destroyed, any objects it contains must be destroyed.

/* * When an object is destroyed, the objects it contains are destroyed also */ #include <iostream> #include <list> using namespace std; #include "chatty.h" // This class just holds three chatty objects. class ChatHolder { public: ChatHolder(int a, int b, int c) { cout << "Creating ChatHolder(" << a << "," << b << "," << c << ")" << endl; m_a.set(a); m_b.set(b); m_c.set(c); } ~ChatHolder() { cout << "Destroying ChatHolder" << endl; } private: Chatty m_a, m_b, m_c; }; // Exercise the holder a bit. void f() { cout << "Enter f()" << endl; ChatHolder ch1(3, 17, 33); ChatHolder ch2(17, -4, 22); cout << "Leave f()" << endl; } // Put some in a standard container and see what happens. void g(int nchat) { cout << "Enter g()" << endl; list<Chatty> cl; for(int i = 1; i <= nchat; ++i) cl.push_back(Chatty(i)); for(Chatty &i: cl) cout << i.val() << " "; cout << endl; cout << "Leave g()" << endl; } main() { cout << "Enter main" << endl; ChatHolder ch(3, 19, 4); f(); g(2); g(5); cout << "Leave main" << endl; }