Copy an instance of a class
Let''s say I have a created an object from a class. Now I want to copy this object. I tried to use memcpy but it didn''t work. I think it failed because the class has inherited from another class. Anyway, I bet that this is really easy to do, but I''ve yet to find the answer...
Just use a simple assignment "a = b;". Of course, if your class contains pointers to dynamically allocated memory or references, you''ll most likely need overload the assignment operator.
That will only give me a pointer that points to the same object. The problem is that I need to delete the old object after I have copied it.
quote:Original post by Rudan
That will only give me a pointer that points to the same object.
Not so. It will copy the identity of the object from b to a. If the objects happen to be pointers, then that''s what will be copied. If you are really talking about copying pointee objects, then you need to dereference the pointers... *a = *b
quote:
The problem is that I need to delete the old object after I have copied it.
Then delete the object.
I guess I''m not making much sense, here.
This is what I want to do:
I have two pointers. One points to an object. I want to copy this object and make the other pointer point to the copy.
My first explanation wasn''t very good. Sorry about that.
This is what I want to do:
I have two pointers. One points to an object. I want to copy this object and make the other pointer point to the copy.
My first explanation wasn''t very good. Sorry about that.
quote:Original post by Rudan
I have two pointers. One points to an object. I want to copy this object and make the other pointer point to the copy.
You mean like this...
int *p1 = new int(5);int *p2 = new int(*p1);
?
quote:int *p1 = new int(5);
int *p2 = new int(*p1);
I didn''t know you could do that with a class object, but it seems to work. Thanks.
Be aware that, if your class contains pointers to dynamically allocated memory, you''ll need a copy constructor for this to work.
Also, with polymorphic types you'll need a separate virtual clone()-function to avoid slicing.
[edited by - civguy on December 4, 2002 3:26:23 PM]
class B { virtual B* clone() const { return new(*this); } ... virtual ~B() {}}class D : public B { virtual D* clone() const { return new(*this); } ...}int main() { B* b1 = new D B* b2 = b1->clone();}
[edited by - civguy on December 4, 2002 3:26:23 PM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement