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.
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.