DotNetGnat
Programmer
Hi Guys,
Below is my attempt to create a double linked list in C++. Please take a look at the classes I came up
with and let me know if there are any sever memory leaks or other errors...
The below code shows partial classes...
I just want to make sure that I am creating and destroying the list and node objects correctly...I am not sure if the code in the destructors is good enough to take care of destroying all objects...
Thanks
-DNG
Below is my attempt to create a double linked list in C++. Please take a look at the classes I came up
with and let me know if there are any sever memory leaks or other errors...
The below code shows partial classes...
I just want to make sure that I am creating and destroying the list and node objects correctly...I am not sure if the code in the destructors is good enough to take care of destroying all objects...
Code:
Node Class
___________
node.h
______
class Node
{
private:
Node *pnext, *pprev;
char *name;
public:
Node();
Node(const char*);
~Node();
};
node.cpp
________
Node::Node()
{
name=0;
pprev=0;
pnext=0;
}
Node::~Node()
{
delete [] name;
}
Node::Node(const char* nameval): pprev(0), pnext(0), name(0)
{
if(nameval)
{
int sz = strlen(nameval)+1;
name = new char[sz];
memcpy(name,nameval, sz);
}
}
[green]
List Class
__________
list.h
______
class List
{
private:
Node *phead;
public:
List();
~List();
int insert_object (Node*,Node*);
int delete_all();
};
list.cpp
_________
List::List()
{
phead=0;
}
List::~List()
{
[red]delete_all();[/red]
}
int List::delete_all()
{
int count = 0;
Node* ptemp;
while(phead!=0)
{
ptemp=phead->getNext();
phead=ptemp;
count++;
}
return count;
}
[/green]
[blue]
main.cpp
_________
int main(int argc, char* argv[])
{
Node a("Ryan");
Node b("John");
Node c("Adam");
List L1;
L1.insert_object(&a,0);
L1.insert_object(&b,0);
L1.insert_object(&c,0);
cout << "Total number of objects in the list : " << L1.total_count() << endl;
return 0;
}
[/blue]
Thanks
-DNG