Dynamic allocation with class

  c++, class, dynamic

I am learning Class and I want to write a simple code that insert value into an array that have been allocated dynamically. I want my program to increase memory allocation of the array by *2 if the current size of the array is full, and also copy the precedent value of the array into the bigger one. (I want to do this manually and not use vector).

Here is the code I wrote, but I don’t understand where is the memory leak in my code, which causes my array to not display correctly.

Main

int main()
{
    Data one(5);
    for (int i = 0; i < 12; i++)
        one.add(i);
    one.display();

    return 0;
}

Header File

class Data
{
private:
    int* _database;
    int _size;
    int _currentSize;
public:
    Data(int size);
    ~Data();

    void display();
    void add(int value);
};

Class file

#include "data.h"
#include <iostream>
using namespace std;

Data::Data(int size)
{
    this->_database = new int[size];
    this->_size = size;
    this->_currentSize = 0;
}

Data::~Data()
{
    if (this->_database)
        delete[] this->_database;
}

void Data::display()
{
    cout << "Size: " << this->_size << endl;
    cout << "Current size: " << this->_currentSize << endl;
    for (int i = 0; i < this->_currentSize; i++)
        cout << *(this->_database + i) << " ";
    cout << endl;
}
void Data::add(int value)
{
    if (this->_currentSize < this->_size || this->_currentSize > this->_size)
    {
        this->_currentSize = value;
    }
    else
    {
        Data tmp(this->_currentSize * 2);
        for (int i = 0; i < this->_currentSize; i++)
            *(tmp._database + i) = *(this->_database + i);
        *(tmp._database + this->_currentSize) = value;
        delete[] this->_database;
        this->_database = tmp._database;
        this->_size = tmp._size;
    }
    this->_size++;
}

Source: Windows Questions C++

LEAVE A COMMENT