60 likes | 209 Vues
This guide explores the concept of memberwise assignment in C++, focusing on how one object can be assigned to another or initialized using another object's data. It details the process of copying member values from one instance to another through examples such as `instance2 = instance1`. Additionally, the guide presents a class example for `MyString`, showcasing how to implement an assignment operator that ensures proper memory management and avoids self-assignment. Learn the intricacies of constructors, destructors, and member functions in object-oriented programming.
E N D
Memberwise Assignment • Can use = to assign one object to another, or to initialize an object with an object’s data • Copies member to member. e.g., instance2 = instance1; means: copy all member values from instance1 and assign to the corresponding member variables of instance2 • Use at initialization: Rectangle r2 = r1;
Declare the Class my_string class MyString{ public: MyString(int n); MyString(const char * str); ~ MyString(); int length() const ; //const member function void print() const; private: char * s; int len; };
// // Assignment of a Mystring into another Mystring // Mystring& Mystring::operator=(const Mystring& mstr) { // ("Mystring assignment operator”) if (&mstr == this) { //("Not copying myself"); return *this; } // Delete the old string that this class was holding. delete [] s; // Allocate enough space for the new string. s = new char[mstr.length() + 1]; // Copy the new string into myself strcpy(s, mstr.s); // Return myself return *this; }