/////////////////////////////////////////////////////////////// // MT1Q3.cpp - copy constructor with reference member // // // // Jim Fawcett, CSE687 - OOD Midterm, Spring 2013 // /////////////////////////////////////////////////////////////// #include #include #include "../MTutility/MTutility.h" class X { public: X(std::ostream& out=std::cout) : out_(out) {} X(const X& x) : out_(x.out_) {} // this is what compiler generated cctor does X& operator=(const X& x) // same as compiler generator assignment { if(this == &x) return *this; // nothing to do as we must use our original ostream - it can't be reset return *this; } void write(const std::string& msg) { out_ << "\n " << msg.c_str(); } private: std::ostream& out_; }; int main() { Title("MT1Q3 - Copy Ctor for class with reference member"); X x; x.write("x writing"); X xcopy(x); xcopy.write("xcopy writing"); std::ofstream fout("test.dat"); if(fout.good()) { X fx(fout); fx.write("fx writing"); X fxcopy(fx); fxcopy.write("fxcopy writing"); fout.close(); std::ifstream fin("test.dat"); if(fin.good()) { std::cout << fin.rdbuf(); } x = fx; // will use x's original ostream, e.g., cout x.write("after assignment"); } std::cout << "\n\n"; return 0; }