Overloading the copy assignment operator : overload assignment operator « Operator Overloading « C++ Tutorial






#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
using namespace std;

class MyString {
  public:
    MyString(const char* pText) {
      pString = new char[ strlen(pText) + 1 ];
      std::strcpy(pString, pText);
    }

    ~MyString() {
      cout << endl << "Destructor called." << endl;
      delete[] pString;
    }

    MyString& operator=(const MyString& String) {
      cout << endl << "calling =." << endl;
      if(this == &String)
        return *this;

      delete[] pString;
      pString = new char[ strlen(String.pString) + 1];

      // Copy right operand string to left operand
      std::strcpy(this->pString, String.pString);

      return *this;
    }


    char* getString() const{ return pString; }

  private:
    char* pString;
};

int main() {
  MyString warning("There is a String");
  MyString standard("");

  cout << warning.getString();
  cout << standard.getString();

  standard = warning;

  cout << warning.getString();
  cout << standard.getString();
  cout << endl;

  return 0;
}
There is a String
calling =.
There is a StringThere is a String

Destructor called.

Destructor called.








10.3.overload assignment operator
10.3.1.Overloading the copy assignment operator
10.3.2.Define -, + and = for the ThreeD class
10.3.3.Overload operator plus (=)
10.3.4.Overload assignment for Point
10.3.5.Use overloaded +=