/* Ken Moore 3/22/2005 Did not want to waste lecture time developing this code - went home did this demo on c-tor's/value based symantics. */ #include #include using namespace std; class testCons{ public: int thirty; testCons(){thirty = 30;cout << " in default c-tor" << endl;} testCons(testCons & tcr){thirty = tcr.thirty; cout << " in copy c-tor" << endl;} /* // If in, causes error // What happens is this: // returnLocalAsRef is returning a non protected variable. // Without this assignment operator, nothing affects the program stack before // assignment in main to tc. // When the assignment operator is used, it gets pushed on the program stack before // the assignment, showing the folly of returning a local variable by reference. testCons& operator=(const testCons& rhs){ thirty = rhs.thirty; cout << "in assignment overload" << endl; return *this; } */ }; // show that pass by value calls copy c-tor. void passByValue(testCons x){ cout << " In pass by value" << endl; } // create potential mistake - add = operator to show mistake. testCons& returnLocalAsRef(){ cout << " In returnLocalAsRef " << endl; testCons tcr; tcr.thirty = 14; return tcr;// generates warning. } // show that return by value calls copy constructor. testCons returnLocalByValue(){ cout << " In returnLocalByValue " << endl; testCons tcr; tcr.thirty = 44; return tcr;// generates warning. Actually corrupts program when = operator in. } testCons* returnPtr(){ cout << " In returnPtr " << endl; testCons *ptc = new testCons(); return ptc; } int main(void){ testCons *ptc, tc; passByValue(tc); // causes call to copy constructor! tc = returnLocalByValue(); // returns invalid cout << " After returnLocalByValue tc.thirty = " << tc.thirty << endl; // thirty? tc = returnLocalAsRef(); // returns invalid cout << " After returnLocalAsRef tc.thirty = " << tc.thirty << endl; // thirty? ptc = returnPtr(); delete ptc; return EXIT_SUCCESS; }