-2

Following is a c++ code for copying a binary tree. I am trying to overload copy function. I think it should work because return type of these two functions is different.

node* copy(node *onode,node *cnode)
{
    if(root==NULL)
        root=onode;
    if(onode)
    {
        cnode=new node;
        cnode->data=onode->data;
        cnode->left=copy(onode->left,cnode->left);
        cnode->right=copy(onode->right,cnode->right);
        return cnode;
    }
        return cnode;
}

void copy(node *onode,node* cnode)
{
    onode=copy(onode,cnode);
}

However, I get following error at compilation.

error: ‘void tree::copy(node*, node*)’ cannot be overloaded void copy(node onode,node cnode) error: with ‘node* tree::copy(node*, node*)’ node* copy(node *onode,node *cnode)

Thanks.

Stephen Quan
  • 21,481
  • 4
  • 88
  • 75
  • 2
    If I call `copy(a, b)`,where `a` and `b` are `node*`, which version do you expect the compiler to call? How could it possibly know? – Silvio Mayolo Feb 13 '18 at 04:21
  • https://stackoverflow.com/questions/2807840/is-it-possible-to-have-different-return-types-for-a-overloaded-method – lukai Feb 13 '18 at 04:23
  • 3
    The second version of `copy` doesn't make any sense. Why change the value of `onode` but then do nothing with the new value? I think you meant `void copy(node **onode,node* cnode) { *onode=copy(*onode,cnode); }`. This will fix your error as well. – David Schwartz Feb 13 '18 at 04:33

1 Answers1

1

Return types can be different only if parameters are different according to rules of overloading

Mirza Asad
  • 606
  • 1
  • 7
  • 18