0

I have written the demo class. It allocated the array arr dynamically. Do I need to write the default destructor ~demo as shown in the code to free up the memory allocated to arr or the default destructor does that itself?

#include <iostream>
using namespace std;

class demo
{

    int *arr;

public:
    demo(int n)
    {
        arr = new int[n];
    }
    ~demo()
    {
        delete[] arr;
    }
};
int main()
{
    demo obj(10);
    cout << "done\n";
    return 0;
}
Evg
  • 25,259
  • 5
  • 41
  • 83
Harry
  • 11
  • If you use `std::vector` here, instead of calling `new`, you can forget about memory management entirely. – Paul Sanders Jul 23 '23 at 14:57
  • 1
    https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three – NathanOliver Jul 23 '23 at 14:58
  • Thanks! Can you elaborate that, please? I'm new to this. And how to I learn about this? – Harry Jul 23 '23 at 15:00
  • `~demo()` is a *destructor*, not a constructor. The `demo(int n)` is a constructor. But, in short, if your code does an explicit `new` expression somewhere, it is necessary to ensure a corresponding `delete` expression is performed exactly once for every time the `new` expression is executed. So, yes, your destructor is necessary. You might also wish to investigate "rule of three" or (C++11 and later) "rule of five", to avoid other cases in which a `new` expression in your class is unmatched by a corresponding `delete` expression. – Peter Jul 23 '23 at 15:02
  • Also, in your class definition, you only have one constructor that takes an argument `n`. The default constructor in C++ is a constructor that can be called with no arguments. So your class does not currently have a default constructor. – Sash Sinha Jul 23 '23 at 15:03
  • If you want that behavior use std::vector, in current C++ try to avoid the use of new/delete unless you are really implementing a datastructure of your own. – Pepijn Kramer Jul 23 '23 at 15:17
  • You "learn about this" in your favorite introductory C++ textbook, which explains what `std::vector` is, how to use it and all other core fundamental C++ concepts. Unfortunately Stackoverflow isn't really meant to be a replacement for a C++ textbook, we don't provide tutorials here, we only answer ***specific*** programming questions. Since you're just starting to learn C++ you are fortunate to be in the best position to do it correctly: by following an organized textbook-guided curriculum, instead of many other strayed souls who waste years on Youtube videos and useless coding puzzles. – Sam Varshavchik Jul 23 '23 at 15:18

0 Answers0