Reputation: 818
I have been implementing the Red Black Trees in C++ using inheritence. I have 4 Classes, Node, Tree, RBNode, RBTree.
class Node
{
protected:
int data;
Node *left;
Node *right;
Node *parent;
public:
Node();
Node(int data);
void print_node(ofstream &file);
Node * find_node(int data);
void insert_node(Tree *t);
void left_rotate_node(Tree *t);
void right_rotate_node(Tree *t);
void delete_node(Tree *t);
}
class Tree
{
protected:
Node * root;
list<int> treedata;
public:
Tree();
virtual Node * get_root();
virtual void set_root(Node *root_node);
void insert_into_tree();
void delete_from_tree();
virtual void print_tree();
}
RBNode and RBTree inherit Node, Tree respectively. But I am not able to use the functions of the Node class. For example, the function void Tree::insert_node(Tree *t);
Even in the class RBNode, this function does the same work except that the funntion receives RBTree as the parameter. How can I make use of the same function without redeclaring it in RBNode. I thought of using casting inside function, but how will I know which classes object is calling the function.
Please give me some suggestions. I am new to C++.
Upvotes: 1
Views: 386
Reputation: 73366
Either the inheritance was not properly defined, or there is a confuson on insert_node(Tree *t)
which is defined in the Node
and not in the Tree
.
Anyway, the following minimal code example compiles well:
class Tree;
class Node
{
protected:
int data;
Node *left,*right, *parent;
public:
Node(int data=0) : data(data), left(nullptr), right(nullptr), parent(nullptr) {}
void insert_node(Tree *t) { cout << "Insert" << endl; }
};
class Tree
{
protected:
Node * root;
list<int> treedata;
public:
Tree() : root(nullptr) {}
};
class RBSnode : public Node {}; // public inheritance
class RBStree : public Tree {};
...
RBSnode n;
RBStree t;
n.insert_node(&t);
Note that in absence of the public
inheritance specifier, private inheritance is assumed: within the class you have acces to all the protected and public members of the base class, but outside, the class, you don't see the inherited members. I guess it's what happenned to you.
Upvotes: 1