11

I'm making a tree that has several different node types: a binary node, a unary node, and a terminal node. I've got an ABC that all the nodes inherit from. I'm trying to write a recursive copy constructor for the tree like so:

class gpnode
{
public:
  gpnode() {};
  virtual ~gpnode() {};
  gpnode(const gpnode& src) {};

  gpnode* parent;
}

class bnode:gpnode
{
public:
  bnode() {//stuff};
  ~bnode() {//recursive delete};

  bnode(const bnode& src)
  {
    lnode = gpnode(src.lnode);
    rnode = gpnode(src.rnode);

    lnode->parent = this;
    rnode->parent = this;
  }

  gpnode* lnode;
  gpnode* rnode;
}

class unode:gpnode
{
public:
  unode() {//stuff};
  ~unode() {//recursive delete};

  unode(const unode& src)
  {
    node = gpnode(src.node);

    node->parent = this;
  }

  gpnode* node;
}

My problem is that I can't do

node = gpnode(src.node);

because gpnode is a virtual class. I could do

node = unode(src.node);

but that doesn't work when the child of a unode is a bnode. How do I get it to intelligently call the copy constructor I need it to?

LinuxMercedes
  • 251
  • 5
  • 10
  • 1
    `src.node` is a pointer. The constructor you have have the reference as argument. I think it should be `unode(*(src.node))` – Abhinav Oct 27 '11 at 08:01
  • True. In my actual code, I believe it's correct, but here I just forgot that detail when writing the example. – LinuxMercedes Oct 27 '11 at 19:04
  • LinuxMercedes _>because gpnode is a virtual class_ what do u mean by virtual class here? – Abhinav Oct 28 '11 at 07:59

3 Answers3

12

You need to implement cloning.

   class base
   {
   public:
       virtual base* clone() const = 0;
   }

   class derived : public base
   {
   public:
       derived(){}; // default ctor
       derived(const derived&){}; // copy ctor

       virtual derived* clone() const { return new derived(*this); };
   };

Etceteras

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
4

To do this you have to provide a clone-method for your objects, that returns a pointer of the appropriate type. If all your classes have copy-constructors, that is as simple as that:

node* clone() const {
    return new node(*this);
}

Where node is the class you are writing the clone-method for. You would of course have to declare that method in your base-class:

virtual gpnode* clone() const = 0;
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
3

Use virtual constructor.

Naszta
  • 7,560
  • 2
  • 33
  • 49
  • Pure link are generally frown upon, your answer would be better were you to cite an excerpt or present the link in some way in order to get people excited about visiting the link. – Matthieu M. Oct 27 '11 at 08:13