1 / 6

Understanding Memberwise Assignment in C++: Object Initialization and Assignment

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.

shea
Télécharger la présentation

Understanding Memberwise Assignment in C++: Object Initialization and Assignment

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Memberwise Assignment 14.3

  2. 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;

  3. 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; };

  4. // // 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; }

More Related