CAbout CAbout::operator+(const CAbout& str) { CAbout dopstr; dopstr.m_length = this->m_length + str.m_length - 1; dopstr.m_strok = new char[dopstr.m_length]; for (size_t i{0}; i < this->m_length; i++) { *(dopstr.m_strok + i) = *(this->m_strok + i); } for (size_t i{ 0 }; i < str.m_length + 1; i++) { dopstr.m_strok[i + this->m_length] = str.m_strok[i]; } return dopstr; } 

The class itself looks like a trace. way

 class CAbout { public: CAbout(const char* str = "Standart str"); CAbout(const CAbout& str); ~CAbout(); CAbout& operator=(const CAbout& str); CAbout operator+(const CAbout& str); void show(); private: char* m_strok; size_t m_length; }; 

Interested in the functions of the operator +, all other functions work well. Even not so much interested in how to write the correct working code, but why the first for loop in the function of the + operator works well, and the second cycle passes, but does not change anything. The string of class dopstr takes the value this-> m_strok in the first loop and does not change further. What is the problem ?

  • I don’t understand why memory is allocated for the sum of lengths without one, and the total number of loop iterations is the sum of lengths plus one? - Zealint

1 answer 1

As I understand it, m_length for you takes into account the null character of the string too. Then everything is obvious - just the second cycle starts writing after the zero character.

  • Doesn't he overwrite the null character of the first line? - Senya
  • @ Senya Let's let the first one be "Senya", the second one - well, it doesn't matter yet. m_length equals 5. Writing the first row to a NEW array — all 5 characters. Now the second cycle starts by writing to which element? That's right, 0+m_length = 5 , i.e. in SIXTH. AFTER ZERO. And, by the way, you also get beyond the array, so if the program does not crash right away - this can be considered bad luck - it means that it will fall down at some remote point ... - Harry
  • I get it now. Thank you - Senya