llsumitll

Assignment Operator

Jan 22nd, 2023
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | Source Code | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. class MyString
  4. {
  5.     private:
  6.         char *str;
  7.     public:
  8.         MyString();
  9.         MyString(const char *str);
  10.         MyString( const MyString &other);
  11.         ~MyString();
  12.  
  13.         //assignment operator
  14.         MyString& operator=(const MyString &rhs); // copy assignment operator
  15.        
  16.         void Display() const;
  17.         int get_length() const;
  18.         const char *get_str() const;
  19. };
  20.  
  21. MyString& MyString::operator=(const MyString &rhs)
  22. {
  23.     //if (this == &ref)
  24.     //    return *this;
  25.  
  26.     delete[] this -> str;
  27.     str = new char[strlen(rhs.str)+1];
  28.     delete[] this -> str;
  29.     str = new char[strlen(rhs.str)+1];
  30.     strcpy(this->str , rhs.str);
  31.     return *this;
  32. }
  33. MyString::MyString()
  34. {
  35.     str = new char[1];
  36.     *str = '\0';
  37. }
  38. MyString::MyString(const char * s)
  39. {
  40.     if(s == nullptr)
  41.     {
  42.         str = new char[1];
  43.         *str = '\0';
  44.     }
  45.     else
  46.     {        
  47.         str = new char[strlen(s)+1];
  48.         strcpy(str, s);
  49.     }
  50. }
  51.  
  52. MyString::MyString(const MyString & source)
  53. {
  54.     cout << "Copy Constructor" << endl;
  55.     str = new char[strlen(source.str)+1];
  56.     strcpy(str, source.str);
  57. }
  58.  
  59. MyString::~MyString()
  60. {
  61.     if (str != nullptr)
  62.         delete[] str;
  63. }
  64. void MyString::Display() const
  65. {
  66.     for (int i = 0; i <strlen(str) ; i++)
  67.         cout << str[i];
  68.     cout << endl;
  69. }
  70.  
  71. int MyString::get_length() const
  72. {
  73.     return strlen(str);
  74. }
  75. const char * MyString::get_str() const
  76. {
  77.     return str;
  78. }
  79.  
  80. int main()
  81. {
  82.     MyString ms("Hello");
  83.     MyString name("Sumit");
  84.     MyString MyEdu("BELLB");
  85.     MyString aa{name};
  86.     aa.get_str();
  87.     MyString a;
  88.     a = aa;
  89.     cout << "aa-> str : " << aa.get_str() << endl;
  90.     cout << "a-> str : " << a.get_str() << endl;
  91.     //aa = aa;
  92.     //cout << name.get_str() << endl;
  93.     //cout << "string is: " << ms.Display() << endl;
  94.     //cout << "Length of the string : " << ms.get_length() << endl;
  95.     //cout << "The string : " << ms.get_str() << endl;
  96.     cout << "Program End" ;
  97.     return 0;
  98. }
Add Comment
Please, Sign In to add comment