I got stuck with deleting an dynamically allocated array of int. I've got a destructor, where I'm trying to use a loop for to delete all elements of array and finally delete it. I have code on http://rextester.com/OTPPRQ8349 Thanks!
class MyClass
{
public:
int _a;
int* c;
int fRozmiar;
static int fIlosc;
MyClass() //default constructor
{
_a=0;
c = new int [9];
for(int i = 0; i<=9; i++)
{
c[i] = 1;
}
fIlosc++;
}
MyClass(int a1, int c1) // parametrized constructor
{
_a=a1;
c = new int [c1];
for(int i = 0; i<=c1; i++)
{
c[i] = rand();
}
fIlosc++;
}
MyClass(const MyClass &p2) // copy constructor
{
_a =p2._a;
c = p2.c;
fRozmiar = p2.fRozmiar;
fIlosc = fIlosc;
fIlosc++;
}
~MyClass(); // destructor
static int getCount() {
return fIlosc;
}
};
//Initialize static member of class
int MyClass::fIlosc = 0;
MyClass::~MyClass()
{
for(int i = 0; i<sizeof(c); ++i)
{
delete[] c[i];
}
delete[] c;
fIlosc--;
}
int main()
{
}
sizeof(c)isn't going to give you the size of the buffer pointed at byc. It will give you the size of the pointer, the size of an address, in bytes. Not very useful most of the time.c = p2.c;is a fatal error. You now have two objects pointing at the same allocation. When the destructor runs for one of these objects the memory will be gone for the other object. If the program doesn't crash over the other object trying to use released memory, something horrible (probably a crash) will happen when the other object is deleted and tries to delete memory that has already been deleted.fIlosc = fIlosc;assigning a variable to itself. Since this variable is static, it will be the same for both objects so there's no point to doing this.