i have two classes Node and AvlTree , i will make other methods of AvlTree later but i can't access root
data member of AvlTree in it's own class , how can i access root
in AvlTree class inOrder
method.
My code is following here
class Node {
public:
int key;
Node* left;
Node* right;
int height;
Node(int key) : key(key) , left(nullptr) , right(nullptr) , height(1) {};
};
class AvlTree {
private:
Node* root;
public:
AvlTree() : root(nullptr) {};
int height(Node* ptr) {
}
int getBalanceFactor(Node* ptr) {
}
void inOrder(Node* itr = root) { // <--- i get an error here
}
};
I tried with this->root
but that also does't work , what i am do wrong here , also can i not access like this in it's own class.
I got an error like
09_avl_tree.cpp:36:34: error: invalid use of non-static data member ‘AvlTree::root’
36 | void inOrder(Node* itr = root) {
| ^~~~
09_avl_tree.cpp:15:15: note: declared here
15 | Node* root;
| ^~~~
I don't want to make root
as static data member. because i want multiple instances of AvlTree.
The short answer, as the compiler is telling you, is that you can't do that as a default value of an argument.
The simplest approach would be to overload the inOrder()
function, for example (within the definition of AvlTree
)
void inOrder(Node *itr)
{
// whatever
}
void inOrder()
{
inOrder(root);
}
Also, unrelated to your question, the shadowing of member names in Node
s constructor (e.g. an argument named key
used to initialise a member named key
) is not a good idea, since it is easy to mislead human readers about what the code does. It is therefore often considered preferable to name the argument differently from the member.