You code doesn't compile. The following one does and reproduces the runtime error:
class A
{
public:
char * data;
~A() {
if (data) delete [] data;
}
};
class B
{
A* objectA;
public:
~B() {
delete objectA;
}
public:
void function()
{
A * pointer = new A;
pointer->data = new char [100];
}
};
int main()
{
B b;
b.function();
}
You get an error because:
- You never allocate memory for
objectA
but you delete it inside B
's ctor. - You never initialize the
objectA
's member data
(note: memory associated to
pointer
temporary variable leaks).
A fix would be
class A
{
public:
A():data(NULL){}
};
class B()
{
public:
B():objectA(NULL){}
};
(you may use
nullptr
instead of
NULL
if you have an updated compiler)
On the overall your design doesn't look terribly robust.