Hi all,

I'm having some troubles practicing linked-lists: the problem calls to implement string as a linked-list of chars. So I created a new class - mystring and defined building function, show(), and also destructor.
The build and show works correctly. I get the exact same string I sent as input, but for some reason, the destructor ~mystring() does not. It is almost identical to the show() function, except it moves to ->next and then erases the current object.
The list is very basic, and I'm not sure what I've done wrong but it doesn't seem to work. Supposedly, using delete on an object should activate the destructor first right?

Also (and I am not sure if it is C++ related or platform related), after execute 'delete list;' nothing else see to work. Not the subsequent 'cout <<"blah\n";' or anything. I am using Eclipse/Ubuntu 10.4 LTS.

May the one willing and able to help me be blessed with an exceptionally good week! (and all the rest of you too),
Regards,
-R

Code here.... -----> *Snip*

#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <math.h>
#include <string.h>

using namespace std;

// the class's data is one char and one pointer to the next link.
class mystring {
private:
	char ch;
	mystring *next;
public:
	mystring() { };	// empty constructor
	mystring(const char*); // initialization constructor
	void show();
	~mystring();	// destructor (here lies the problem :-( )
};

mystring::~mystring() {
	cout<<"The string being deleted is... ";
	mystring *cur=this;
	mystring *tmp;
	while (cur != NULL) {
		tmp=cur;
		// asking the destructor to print each letter in the string, as it erases the list
		// as far as I am able to determine, this does not work. Not the erasing nor the printing.
		cout<<(cur->ch);
		cur=cur->next;
		delete tmp;
	}
}

// present the string
void mystring::show () {
	cout<<"The string is... ";
	mystring *cur=this;
	while (cur != NULL) {
		cout<<cur->ch;
		cur=cur->next;
	}
}

// creating the linked list
mystring::mystring (const char *str) {
	mystring *cur=this;
	int i=0;
	do {
		cur->ch=str[i];
		cout<<cur->ch;
		cur->next=new mystring;
		cur=cur->next;
		i++;
	} while (str[i]);
	cout<<"\n";
	cur->next=NULL;
}

int main() {
	mystring *list=new mystring("John Lennon"); 
	list->show(); // This works. Can't be wrong with John Lennon right?

	// In spite of Lennon, this does not work for some reason :-( 
	delete list;
	list->show();
	cout<<"blah!";
}

Code here.... <----- *Snap*

Ok problem solved.
Created two classes:
1) contains data + pointer to data from the same type
2) list class (1). List contains pointer to head, as well as the needed destructor functions.

-R

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.