PDA

View Full Version : inheritance and downCasting between objects



mickey
9th November 2007, 11:45
//node.h
class Node : public Interval {
Node* _left;
Node* _right;
Node* _parent;
int _max;
};
//myTree.cpp
void myTree::createTree (vector<Interval>* vec) {
for (int i=0; i < (int) (*vec).size() ; ++i) {
appendNode ( &(*vec)[i] );
}

void Tree::appendNode(Node* node) { }

//main.cpp
vector<Interval> listInterval;
(listInterval).push_back(Interval (10,12));
listInterval.push_back(Interval (20,25));
listInterval.push_back(Interval (30,40));
listInterval.push_back(Interval (50,88));
tree->createTree(&listInterval);

I passed a vector to create tree and then for each element I call append node; but I don't know hoe can I pass it to appendNode; in that way compiler get error.
I have to convert Interval to Node for obvious reansons.. when I create the intervals, then they must be contained in then nodes
Any suggests do to this, please? thank you!

high_flyer
9th November 2007, 12:17
it is better to use the iterator:


void myTree::createTree (const vector<Interval>& vec) {
std::vector<Interval>::iterator it;
for(it = vec.begin(); it != vec.end(); it++)
appendNode ( it );
}

marcel
9th November 2007, 12:23
OK. You initially add four Interval objects to the vector. Next, you use appendNode which takes a Node and add the 4 Interval objects.

Error 1: To downcast Interval to a node you need an explicit cast.
Error 2: Even with an explicit cast you will get invalid Node objects since the initial objects are Interval and know nothing about Node's members, therefore _left, _right and _parent will be invalid.

mickey
9th November 2007, 18:56
hello, I know that I can't convert Interval to Node and that my example is wrong. How can I refactor it, please?
A interval is something like: [1,10] = (int, int)
A node must contain an interval and Left*, Right*.........So for me, a Node, appear as a specialized intrerval (from here inheritance). But I have to fill the tree with Nodes.
I could create a vector<Node> in main() but I don't like it. Isn't likely create a vector of Interval to tree and then, it converts Interval into Nodes?

thanks.

mickey
12th November 2007, 19:49
Hello, Is this a good idea? I'm trying the way to create in the main() a vecto<Interval> and pass it to the tree (and to do this I have to convert it in Nodes)


class Tree {
std::vector<Node> _nodes;
}
void Tree::createTree (vector<Interval>& vec) {
vector<Interval>::iterator it_interval = vec.begin();
for (int i=0 ; it_interval != vec.end(); ++it_interval, ++i) {
//this create a object; costructor is Node (int, int)
Node node ( it_interval->getLow(), it_interval->getHigh() );
this->_nodes.push_back(node);
this->appendNode( _nodes.back() );
}
}