/////////////////////////////////////////////////////////////// // relation.cpp - demonstrate class relationships // /////////////////////////////////////////////////////////////// #include using namespace std; class A { // objects of A will be aggregated by B public: A() { cout << " void constructing A object\n"; } A(const A &a) { cout << " copy constructing A object\n"; } ~A() { cout << " destructing A object\n"; } int& getInt() { cout << " accessing A's private int\n"; return ai; } private: int ai; // B and D have no access to ai accept through getInt() }; class B { // B class is base for inheritance used by D public: B() : bi(0) { cout << " void constructing B object\n"; } B(const B &b) : _a(b._a), bi(b.bi) { cout << " copy constructing B object\n"; } ~B() { cout << " destructing B object\n"; } int& iPart() { cout << " accessing B's protected int\n"; return bi; } protected: A _a; int bi; }; class D : public B { public: D() { cout << " void constructing D object\n"; } D(const D &d) : B(d) { cout << " copy constructing D object\n"; } ~D() { cout << " destructing D object\n"; } int iBPart() const { cout << " reading B's protected int\n"; return bi; } }; void msg(char *s) { cout << s << endl; }; void main() { msg("\n<<<<<<<<---- entering scope #1 ---->>>>>>>>"); { msg("1st statement:"); A a1; msg("2nd statement:"); A a2 = a1; msg("3rd statement:"); a2.getInt(); msg("<<<<<<<<---- leaving scope #1 ---->>>>>>>>"); } msg("\n<<<<<<<<---- entering scope #2 ---->>>>>>>>"); { msg("1st statement:"); B b1; msg("2nd statement:"); B b2 = b1; msg("3rd statement:"); b2.iPart() = 5; msg("<<<<<<<<---- leaving scope #2 ---->>>>>>>>"); } msg("\n<<<<<<<<---- entering scope #3 ---->>>>>>>>"); { msg("1st statement:"); D d1; msg("2nd statement:"); D d2 = d1; msg("3rd statement:"); d2.iPart() = 4; msg("4th statement:"); cout << " D's iPart inherited from B = " << d2.iBPart() << endl; msg("<<<<<<<<---- leaving scope #3 ---->>>>>>>>"); } }