0

I need help creating a class destructor. I don't really understand how to create one but I do understand what they do. Since new is called to create users and prizes, I need to write a destructor that calls delete on all the users and prizes.

class User {
  public:
    string username;
    string realname;
    int points;
    set <string> phone_numbers;
};
class Prize { 
  public:
   string id;
   string description;
   int points;
   int quantity;
};

class CodeProcessor {
    ~CodeProcessor(); //destructor 
  protected:
    map <string, User *> Names;
    map <string, Prize *> Prizes;
}
  • 2
    Why don't you just make the maps contain objects, rather than pointers ? – Sid S Mar 30 '18 at 06:55
  • *The destructor doesn't have to clear the maps or sets* -- You have no control over that. The destructor of the `map` will be called automatically anyway when `~CodeProcessor()` is invoked, thus clearing the map. – PaulMcKenzie Mar 30 '18 at 06:55
  • Also, consider what happens if you copy or assign `CodeProcessor` objects. Your destructor will invoke undefined behavior, since `CodeProcessor` has incorrect copy semantics. Time to read up on [the rule of 3/5/0](http://en.cppreference.com/w/cpp/language/rule_of_three) – PaulMcKenzie Mar 30 '18 at 06:59
  • @PaulMcKenzie some backstory: https://stackoverflow.com/questions/49568410/inserting-into-a-map . The asker is stuck with crippled code because of a poorly written header they've been tasked with implementing. – user4581301 Mar 30 '18 at 07:16
  • @user4581301 I don't want to seem needy, but I need help with a Delete_User function, but I can't ask another question. If I updated the question would help out? – user9573040 Mar 30 '18 at 07:43
  • @user9573040 Please don't tell us that `User`'s destructor is also borked and you need to destroy it from the outside... – Quentin Mar 30 '18 at 09:15
  • @user9573040 Did you get this working? –  Apr 06 '18 at 07:06

2 Answers2

0

You could implement the destructor like this

CodeProcessor::~CodeProcessor()
{
    for (auto n : Names)
    {
        delete n.second;
    }
    for (auto p : Prizes)
    {
        delete p.second;
    }
}

But then again, why don't you just make the maps contain objects, rather than pointers ?

R Sahu
  • 204,454
  • 14
  • 159
  • 270
Sid S
  • 6,037
  • 2
  • 18
  • 24
0

You need to iterate over the values in the map and delete each one. In C++17 you can use the following

for (auto [key, user] : Names) {
    delete user;
}
for (auto [key, prize] : Prizes) {
    delete prize;
}

More information on looping over maps in this answer