// CSE 374, 2015-03-04, BM #include // class D will keep the default copy constructor class D { public: int* z; D() { z = new int[4]; } /* no redefinition of copy constructor. * C++ will give us the default, which * behaves the same as struct assignments. */ }; // class C will re-define the copy constructor class C { public: int* z; C() { z = new int[4]; } // re-define the copy constructor // to do a deep copy // QUIZ: copy constructor takes a reference, why not a value? // e.g. why C(C& to_copy) rather than C(C to_copy) ? C(C& to_copy) { std::cout << "copying" << std::endl; z = new int[4]; for (int i=0; i<4; i++) { z[i] = to_copy.z[i]; } } }; // a function that takes an object of class C _by value_ void uses_c(C c) { std::cout << c.z << std::endl; } int main() { // calls constructor C() C c1; // calls the constructor C() C c2; // calls the copy constructor on c2, with argument c1 c2 = c1; std::cout << "copied a C: " c1.z << " " << c2.z << std::endl; // calls copy constructor on c3, with argument c1 C c3(c1); // since uses_c takes its argument by value, // c1 will be copied, invoking the copy constructor of C uses_c(c1); // demonstrate the default copy constructor D d1; D d2; d2 = d1; std::cout << "copied a D: " << d1.z << " " << d2.z << std::endl; }