Playing well with Java CollectionsPlaying well with C++copy constructorAssignment operatorDestructorCPS 108 : Fall 20024.1Playing well with Java CollectionsEvery object has an equals(..) method, contract?What does this return? How do you implement it, what about apples and oranges?Default behavior? When to over-ride?If you override/over-ride equals, see hashCode()What does this return? Implementation issues?Good, bad, …?CPS 108 : Fall 20024.2Playing well with C++What happens with the statement myDay = d; ?assignment is memberwise unless operator = overloadedcopy constructor used in passing parameters by valueIf you need one of: destructor, assignment operator, copy constructor, you need all of themheuristic only: managing resources other than memorypreventing objects from being copiedwhat about non-copyable state, e.g., streamIn assignment operator, watch for self-assignmentStudy implementation of string/vectorCPS 108 : Fall 20024.3copy constructorUsed for “first-time” creationDate d(1,1,2000);Date copy(d); Used for pass-by-valueDoStuff(Date d);//…Date first(1,1,2000);DoStuff(first);what about use of myLength in code as opposed to length()?template <class Item>tvector(const tvector<Item> & vec)// precondition: Item supports assignment // postcondition: return copy of vec { // allocate storage myList = new Item[myLength=vec.myLength]; assert(myList != 0); // copy elements for(int k = 0; k < vec.myLength; k++) { myList[k] = vec.myList[k]; } }CPS 108 : Fall 20024.4Assignment operatorWe want to have deep copy when assigning as well as when we copyObject x(23,4);Object y;y = x; // assignment operatorObject z = x; // copy constructor!!!z = y = x; // how does this work?Assignment operator returns *thisWon’t be const reference return, will be referenceAssignment operator checks for not assigning to selfCan assign to self via aliasing, e.g., pass-by-referenceAssign to every data member (deep copy as needed)See tvector for detailsCPS 108 : Fall 20024.5DestructorIf you need copy constructor, you need assignment operator, and you need destructorWhat is purpose of destructor?Free resourcesWhat’s a resource: memory, files, network connectionsWhen is the destructor called?Automatically when a stack object goes out of scopeWhen you call delete on a heap objectWhat’s the problem with this “automatic destruction”?It’s not automatic, it’s fraught with problems getting it rightWhat about yahoo and the rolling
View Full Document