Thursday, July 9, 2009

Is there a C++ God in the house? General question..tree ADT's ..and..about inheritance I think?

Lets say I'm creating a tree ADT composed of nodes.





struct TreeNode{


int data;








~virtual TreeNode() {} = 0;


}





struct TreeNodeData{








virtual ~TreeNodeData(){};


}





struct TreeNodeContainer[





TreeNode* leftChild;


TreeNode* rightChild;


virtual ~TreeNodeContainer();


}





class MyTree{





public:





some methods about adding nodes





private:





TreeNodeContainer rootnode;





};








I understand that all of the structs will contain int data, because it is part of the base class correct??





So, say i was building a binary tree, where I don't know if a node is going to have children or not when it is created.......what would be the purpose of having a pure data node that can't have children??.....I'm in college and my teacher didn't explain this chapter to well because its summer school and we are crammed for time...





If none of that makes sense, can someone please explain why we need virtual functions? In the example I gave, is declaring TreeNode x illegal because it is the base class? is it the base?

Is there a C++ God in the house? General question..tree ADT's ..and..about inheritance I think?
It looks like you want a leafless node class to be a parent class for node-with-leafs class.


First, your TreeNode class is declared abstract (by ~virtual TreeNode() {} = 0;). Therefore you can't declare TreeNode x - it is not legal to instantiate an abstract class. Removing "=0" from the destructor declaration will make it non-abstract and will allow you to create TreeNode objects.


Second, your tree element can't be TreeNode, as TreeNode can't have any leafs. So, your elements will be TreeNodeContainer. TreeNode is not based on TreeNodeContainer ('cos TreeNodeContainer is based on TreeNode!), so you will not be able to put objects of TreeNode type into your tree.





I think the better solution would be to make TreeNodeContainer the base class and to inherit TreeNode from TreeNodeContainer. Leafless node will just have its leftChild and rightChild members set to 0 (or NULL if you prefer C-style). In this case you can compose you tree of TreeNodeContainer elements and be able to put there TreeNodeContainer objects exactrly as good as TreeNode objects.
Reply:i am sure that you are unsure of your question.





first of alll i deduce taht you are pretty unclear about


1) inheritance


2) polymorphism(virtual functions





me notin anythin wouldnt be as valuable as you studying a good book.


you can findmany good articles on both these topics in the net.


first try that then again you cudn't find answer u can send me message.


No comments:

Post a Comment