// B1#6.cpp - What constructors are needed? What operations occur? #include using namespace std; class W { public: // W(const W& w) : value(w.value) // needed only to verify operations int& val() { return value; } // needed for W W::operator-() W operator-() { W temp; temp.val() = -value; return temp; } // needed for X::operator-() private: int value; }; class X { public: // X(const X &x) : w(x.w) { } // needed only to verify operations X() : w() { } // needed for Y() X(const W &otherW) : w(otherW) { } // needed for X::operator-() // and for aFunction(...) int& val() { return w.val(); } // just to check the value operator W () { return w; } // cast supports aFunction X operator-() { X temp(-w); return temp; } private: W w; }; class Y : public X { public: // Y() : X() { }; // compiler generated void constructor // works correctly for this class }; W aFunction(X &x) { return -x; } void main() { /////////////////////////////////////////////////////////////////////////// // The following statement results in the operations: // - calls compiler generated void constructor for the Y class // - that, in turn, immediately calls void constructor for X class // - that, in turn, immediately calls compiler generated void constructor // for W class Y y1; // /////////////////////////////////////////////////////////////////////////// // calls inherited X::val() which calls its data member w's val() function. y1.val() = 7; /////////////////////////////////////////////////////////////////////////// // The numbered operations are a necessary part of a complete answer. // The function below accepts derived object y1 as a base reference. // 1.- It then calls Y's inherited X::operator-() //--------------- start of code specific to my implementation ----------- // - which calls W's W::operator-() // - that calls W's compiler generated void constructor, W::val(), // and compiler generated copy constructor // - now, back in X::operator-(), X::X(const W&) constructor is called // that generates the negated x. //--------------- end of code specific to my implementation ------------- // 2.- now, back inside aFunction(...), calls X::X(const X&) to copy out // returned X object. // 3.- This must be cast to a W using X::operator W (); // 4.- finally, the X::X(const W &w) promotion constructor is called to // create x1. X x1 = aFunction(y1); /////////////////////////////////////////////////////////////////////////// // X::val() calls W::val() cout << "\n value of x1 = " << x1.val(); cout << "\n\n"; }