Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Recursive classes help

Status
Not open for further replies.

grahamfletcher

Programmer
Joined
Nov 24, 2004
Messages
2
Location
GB
I know there's some C++ geniuses out there - hopefully somebody can solve this problem I've encountered. I'm fairly new to C++ (though I've been using C for years), so go easy on me :)

I want a class (which I'm going to use in a CList), which can contain lists of its own type. For example:

class CTreeEntry
{
CString Name;
CString Description;

CList <CTreeEntry, CTreeEntry&> ChildTrees;
}

But I can't get it to work. In C, I'd just use a list-styled struct with a pointer to the struct type as a member, and form a list from that.

Am I right in thinking I should be using a CTypedPtrList, or are there other ways to get what I'm trying to achieve?
 
> In C, I'd just use a list-styled struct with a pointer to the struct type as a member
So do the same - use a pointer to the class.

Code:
CList <CTreeEntry*, CTreeEntry*> ChildTrees;

--
 
Alas, I'm not a genius, but...
It's impossible to instantiate this recursive template when node class is not completely defined (i.e. inside the class declaration). But you can use your C experience: declare member pointer to list of nodes: it compiles OK, or see Salem's advice, but...

Be careful: these recursively declared constructs are very dangerous. Suppose you insert a node (object) in its internal list<node>. Now imagine what's happen when it's this node inserted in its own member list. Try to understand this situation (I can't;). Try to understand in what order to destruct the member list nodes when one of them is the master node of this member list...
 
Thanks very much for the advice - I seem to have the thing working now, with ChildTrees containing lists of pointers.

I'm aware I'll have to be really careful with allocation, so I'm planning to override my delete & new operators to keep track of allocation (I'm from the embedded world, so getting low down & dirty with CPUs is something I'm quite happy doing).



 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top