avr39ripe

cppMarksClassCopyConstructor

Jul 13th, 2021
1,267
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. class MarksStorage
  4. {
  5.     const size_t size;
  6.     int* storage;
  7.     static size_t count;
  8. public:
  9.     static const int maxMark{ 12 };
  10.     static const int minMark{ 1 };
  11.  
  12.     MarksStorage(size_t sizeP) : size{ sizeP }, storage{ new int[sizeP] {} } {std::cout << "Acquire memory for marks!\n"; ++count; }
  13.     MarksStorage() : MarksStorage(1) {}
  14.     MarksStorage(const MarksStorage& ms) : size{ms.size}, storage{new int[ms.size]}
  15.     {
  16.         for (int i{ 0 }; i < size; ++i)
  17.         {
  18.             storage[i] = ms.storage[i];
  19.         }
  20.         std::cout << "MarksStorage COPY constructed for -> " << this << '\n';
  21.     }
  22.  
  23.     bool setMark(size_t id, int mark)
  24.     {
  25.         if (id < 0 or id > size - 1 or mark < MarksStorage::minMark or mark > MarksStorage::maxMark) { return false; }
  26.         storage[id] = mark;
  27.         return true;
  28.     }
  29.  
  30.     int getMark(size_t id)
  31.     {
  32.         if (id < 0 or id > size - 1) { return 0; }
  33.         return storage[id];
  34.     }
  35.  
  36.     int getSize() { return size; }
  37.  
  38.     static int getCount() { return count; }
  39.  
  40.     void print(/* MarksStorage* const this */)
  41.     {
  42.         // ++size; // ERROR!!
  43.         std::cout << "Marks: ";
  44.         for (int i{ 0 }; i < this->size; ++i)
  45.         {
  46.             std::cout << storage[i] << ' ';
  47.         }
  48.         std::cout << '\n';
  49.     }
  50.  
  51.     ~MarksStorage() { std::cout << "Try to delete memory by ptr - > " << storage << '\n';  delete[] storage; std::cout << "Release memory from marks!\n"; --count; }
  52. };
  53.  
  54. size_t MarksStorage::count{ 0 };
  55.  
  56. //print(&ms1);
  57.  
  58. void print(MarksStorage& ms)
  59. {
  60.     std::cout << "Marks: ";
  61.  
  62.     for (int i{ 0 }; i < ms.getSize(); ++i)
  63.     {
  64.         std::cout << ms.getMark(i) << ' ';
  65.     }
  66.  
  67.     std::cout << '\n';
  68. }
  69.  
  70. int main()
  71. {
  72.     //char* str{ new char[10]{"hello"} };
  73.     //char* str1{ str };
  74.  
  75.     //std::cout << str1 << '\n';
  76.  
  77.     //return 0;
  78.  
  79.     MarksStorage ms1{ 4 };
  80.  
  81.     ms1.setMark(0, 11);
  82.     ms1.setMark(1, 7);
  83.     ms1.setMark(2, 9);
  84.     ms1.setMark(3, 10);
  85.  
  86.     std::cout << "MarksStorage 1\n";
  87.     //ms1.print();
  88.     print(ms1);
  89.  
  90.     MarksStorage ms2{ ms1 };
  91.     std::cout << "MarksStorage 2\n";
  92.     //ms2.print();
  93.     print(ms2);
  94.  
  95.     return 0;
  96. }
RAW Paste Data