Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class MyString
- {
- private:
- char *str;
- public:
- MyString();
- MyString(const char *str);
- MyString( const MyString &other);
- ~MyString();
- //assignment operator
- MyString& operator=(const MyString &rhs); // copy assignment operator
- void Display() const;
- int get_length() const;
- const char *get_str() const;
- };
- MyString& MyString::operator=(const MyString &rhs)
- {
- //if (this == &ref)
- // return *this;
- delete[] this -> str;
- str = new char[strlen(rhs.str)+1];
- delete[] this -> str;
- str = new char[strlen(rhs.str)+1];
- strcpy(this->str , rhs.str);
- return *this;
- }
- MyString::MyString()
- {
- str = new char[1];
- *str = '\0';
- }
- MyString::MyString(const char * s)
- {
- if(s == nullptr)
- {
- str = new char[1];
- *str = '\0';
- }
- else
- {
- str = new char[strlen(s)+1];
- strcpy(str, s);
- }
- }
- MyString::MyString(const MyString & source)
- {
- cout << "Copy Constructor" << endl;
- str = new char[strlen(source.str)+1];
- strcpy(str, source.str);
- }
- MyString::~MyString()
- {
- if (str != nullptr)
- delete[] str;
- }
- void MyString::Display() const
- {
- for (int i = 0; i <strlen(str) ; i++)
- cout << str[i];
- cout << endl;
- }
- int MyString::get_length() const
- {
- return strlen(str);
- }
- const char * MyString::get_str() const
- {
- return str;
- }
- int main()
- {
- MyString ms("Hello");
- MyString name("Sumit");
- MyString MyEdu("BELLB");
- MyString aa{name};
- aa.get_str();
- MyString a;
- a = aa;
- cout << "aa-> str : " << aa.get_str() << endl;
- cout << "a-> str : " << a.get_str() << endl;
- //aa = aa;
- //cout << name.get_str() << endl;
- //cout << "string is: " << ms.Display() << endl;
- //cout << "Length of the string : " << ms.get_length() << endl;
- //cout << "The string : " << ms.get_str() << endl;
- cout << "Program End" ;
- return 0;
- }
Add Comment
Please, Sign In to add comment