// // Program demonstrating use of simple class for dynamically-allocated // array storage. // // The class's constructors, destructors, and assignment operator // print messages when invoked; this program demonstrates several // scenarios in which these functions are used. // #include #include // has EXIT_SUCCESS #include "dArray.h" // definition of dArray class using namespace std; // Function to print the contents of d to stdout, one element per // line, preceded by "msg". // Since d is passed by value, the copy constructor for // class dArray will be invoked. void printArray(const char *msg, const dArray d) { cout << msg << endl; for (dArray::length_pos i = 0; i < d.size(); ++i) cout << d.get(i) << endl; } // Function to multiply every element of d by 2 and return the result // (a new dArray). // We should see the dArray class's constructor and destructor // called for local variable "temp"; we should also see the // copy constructor invoked to make a copy of "temp" for the // return value. dArray doubleArray(const dArray & d) { dArray temp(d.size()); for (dArray::length_pos i = 0; i < d.size(); ++i) temp.set(i, 2*d.get(i)); return temp; } // Main program. int main(int argc, char * argv[]) { cout << "Starting main program.\n"; cout << "Declaring a dArray\n"; dArray a1(4); cout << "Array size = " << a1.size() << ".\n"; a1.set(0, 10); a1.set(1, 20); cout << "Element 0 = " << a1.get(0) << ".\n"; cout << "Element 1 = " << a1.get(1) << ".\n"; cout << "Declaring a dArray as a copy of another dArray.\n"; // We should see dArray's copy constructor being invoked here. dArray a2(a1); cout << "Assigning one dArray to another.\n"; // We should see dArray's assignment operator being invoked here. a2 = a1; cout << "Calling a function that returns a dArray.\n"; // We should see dArray's assignment operator being invoked here; // also see comments for function doubleArray(). a2 = doubleArray(a1); cout << "Calling a function with a pass-by-value dArray parameter.\n"; // See comments for function doubleArray(). printArray("Contents of doubled array:", a2); cout << "Ending main program.\n"; return EXIT_SUCCESS; }