Search code examples
c++c++11deep-copyself-referencethis-pointer

copy constructor of a class which has self-pointer to itself in C++?


I wanted to ask that how will we implement a copy constructor of a class which has self pointer to itself as its data member, i want to implement a deep copy,

class City
{
    string name;
    City* parent;
public:
    City(string nam, double dcov);
    City(string nam, double dcov, City* c);
City(const City& obj)

{

    this-> name = obj.name;
// how to assign parent 
parent = new City(??)
}
    ~City();

    void setName(string name1);
    void setDistanceCovered(int dist);
    string getName();
    double getDistanceCovered();
    City* getParent(){return parent;}


};

I am confused that this line // how to assign parent parent = new City(??)will call constructor again instead of deep copy? Regards.


Solution

  • How about

    if (obj.parent != NULL)
        parent = new City(*obj.parent)
    else
        parent = NULL;
    

    This should work unless you have cycles in the parent hierarchy.