copy constructors

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

BY DEFAULT

1> Constructor 2>Destructor 2> Copy constructor 3>Assignment operator

assignment operator

1>destruction => immediate reconstruction. 2>Shallow Copy

COPY VS ASSIGN Copy constructor is called when a new object is created from an existing object, as a copy of the existing object (see this G-Fact). And assignment operator is called when an already initialized object is assigned a new value from another existing object.

>Copy: create new object >Assg: assign to existing object

A a1, a2;//default ctor A a3(a2);//copy ctor A a2=a1;//calls copy ctor a3=a2;//calls assignment ctor

Resource Acquisition Is Initialization(RIIA)

copy constructors

Shallow Copy 1>Function return 2>Function Argument 3>Temp Object 4>Construct Object based on other 5>exception is thrown using this object type (Class a; .... throw a;)

copy (no need to check, clean up, return) 1>Copies new to existing 2> initializes uninitialized memory 3>donot return anything. 4> A ( const A&); // copy ctor 5>Default: Shallow

assignment 1>Copies existing to existing 2>Assigns existing initialized objects. 3> returns *this 4> A& operator=(constA&);//assignment ctor 5>Default: Shallow

What is called here mystring betty("Betty Rubble"); mystring bettyClone; bettyClone = betty;

assignment operator is being called instead of the copy constructor.By default, the assignment operator does a member-wise copy of the object, which in this case gives a shallow copy.

assignment operator Implementation 1>Check self assignment 2>Destruction + Construction 3>return *this; // return self-reference

const mystring& operator=(const mystring& rhs) { if (this != &rhs) { delete[] this->str; // donate back useless memory this->str = new char[strlen(rhs.str) + 1]; // allocate new memory strcpy(this->str, rhs.str); // copy characters this->length = rhs.length; // copy length } return *this; // return self-reference so cascaded assignment works }

exception is thrown using this object type (Class a; .... throw a;)

exception is thrown using this object type (Class a; .... throw a;)


Kaugnay na mga set ng pag-aaral

Ch 13 Cardiovascular Alterations

View Set

تربية اسلامية توجيهي

View Set

Econ 448 Exam 2 Practice Questions

View Set

Chapter 15 : Implementing Secure Cloud Solutions

View Set