0

I am working with a node tree and I want to copy a node and all of it's children but I can't because of polymorphism.

class Node 
{
    Node(const Node& other)
    {
        // not sure what to do
    }
    ~Node() virtual
    {
        for (auto child: children)
            delete child;
    }

    vector<Node*> children;
}

class Node1 
{
    // node1
}
class Node2
{
    // node2
}

Children in node is a mix of node1 and node2.

I have tried using new Node exception that does not work because then it does not have enough space for the polymorphised nodes. The only way that I can think to do this is with malloc but that seems a little crude.

  • Try an if statemt with `dynamic_cast`. Perhaps [this](https://stackoverflow.com/questions/4644753/c-dynamic-cast-polymorphic-requirement-and-downcasting) might help. – ignacio Oct 06 '19 at 22:56
  • 1
    Aren't `Node1` and `Node2` supposed to derive from `Node`? Your description implies that, but it's not in your code. – JaMiT Oct 06 '19 at 23:09
  • Polymorphism only works with pointers or references, so you've made a good start by using `vector`. But there must also be a common parent class. – Mark Ransom Oct 06 '19 at 23:12
  • 3
    Possible duplicate of [How to clone as derived object in C++](https://stackoverflow.com/questions/24939570/how-to-clone-as-derived-object-in-c) (assuming the derived relations I inferred were supposed to be present in the code) – JaMiT Oct 06 '19 at 23:14
  • 1
    P.S. the C++ replacement for `malloc` is `new`. – Mark Ransom Oct 06 '19 at 23:26
  • FYI, a vector of "Node*" (on my Ubuntu 64, g++, system) is only 24 bytes (in automatic memory), regardless of how many elements or size of elements. All the bulk of data resides in dynamic memory. – 2785528 Oct 06 '19 at 23:47
  • @MarkRansom P.P.S. The modern C++ replacement for `new` is `std::unique_ptr`. – L. F. Oct 07 '19 at 08:15
  • @L.F. I wouldn't presume to guess at appropriate pointer ownership from such a small code sample. – Mark Ransom Oct 07 '19 at 13:09

1 Answers1

0

I would make an abstract base class, like this

class i_node
{
    public: 

    virtual i_node() = 0;
    virtual ~i_node(){}
}

And make Node, Node1 and Node2 all inherit from i_node, with the children vector containing pointers to i_nodes instead of a derived class.

vector<i_node*> children;
Adam Coville
  • 141
  • 7