Contain instance of Derived Class in instance of Base Class

Started by
11 comments, last by SiCrane 11 years, 4 months ago
Yikes I was using a single equals in the RemoveChild as well.
Advertisement
This is the current state. So far it's passing all my tests. Thanks for the help.


#include <iostream>
using namespace std;
class BaseClass;
struct Node
{
Node* prev;
Node* next;
BaseClass* data;
};
class BaseClass
{
public:
int x, y;
//Node<BaseClass*>* list;
Node* list;
void AddChild(BaseClass* obj)
{
Node*elem = new Node;
elem->prev = NULL;
elem->data = obj;
if (list == NULL)
{
elem->next = NULL;
list = elem;
}
else
{
elem->next = list;
list->prev = elem;
list = elem;
}
}
void RemoveChild(BaseClass* obj)
{
for(Node*elem = list; elem != NULL; elem = elem->next)
{
if (elem->data == obj)
{
//if node to delete is head of list
if (elem->prev == NULL)
{
list = elem->next;
}
//if node to delete is tail of list
else if (elem->next == NULL)
{
elem->prev->next = NULL;
}
//if node to delete is not start or end
else
{
elem->prev->next = elem->next;
elem->next->prev = elem->prev;
}
delete elem;
return;
}
}
}
void ListChildren(int tabDepth=0)
{
Node*elem = new Node;
elem = list;
while(elem != NULL)
{
for (int i=0; i<tabDepth; i++) cout << " ";
cout << "child: " << elem->data->x << endl;
if (elem->data ->list != NULL)
{
elem->data->ListChildren(tabDepth+1);
}
elem = elem->next;
}
}
BaseClass()
{
list = NULL;
}
};
class DerivedClass: public BaseClass
{
public:
int memberValue;
DerivedClass(int a, int b)
{
x = a;
y = b;
}
};
int main()
{
BaseClass* root = new BaseClass;
BaseClass* child1 = new DerivedClass(1, 2);
root->AddChild(child1);
BaseClass* child11 = new DerivedClass(5, 6);
child1->AddChild(child11);
BaseClass* child111 = new DerivedClass(13, 14);
child11->AddChild(child111);
BaseClass* child112 = new DerivedClass(15, 16);
child11->AddChild(child112);
BaseClass* child113 = new DerivedClass(17, 18);
child11->AddChild(child113);
BaseClass* child12 = new DerivedClass(7,8);
child1->AddChild(child12);
BaseClass* child2 = new DerivedClass(3, 4);
root->AddChild(child2);
BaseClass* child21 = new DerivedClass(9, 10);
child2->AddChild(child21);
BaseClass* child22 = new DerivedClass(11, 12);
child2->AddChild(child22);
root->ListChildren();
}
There are still a few basic problems in your code. One is that you leak memory all over the place. Aside from the allocations you perform in main, when a BaseClass object is destroyed it doesn't free the list and in ListChildren() you allocate an object that you never use and then promptly leak. Bad things will also happen if you copy construct or assign your BaseClass objects; they should either be properly implemented or explicitly disabled. And since you store derived class objects in base class pointers you should have a virtual destructor.

This topic is closed to new replies.

Advertisement