We have already seen using constructor to create class object and destructor which gets called automatically to do clean up work.

This is the use case where constructor is used to allocate create dynamic objects and destructor to release the memory used for dynamic allocation.

For example:

#include <iostream>
 
class Basket
{
 
public:
    int totalItems{}; // should be private
    int *items{}; // should be private
    
    Basket(int count)
    {
        std::cout << "Creating" << '\n';
        items = new int[count];
        totalItems = count;
    }
 
    ~Basket()
    {
        std::cout << "Destroying" << '\n';
        delete items;
    }
 
    const int *begin() const
    {
        return items;
    }
 
    const int *end() const
    {
        return items + totalItems;
    }
};
 
int main(int argc, char const *argv[])
{
    int totalItems{};
    std::cout << "Enter item counts: " << '\n';
    std::cin >> totalItems;
 
    Basket b1(totalItems);
 
    std::cout << b1.totalItems << '\n';
 
    std::cout << "Enter " << totalItems << " items" << '\n';
    for (int i = 0; i < b1.totalItems; ++i)
    {
        std::cin >> b1.items[i];
    }
 
    std::cout << "Items you've entered" << '\n';
 
    for (auto i : b1)
    {
        std::cout << i << '\n';
    }
 
    return 0;
}

This example shows a class basket which has constructor and destructor. Constructor takes a length argument and dynamically creates an array of that size. Destructor then deallocates the array using delete operator.

Please note that when we create an object of a container/list, we use direct initialization where we pass length as we did using Bucket b1(totalItems); (like we do with std::vector) .

References

  1. https://www.learncpp.com/cpp-tutorial/destructors/