#include <iostream>
class ArrayClass
{
private:
int *m_Arr;
int i;
public:
int Size;
ArrayClass() : Size(5), i(0), m_Arr(nullptr)
{
std::cout << "The constructor was called." << std::endl;
}
~ArrayClass()
{
std::cout << "The destructor was called." << std::endl;
delete[] m_Arr;
}
void InitArr()
{
m_Arr = new int[Size];
}
void Setter(int &var)
{
*(m_Arr + i) = var;
i++;
}
int *Getter() const
{
return m_Arr;
}
};
int main()
{
ArrayClass *instance = new ArrayClass[2];
std::cout << instance << std::endl;
for (int j = 0; j < 2; j++)
{
(instance + j)->InitArr();
for (int i = 1; i <= (instance + j)->Size; i++)
{
(instance + j)->Setter(i);
}
int *Get = (instance + j)->Getter();
std::cout << "The numbers are:" << std::endl;
for (int i = 0; i < (instance + j)->Size; i++)
{
std::cout << *(Get + i) << std::endl;
}
}
for (int l = 0; l < 2; l++)
{
delete (instance + l);
}
std::cin.get();
return 0;
}
I am a beginner in C++, and have ran into a problem, I am trying to use the delete keyword, using the for loop, instead of delete[] instance. I am just trying to keep this method of deleting the instance array in heap, using the pointer arithmetic. But the delete is not doing the work, when I run the program, the destructor code snippet is not printed out on the cmd, the program just terminates, not respecting the line std::cin.get();
Only, doing this works. delete[] instance;.
But, I want this method to be used,
for (int l = 0; l < 2; l++)
{
delete (instance + l);
}
So, can you please rectify the mistake.
Or, is it that the method I am trying to use, even valid in C++
deletemust match thenewthat was used to allocate memory. You have onenew[]to createinstance, but then try to call 3deleteto remove it - that cannot work.delete[] instanceoutside of any loop is the only allowed way to releaseinstance.delete[] instance;." because only that is the correct way to delete the array. There isnt much more to it (other than you shouldnt be usingnewanddeletein the first place, but I suppose this is for an exercise)newanddeleteare an advanced topic. If someone is purporting to teach you C++ and is starting with owning raw pointers, they are doing you a disservice.