Day_Dreamer
Day_Dreamer

Reputation: 3373

Is it necessary to call a destructor for "string" members within the object destructor?

I created a class:

class Message {
public:
  Message(string sender, string message_text);
  Message(string sender);
  Message();

  ~Message();

  bool wasRead() const;
  void updateWasReadStatus();
  void printMessage() const;
private:
  string Sender_;
  string Text_;
  bool wasRead_;
};

When I implement the destructor, do I have to call explicitly the destructor for Sender_ & Text_? Or are they called implicitly by the default destructor when I write (without implementing ~Message() explicitly):

delete pMessage; //pointer to Message object

Anyhow, I implemented the destructor like this:

Message::~Message(){
    delete Sender_;
    delete Text_;
}

Is it OK? Should I count maybe on the default destructor in this case?

I understand (please correct me if I'm wrong): when a default-destructor is called, it calls a destructor for each member:

If I don't get it right I would be grateful if someone can explain it to me.

Upvotes: 1

Views: 1675

Answers (1)

Stephane Rolland
Stephane Rolland

Reputation: 39916

No, you don't need. (And you must not !)

You are only responsible for the memory you have allocated with new, only then should you use delete.

Upvotes: 9

Related Questions