Olumide wrote:
Hello -
I have two classes A and B as follows:
class B{
public:
~B(){ cout << "destroying B" << endl; }
};
class A{
public:
~A(){ cout << "destroying A" << endl; }
B** b;
};
When used in my main function as follows:
int main()
{
A a;
a.b = new B*[4];
for(int i = 0; i < 3; i++)
{
a.b[i] = new B;
}
}
Only the destructor of A is called.
Well yes, the local copy of A is destroyed at the end of the scope it
is in since its a local variable.
If you allocate anything with new, it's your responsability to
deallocate with delete, or as in this case, delete [].
>
<ramble>
Do I need to wrap B in an intermediate class before it can be
destroyed? I sort of have the idea that destructors are not called
over(?) a pointer
</ramble>
What? the pointer is used to track the allocations you are required to
deallocate manually. The compiler has no way to deallocate since new
removes *all* responsability that the compiler has to free up those
array blocks.
Why not use std::vector< std::vector to do this? You wouldn't need to
allocate anything on the heap. And if really want to use pointers, then
do without the B** indirection. Pointers are a pain enough as it is.
Consider using templates as follows in the case you prefer primitive
arrays.
#include <iostream>
class B {
public:
B() { std::cout << "B()\n"; }
~B() { std::cout << "~B()\n"; }
};
template< typename T, // element type
const size_t Arrays, // number of arrays
const size_t Size // size of each array
class A {
T* array[Arrays];
public:
A() { std::cout << "A()\n"; }
~A() { std::cout << "~A()\n"; }
void allocate()
{
for(size_t i = 0; i < Arrays; ++i)
{
array[i] = new T[Size];
}
}
void deallocate()
{
for(size_t i = 0; i < Arrays; ++i)
{
delete [] array[i];
}
}
};
int main()
{
A< B , 2, 2 a; // 2 arrays of 2 elements each
a.allocate();
a.deallocate();
}
/*
A()
B()
B()
B()
B() // thats 2 x 2 = 4
~B()
~B()
~B()
~B()
~A()
*/
Note that T* array[Arrays] is created as an array of pointers to
nothing. That array gets zapped along with the a variable in main. So
once you get the above working correctly, you can stick allocate() in
ctor and deallocate() in d~tor.