avr39ripe

cppPlayerClassDemoDestructor

Jul 8th, 2021
1,236
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. const int maxNameLen{ 50 };
  5.  
  6. class Player
  7. {
  8.     int id;
  9.     char* name;
  10.     int rank;
  11.  
  12. public:
  13.     Player() : Player{ 0, "John Doe", 0 } { std::cout << "Player default constructor started!\n"; }
  14.     Player(int idP, const char* nameP, int rankP) : id{ idP }, name{nullptr}, rank{ rankP }
  15.     {
  16.         setName(nameP);
  17.         std::cout << "Player parametrized constructor started!\n";
  18.     }
  19.  
  20.     void setName(const char* nameP)
  21.     {
  22.         auto len{ strlen(nameP) + 1 };
  23.  
  24.         if (!name)
  25.         {
  26.             name = new char[len];
  27.         }
  28.         else if (name and strlen(name) + 1 < len)
  29.         {
  30.             delete[] name;
  31.             name = new char[len];
  32.         }
  33.  
  34.         strcpy_s(name, len, nameP);
  35.     }
  36.  
  37.     void print()
  38.     {
  39.         std::cout << id << ' ' << name << ' ' << rank << '\n';
  40.     }
  41.  
  42.     ~Player()
  43.     {
  44.         std::cout << "Player destructor started!\n";
  45.         delete[] name;
  46.     }
  47. };
  48.  
  49. void printPlayers(Player* begin, Player* end)
  50. {
  51.     for (auto player{ begin }; player != end; ++player)
  52.     {
  53.         player->print();
  54.     }
  55. }
  56.  
  57. int main()
  58. {
  59.     Player* ptr{};
  60.     {
  61.         int x{ 42 };
  62.         int* pI{ new int{42} };
  63.  
  64.         Player* p1{ new Player{} };
  65.         p1->print();
  66.  
  67.  
  68.         //Player p1;
  69.         //p1.print();
  70.  
  71.         ptr = p1;
  72.         delete pI;
  73.     }
  74.     std::cout << "main Part started!\n";
  75.  
  76.     /*const int playersCount{ 3 };
  77.     Player players[playersCount]{ {26007, "MadMax", 39}, {28002, "Batman", 25}, {29002, "Joker", 15} };
  78.     Player* const playersEnd{ players + playersCount };
  79.  
  80.     players[1].setName("MishMans");
  81.     printPlayers(players, playersEnd);*/
  82.     delete ptr;
  83. };
  84.  
RAW Paste Data