I was just writing an inorder function to my Binary tree and I have encountered this difficulty.
class BinaryTree
{
private:
struct Node* o_root;
public:
BinaryTree()
{
o_root = new Node();
o_root->data = 0;
o_root->left = NULL;
o_root->right = NULL;
}
void inorder(Node*root = o_root);//Invalid
};
void BinaryTree::inorder(Node* root = o_root)//Invalid
{
if(root==NULL)
{
return;
}
inorder(root->left);
cout<< root -> data;
inorder(root->right);
}
I get an error : a nonstatic member reference must be relative to a specific object
if I turn the root node static this works.
Why should this be so ? If i have two binary trees I would want the specific root of the object, not a static member. I tried using a this operator but that gives me another error which basically says that use of this operator not allowed in default parameter.
Can anyone explain why this is not working and why has C++ denied use of this operator as default arguments?
That’s because
thisisn’t defined nor does it exist, when the method is actually called (imagine the resulting code). Same is true for actual member variables (without the pointer to the data there’s no way to access the data either).To elaborate this a bit more, it would also result in weird constructs that aren’t really defined, like the following (remember that
o_rootis even private!):How about just overloading
inorder(), removing the default parameter?Basically use the following: