2

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.

11
  • Is MyClass copyable? Can you do MyClass a, b; a = b;? Commented Feb 4, 2018 at 0:41
  • How do I find that? It is created by someone else. Commented Feb 4, 2018 at 0:42
  • 2
    The instructions (documentation)? Or you can just try it and see. Commented Feb 4, 2018 at 0:42
  • Can you please tell me how I can try it Commented Feb 4, 2018 at 0:45
  • 1
    @Ron good point. I have missed * while typing p Commented Feb 4, 2018 at 1:02

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, I will check this. Can you please suggest a good C++ book to start with? There are many on the internet if I search, but please recommend one.
@harsh This is a recommended book for beginners: rads.stackoverflow.com/amzn/click/0321992784
Thanks a lot @Galik
2

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)

1 Comment

Thank you I got another answer, so I did not check this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.