Does delete call the destructor? I have modified the code on the first answer a little bit, but i can't catch my wrong. It is being compiled with 0 errors but program crashes when i run it, also devC++ debug mode gives me SIGTRAP signal. I'd really appreciate a second hand here.
So the idea is; reform() will delete the old array (if necessary, the second parameter is optional and i'm only using it in constructors because at that moment the pointer is actually null (?)). And then it will allocate it again with new, using the input parameter size. I really have no idea which part might be wrong. Thanks for all answers.
#include <iostream>
using namespace std;
class A
{
private:
int val;
public:
A();
int GetVal();
void SetVal(int Val);
};
A::A()
{
this->val = 0;
}
int A::GetVal()
{
return this->val;
}
void A::SetVal(int Val)
{
this->val = Val;
}
#define DEF_A_SIZE 1
class B
{
private:
A *a_s;
int aSize;
int aCount;
void reform(const int size, int dlt = 1);
public:
B();
~B();
void SetSize(const int newSize);
int GetSize();
void AddA(A a);
A GetA(int index);
};
void B::reform(const int size, int dlt)
{
if(dlt)
{
delete[] (this->a_s);
}
this->a_s = new A[size];
this->aCount = 0;
this->aSize = size;
}
B::B()
{
reform(DEF_A_SIZE, 0);
}
B::~B()
{
delete [] (this->a_s);
}
void B::SetSize(const int newSize)
{
reform(newSize);
}
int B::GetSize()
{
return this->aSize;
}
void B::AddA(A a)
{
if (aCount < aSize)
{
this->a_s[aCount].SetVal(a.GetVal());
aCount++;
}
}
A B::GetA(int index)
{
if (index < aCount)
{
return this->a_s[index];
}
}
#define B_NUM 1
class C
{
private:
B *b_s;
int bc;
int bs;
void reform(const int size, int dlt = 1);
public:
C();
~C();
void addb(B b);
B getB(int index);
};
void C::reform(const int size, int dlt)
{
if (dlt)
{
delete [] (this->b_s);
}
bc = 0;
bs = size;
b_s = new B[size];
}
void C::addb(B b)
{
if (bc < bs)
{
b_s[bc].SetSize(b.GetSize());
for (int i = 0; i < b.GetSize(); i++)
{
b_s[bc].AddA(b.GetA(i));
}
bc++;
}
}
B C::getB(int index)
{
if (index < bc)
{
return b_s[index];
}
}
C::C()
{
reform(B_NUM, 0);
}
C::~C()
{
delete [] (this->b_s);
}
int main()
{
C *cptr = new C();
B b = B();
b.SetSize(2);
A a = A();
a.SetVal(10);
b.AddA(a);
A a2 = A();
a2.SetVal(20);
b.AddA(a2);
cptr->addb(b);
cout << cptr->getB(0).GetA(0).GetVal() << endl;
cout << cptr->getB(0).GetA(1).GetVal() << endl;
delete cptr;
cin.get();
return 0;
}
Solved
Turns out my problem was my Add or Get functions. I changed them this way; Getters will return references to the respective objects (e.g B &getB(int index);) And Adder's will take pointers as parameters, not objects ( or values ) (e.g void addb(B *b);)