Got a question on how to write copy constructors when pointers to parent object is involved.
I have a File object that has a vector of Data obects. I need to keep track of which File each Data belongs to. So withing each Data, I've got a File pointer.Code:class File { private: vector<Data> file; public: // constructor const CombinedData * parentSet; File(const string & strin, const CombinedData * parent); File(const IDTSegDefFile & old); ~File(void); };
I populate the data vector by this in the File constructor and pass along the this pointer so each Data can point back to the parent File obj.Code:class Data { public: // constructor const File * parentFile; Data(const string & strin, const File * parent); Data(const Data & old); ~Data(void); };
Code:File::File(const string & strin, const CombinedData * parent) { ... // reads data from file and creates a vector of Data obj file.push_back(Data(currentLineRead, this)); ... };
so I can see an issue when a copy constructor is used. When a copy is made, all the references point back to the original obj.
let say I've got these lines of code:Code:Data::Data(const Data & old): lac (old.lac), lgc (old.lgc), lstc (old.lstc), name (old.name), path (old.path), sif (old.sif), sn (old.sn), ude (old.ude), parentFile(old.parentFile) { };
File A(.... , ....);
File B(A);
when the vector in B copies A, what File obj does each Data in B.file point to?
B.file = A.file;
I would think it's still A.....because the way my Data copy constructor above is written.
What's the proper way to update the parent object? update parent pointer of each Data oject from the File copy constructor after the copy of vector is made?
Code:File::File(const Data & old): file(old.file) { for (int i=0; i<file.size(); i++) { file[i].updateParent(this); } };
in a realted question, since these pointer do not piont to objects created by new, I don't need to have delete in the destructor right? but should I have a parentFile = 0;
Thanks!


Reply With Quote


Bookmarks