harish
harish

Reputation: 2493

Copy a C++ object at a pointer to a new pointer

I have a pointer like this.

MyClass *p;  //MyClass is a complex class

I need to create a new pointer that has a copy of data that is inside the object pointed by p. After copying, I need to change my new object without changing the object pointed by *p.

When I do MyClass *q = p it copies the pointer. What is the correct way to do this?

I want to do something like:

MyClass *q = &p;

and when I now change an attribute of the object pointed by q, I should not affect the object at *p.

Please help me with this.

Upvotes: 2

Views: 192

Answers (2)

Kamyar Seifi
Kamyar Seifi

Reputation: 87

First, your second pointer needs to be pointing to some allocated memory which has the same type as your first object:

Myclass *d = something();  //pointing to some object in memory 

Myclass *q = new Myclass(); //allocating space in memory for the same type

then you can use the copy operator to copy the data like this:

(*q) = (*d)

Upvotes: 2

Galik
Galik

Reputation: 48665

If MyClass has a copy constructor then you can simply construct a new one from the old one like this:

MyClass* p = some_function();

MyClass* q = new MyClass(*p); // use copy constructor

Of course you should be using smart pointers for this kind of thing:

std::unique_ptr<MyClass> p = some_function();

std::unique_ptr<MyClass> q = std::make_unique<MyClass>(*p); // copy constructor

This won't work if MyClass is polymorphic, in which case a virtual clone() function would be required.

Upvotes: 3

Related Questions