1 Replies - 1547 Views - Last Post: 26 April 2009 - 10:41 PM Rate Topic: -----

#1 kitty86   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 17-April 09

problem in copy dynamic object

Posted 26 April 2009 - 02:27 PM

Hi all,
please I have a problem in copying a dynamically allocated object in c++
It's always change the original value of the object.

for example: Person * P1=new Person(string name,int age); P2=P1;

then I want to make P2 a separate object to change something in it without affecting P1 .

Any help here :)

Is This A Good Question/Topic? 0
  • +

Replies To: problem in copy dynamic object

#2 r.stiltskin   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2032
  • View blog
  • Posts: 5,435
  • Joined: 27-December 05

Re: problem in copy dynamic object

Posted 26 April 2009 - 10:41 PM

Remember that in your example, P1 and P2 are pointers, not objects. The value of a pointer is just a memory address -- the address of the object that the pointer "points to". So when you assign
P2 = P1
you set the value of P2 to the same address as P1 so they both point to the same object.

If you want P2 to point to a separate object with the same member variable values, create a new object for P2 and then copy the values of P1's name and age members to it.

Or add a copy constructor to your Person class. You already have a constructor with this signature:
Person( string name, int age )
The copy constructor should have this signature:
Person( const Person &p )
This means that the Person object passed to it will not be changed. Your implementation of the copy constructor should copy the name and age (and any other member variable) values of p to the corresponding members of the new object. For example:
this->name = p.name();
or simply
name = p.name();
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1