Search code examples
c++operator-overloadingdeep-copy

copy one object data to another object of te same type c++


Well I understand that this is a problem that's been written already and I followed several of the explanations but I still seem to have no luck. Maybe there is a explanation I failed to see during my search or I am doing something slightly wrong.

I have created a graph and I am trying to copy the data from one graph to another graph. This much works. However I am having trouble making them separate.

graph_maker temp_graph;
temp_graph = kruskal_graph;
for(unsigned int j = 0; j < min_edges.size(); j++){
    temp_graph.add_undirected_edge(min_edges[j].node1, min_edges[j].node2, min_edges[j].edge_dist);
    if(check_cycle(temp_graph) == true)
        temp_graph = kruskal_graph;
    else
        kruskal_graph = temp_graph;
}

the temp_graph and kruskal_graph is the same type called graph_maker. When I conduct the add_undirected_edge() function the edge is being added to both objects. In order to keep them separate I have tried overloading the assignment operator for graph_maker class:

    graphmaker& operator=(const graphmaker& Other)
    {
      v_map = Other.v_map;
      return *this;
    }

the v_map is the structure containing the data that i need. I have also tried the following:

    graphmaker& operator=(graphmaker other)
    {
        using std::swap;
        swap(v_map, other.v_map);
        return *this;
    }

But neither of these techniques are keeping the two objects separate. For both when i add edge the it adds to both for the first line after the for loop. I feel like i am making some simple mistake but i am having a difficult time finding out why.

Thank you for your input.

edit:

struct vertex
{
        vector <pair<float,vertex*>> adj; //cost of edge, destination vertex
        string name;
        vertex(string s){
            name=s;
        }
};

class graphmaker
{
    public:
        /*
        graphmaker& operator=(graphmaker other)
        {
            using std::swap;
            swap(v_map, other.v_map);
            // repeat for other member variables;
            return *this;
        }*/

        graphmaker& operator=(const graphmaker& Other)
        {
          v_map = Other.v_map;
          return *this;
        }

        //typedef map<string, vertex *> map;
        map<string, vertex *> v_map;
        void add_vertex(const string&);
        void add_directed_edge(const string& from, const string& to, float cost);
        void add_undirected_edge(const string& node1, const string& node2, float cost);
        void make_graph(const string& name);
};

Solution

  • In order to deep-copy a complex data structure containing dynamically allocated elements, you need to initalize every dynamic member with new to keep them separate. Therefore, if you have some node(vertex) pointers, they need to be initialized with new for the new object.