Suppose I have a binary tree class whose purpose is to inductively cut a real interval (a, b) into many small intervals, picking midpoints. NB: the class I'm actually writing deals with triangles in the plane but the idea is the same.
Here is what the class looks like in the header file:
class Tree
{
public:
Tree(double &a, double &b, int depth);
~Tree();
Tree getCopy() const;
private:
Tree(double *a, double *b, int depth, int maxDepth);
double *a, *b;
int depth, maxDepth;
Tree *leftChild, *rightChild;
};
Note that the tree stores pointers towards doubles a and b, rather than the actual doubles. The reason for that is to save memory (and speed?), observing that a and b are going to be shared by many children trees (I know that a double is quite "light" but in my actual class, I have something "heavier").
Now here is the main constructor:
Tree::Tree(double *a, double *b, int depth, int maxDepth) :
depth(depth), maxDepth(maxDepth)
{
if (depth == maxDepth)
{
this->a = new double(*a);
this->b = new double(*b);
}
else
{
this->a = a;
this->b = b;
}
if (depth == 0)
{
leftChild = 0;
rightChild = 0;
}
else
{
double * midpoint = new double((*a+*b)/2);
leftChild = new Tree(a, midpoint, depth - 1, maxDepth);
rightChild = new Tree(midpoint, b, depth - 1, maxDepth);
}
}
And the destructor:
Tree::~Tree()
{
if (depth == 0)
{
delete b;
}
else
{
delete leftChild;
delete rightChild;
}
if (depth == maxDepth)
{
delete a;
}
}
I hope both of these functions are correct. Notice that the constructor is private, it is the one that is called recursively. The public constructor is the following:
Tree::Tree(double &a, double &b, int depth)
{
*this = *(new Tree(&a, &b, depth, depth));
}
I know this looks weird, and I'm worried I might be creating a memory leak by doing this? But on the other hand, if I wrote:
*this = Tree(&a, &b, depth, depth);
Wouldn't that fail? Let me try to explain why I think it might fail by considering the equivalently function
{
Tree T(&a, &b, depth, depth);
*this = T;
}
I'm thinking that as soon as this function is exited, the object T is destroyed, therefore the children are deleted etc.
The same concern goes for the copy function:
Tree Tree::getCopy() const
{
return Tree(a, b, depth, depth);
}
So the question is: what is the correct way to write these functions? I'm also open to hearing general remarks about the way I write this class. Thanks in advance!