#include using namespace std; class A { public: A(int aa) : a(aa) { cout << "A constr: " << a << " -- " << this << endl; } ~A() { cout << "A destr: " << a << " -- " << this << endl; } int val() const { return a; } private: int a; }; const A &makeA1() { A a(1); return a; } const A &makeA2() { return A(2); } A &makeA3() { A a(3); return a; } /* A &makeA4() { return A(4); } */ A &&makeA5() { return A(5); } A makeA6() { return A(6); } void useA(const A &a) { cout << "using A = " << a.val() << endl; } class B { public: B(int bb) : a(bb) { cout << "B constr: " << bb << " -- " << this << endl; } ~B() { cout << "B destr: " << a.val() << " -- " << this << endl; } const A &getA() const { return a; } A getA2() const { return a; } private: A a; }; B makeB() { B ret(10); return ret; } class C : public A { public: C(int bb) : A(bb) { cout << "C constr: " << bb << " -- " << this << endl; } ~C() { cout << "C destr: " << A::val() << " -- " << this << endl; } }; C makeC() { C ret(100); return ret; } // inspired by GotW #88 by Herb Sutter -- google it int main(int argc, char **argv) { cout << "l1" << endl; useA(makeA1()); useA(makeA2()); useA(makeA3()); //useA(makeA4()); useA(makeA5()); useA(makeA6()); cout << "------" << endl; useA(makeB().getA()); useA(makeB().getA2()); cout << "------" << endl; const A &a1 = makeA6(); cout << "line 1" << endl; useA(a1); cout << "line 2" << endl; // the following code (note the lacking "const") does not compile: /* cout << "-----" << endl; A &a2 = makeA6(); cout << "line 3" << endl; useA(a2); cout << "line 4" << endl; */ cout << "-----" << endl; const A &a3 = makeC(); cout << "line 5" << endl; useA(a3); cout << "line 6" << endl; }