/////////////////////////////////////////////////////////////////// // MT3Q3.cpp - Copy constructor for class with reference member // // // // Jim Fawcett, CSE687 - OOD Midterm, Spring 2013 // /////////////////////////////////////////////////////////////////// #include #include #include #include #include "../MTutility/MTutility.h" typedef std::vector Characters; class Y { public: Y(Characters chars) : baseChars(chars) {} Characters& characters() { return baseChars; } private: Characters baseChars; }; class X : public Y { public: X(const Characters& chrs, const Characters& baseChrs, std::ostream& out=std::cout) : Y(baseChrs), stuff(chrs), out_(out) {} X(const X& x) : Y(x), stuff(x.stuff), out_(x.out_) {} // this is what compiler generated cctor does X& operator=(const X& x) // compiler can't generate assignment due to reference member { if(this == &x) return *this; static_cast(*this) = x; // can't assign reference member out_ stuff = x.stuff; return *this; } void write() { out_ << "\n "; for(auto character : stuff) { out_ << " " << character; } out_ << "\n "; for(auto character : characters()) { out_ << " " << character; } } private: std::ostream& out_; std::vector stuff; }; int main() { Title("MT3Q3 - Copy Ctor for class with Reference member"); Characters threeStooges; threeStooges.push_back("Larry"); threeStooges.push_back("Moe"); threeStooges.push_back("Curly"); Characters MarxBrothers; MarxBrothers.push_back("Groucho"); MarxBrothers.push_back("Harpo"); MarxBrothers.push_back("Chico"); MarxBrothers.push_back("Gummo"); MarxBrothers.push_back("Zeppo"); X x(threeStooges, MarxBrothers); x.write(); std::cout << "\n copying"; X xcopy(x); xcopy.write(); Characters threeMuskateers; threeMuskateers.push_back("Athos"); threeMuskateers.push_back("Porthos"); threeMuskateers.push_back("Aramis"); std::ofstream fout("test.dat"); if(fout.good()) { X fx(threeMuskateers, MarxBrothers ,fout); std::cout << "\n writing to file"; fx.write(); std::cout << "\n copying"; X fxcopy(fx); fxcopy.write(); fout.close(); std::ifstream fin("test.dat"); if(fin.good()) { std::cout << "\n reading from file"; std::cout << fin.rdbuf(); } std::cout << "\n assigning"; x = fx; // will use x's original ostream, e.g., cout x.write(); } std::cout << "\n\n"; return 0; }