Is this the correct approach for making a deep copy?

Hi

I have an object of type C whose only member variable is a vector of objects of type E. Every E has a member variable which is a pointer back to C.

If I were to make a copy of C into C2 then its default copy constructor would be called which would copy the vector and every object E in the vector. This would in turn call the default copy constructor of E to make a copy E2.

The problem is that E2's pointer would point to C rather than C2. I think the best way to solve this is to define a copy constructor of C which copies the vector of Es but then changes the pointer of every E2 to point to C2 rather than C.

Ordinarily, I don't want clients changing the pointer of an E object so I don't want this as a public member function. Instead I think I'll have to use a friend function.

Any thoughts much appreciated.

Thanks
Correct on everything but the friend function part. Make it a protected or private member function.

:O)


[edit]
Unless I am misunderstanding something really important about how client code handles your object.

Sometimes, however, it is OK to leave things potentially accessible to clients. Make sure you have documentation, in the code only!, about visible stuff (like pointers in E) and warn that messing with it directly is an API violation and could be the source of broken code in future updates.

That usually does the trick.

Last edited on
Sorry, I'm not sure I completely understand.

If I have a method of E which allows its pointer to be changed, that method is either private or public (ignoring protected which is not relevant). If it is private, then object C cannot access the method to change the pointer when the copy constructor is called. If it is public, then this problem doesn't arise but ordinarily I don't want clients changing E's pointer.

What do you recommend here? Would it not be best to make C's copy constructor a friend of E? That way only C (and not the client) can change E's pointer.
Oh, okay, so you want C to call E's accessor method, but you want the accessor method to be unavailable to anything else.

That makes it a lot more clear. Yes, then make C a friend of E. Then C can access public, protected, and private members of E.

Why do you say protected is not relevant? It seems that is the access class you would want E's accessor method to have...
Topic archived. No new replies allowed.