patterncppMinor
Tree Template Class Implementation for C++
Viewed 0 times
templateforimplementationclasstree
Problem
I have not done any parameter checking, however I think the meat of the class is there. Let me know what you think.
#include
#include
using namespace std;
template
class TreeNode {
private:
T* data;
TreeNode* parent;
vector* > children;
public:
TreeNode(TreeNode* parent, T data);
~TreeNode();
T& getData() const;
void setData(const T& data);
void addChild(const T& data);
void removeChild(const size_t& indx);
TreeNode* findChild(const T& data) const;
TreeNode* getChild(const size_t& indx) const;
TreeNode* getParent() const;
int getNumChildren() const;
};
template
TreeNode::TreeNode(TreeNode* parent, T data) : parent(parent) {
this->data = new T(data);
}
template
TreeNode::~TreeNode() {
delete data;
for(TreeNode* childNode : children)
delete childNode;
}
template
T& TreeNode::getData() const {
return *this->data;
}
template
void TreeNode::setData(const T& data) {
*this->data = data;
}
template
void TreeNode::addChild(const T& data) {
children.push_back(new TreeNode(this, data));
}
template
void TreeNode::removeChild(const size_t& indx) {
children.erase(children.begin()+indx);
}
template
TreeNode* TreeNode::findChild(const T& data) const {
for(int i=0; igetData() == data)
return children[i];
return NULL;
}
template
TreeNode* TreeNode::getChild(const size_t& indx) const {
return children[indx];
}
template
TreeNode* TreeNode::getParent() const {
return parent;
}
template
int TreeNode::getNumChildren() const {
return children.size();
}Solution
-
Do not get in the habit of using
-
Since you're using `
Do not get in the habit of using
using namespace std.-
Since you're using `
for size_t, you should make it std::size_t for C++.
-
Since you define your own destructor, you should also overload the copy constructor and the assignment operator. This is known as The Rule of Three in C++. This is especially important in the case of raw pointers as data members as the compiler-provided copy constructor and assignment operator will only copy the pointer (shallow copy), not the data (deep copy).
You should also follow Dieter's advice (in the comments): use T data instead of T* data, and remove thenew/delete. Use as little manual memory allocation as possible in C++.
-
You're using a range-based for-loop in the destructor, which must mean you're using C++11. Bearing this in mind, one change you should make is using nullptr instead of NULL`.Context
StackExchange Code Review Q#47395, answer score: 8
Revisions (0)
No revisions yet.