I am trying to learn C++, so I started coding a custom string class (using only c-style strings) to get familiar with concepts like operator overloading etc. in the case we have a pointer attribute. I wanted to know if there is a smarter/better/neater way to implement the += operator (or the others).
So I am basically defining a private char pointer to store the c-style string, two constructors (empty, char* arg), a copy constructor, a move constructor, a destructor (to deallocate the allocated space from the heap) and two operators (to concatenate strings).
mystring.h
#include <iostream> #include <cstring> class mystring { private: char* str; public: mystring(); mystring(char* str); mystring(const mystring &s); mystring(mystring &&s) noexcept; ~mystring(); mystring& operator=(const mystring &s); friend std::ostream& operator<<(std::ostream &out, const mystring &s); mystring operator+(const mystring &s); mystring& operator+=(const mystring &s); };
mystring.cpp
#include "mystring.h" mystring::mystring() : mystring(nullptr) {}; mystring::mystring(char* str) : str{nullptr} { if(str == nullptr){ this->str = new char; this->str = '\0'; }else { this->str = new char[strlen(str) + 1]; strcpy(this->str, str); } } // Deep copy mystring::mystring(const mystring &s) : str{nullptr} { if(str == nullptr){ this->str = new char; *(this->str) = '\0'; }else { this->str = new char[strlen(s.str) + 1]; strcpy(this->str, s.str); } } // Move constructor mystring::mystring(mystring &&s) noexcept : str{s.str} { s.str = nullptr; } mystring::~mystring() { delete [] str; } mystring& mystring::operator=(const mystring &s){ if(this != &s){ this->str = new char[strlen(s.str) + 1]; strcpy(this->str, s.str); } return *this; } std::ostream& operator<<(std::ostream &out, const mystring &s){ out << s.str; return out; } mystring mystring::operator+(const mystring &s){ mystring concat; concat.str = new char[strlen(this->str) + strlen(s.str) + 1]; strcpy(concat.str, this->str); strcat(concat.str, s.str); return concat; } mystring& mystring::operator+=(const mystring &s){ // temp save "this" string to other mystring other {new char(strlen(this->str) + 1)}; strcpy(other.str, this->str); // allocate space for the concatenated string this->str = new char[strlen(this->str) + strlen(s.str) + 1]; // move "this" and input strings to "this" strcpy(this->str, other.str); strcat(this->str, s.str); return *this; }