Search code examples
c++memorydestructornew-operator

how to delete a new of an object of base class in a derivative class?


Imagine I have a base class that contains a pointer and a destructor that deletes the pointer.

class Base {
private: 
  int *p;
public:
  Base(int data) : p(new int[data]) {}
  ~Base() {delete[] p;}
};

And I a have a derivative class that also contains a pointer and has a method in which I make a new of the base class.

class Drived: public Base{
private:
  Base* _root;
public:
  Drived(int data) : Base(data), _root(new Base(data)) {}
  ~Drived() {delete _root;}
  void myMethod() {Base* bewBase = new Base(10);}
};

So if I do this, I would have a memory leak because in method myMethod I do a new and never delete it.
I want to know how I could fix this problem.
Thank you in advanced for helping me.
P.S: the codes in this question are just examples and my not compile properly. i just wanted to show a better vision of my question. Also I know that I can use std::unique_ptr for this kind of staff but i really want to learn how to manage this throw raw pointers.


Solution

  • Something like this:

    class Drived: public Base{
    private:
      Base* _root;
      Base* bewBase;
    public:
      Drived(int data) : _root(new Base(data)) {bewBase = nullptr;}
      ~Drived() {delete _root; if (bewBase != nullptr) delete bewBase;}
      void myMethod() {bewBase = new Base(10);}
    };
    

    or you can reuse _root pointer, and delete the content of _root before new allocation.