Hello. I solve 2 problem 9 chapters from the book by R. Lafore . Stumbled upon a problem. Task: Recall the STRCONV example from chapter 8. The String class in this example has a defect: it does not have protection in case its objects are initialized to be too long (the size constant has the value 15). For example: String s = "Эта строка имеет очень большую длину и мы можем быть уверены, что она не уместится в отведенный буфер, что приведет к непредсказуемым последствиям."; will cause str array to overflow with string s with unpredictable consequences up to system crash. Create a class Pstring , derived from the class String , in which we prevent the possibility of a buffer overflow in the definition of too long a string constant. The new constructor of the derived class will copy only size-1 characters to str if the line is too long and will copy the entire line if it is shorter than size . Write the main() function of the program to test its work with strings of different lengths.
#include <iostream> #include <cstring> const int size = 15; class String { protected: char str[size]; public: String () { str[0] = '\x0'; } String (const char* s) { strcpy(str, s); std::cout << "Скопировано: " << str << std::endl; } void display () const { std::cout << str << std::endl; } operator char* () { return str; } }; class Pstring : public String { public: Pstring (char* s) { if (strlen(s) >= size) { for (int index = 0; index < size - 1; ++index) { str[index] = s[index]; } str[strlen(str)] = '\x0'; } else { String(s); // почему не копируется строка, а вызывается конструктор без аргументов? } } }; int main () { Pstring p1 = "pointers is evil!!!"; p1.display (); Pstring p2 = "char * is bad"; p2.display(); return 0; } When defining variables of the Pstring class, the default constructor is first called String :: String (); before block execution. Next, there is a check for the length of the string. Question: Why, if the string is smaller, then when the constructor is called String (s); Is the string value not copied to the else branch? Why the output is an empty string.