List of all available Websheets
Viewing cpp/cs104/copyassign/intarray_copycon by redekopp@usc.edu. You have unsaved changes. Log in above to create, edit, preview and publish Websheets.
Property | Value |
---|---|
Description html markup shown to student | Add a copy constructor to perform a deep copy of the array. Does that solve all your problems? <p> Also, go back to <tt>printVals(...)</tt>. <strong>Do you really need to pass-by-value?</strong> How could you avoid making a copy of the argument? |
Remarks Comments, history, license, etc. | Copied from problem cpp/cs104/copyassign/intarray_destructor (author: redekopp@usc.edu) Copied from problem cpp/cs104/copyassign/intarray1 (author: redekopp@usc.edu) |
Engine | |
Template / Reference solution |
using namespace std; class MyArray { public: MyArray() { cout << "In default constructor" << endl; dat = NULL; len = 0; } MyArray(int d[], int num); //normal \[ REDACTED ]\ ~MyArray(); int& operator[](int loc) { return dat[loc]; } int const & operator[](int loc) const { return dat[loc]; } int size() const { return len; } private: int len; int *dat; }; // Normal constructor MyArray::MyArray(int d[], int num) { dat = new int[num]; len = num; for(int i=0; i < len; i++){ dat[i] = d[i]; } } // Copy Constructor \[ REDACTED ]\ { cout << "In copy constructor" << endl; \[ REDACTED ]\ } MyArray::~MyArray() { cout << "In destructor" << endl; delete [] dat; } \[ REDACTED \show: void printVals(MyArray arr) ]\ { for(int i=0; i < arr.size(); i++){ cout << arr[i] << " "; } cout << endl; } int main() { int vals[] = {9,3,7,5}; MyArray a1(vals,4); MyArray a2(a1); // calls copy constructor MyArray a3 = a1; // calls copy constructor MyArray a4; a4 = a1; // calls default assignment // how are the contents of a2, a3, a4 // related to a1 printVals(a1); a1[0] = 11; printVals(a2); printVals(a4); return 0; } |
C++ test suite json list of stdin/args tests e.g. [{"stdin":"hi", "args":["4", "5"]}, {"stdin":"noargs"}] to just run once with no input use [{}] | [{}] |
Solution visibility | |
Is example? i.e., just a demo | |
Add compiler flag(s) json list of flags e.g. ["-Wno-unused-variable"] | ["-Wno-unused-variable"] |
Note: problems are open-source by default (see 'Public permissions'). Assumed license for open problems is Creative Commons 4.0 Attribution-ShareAlike unless specified in 'Remarks'.