Nominate our 2022 Qt Champions!

How do I copy an Object (Object Pointer) to another?



  • I have an object and I want to make a copy of them.
    The that that I only have the pointer of this object, as see below:

    @
    MyObject* myObj = new MyObject();
    @

    I need to make a copy of this object, I need to have two objects but in different pointer reference... I don't need to link one to another, I need a copy.
    How can I make that?

    Thanks



  • -deleted-





  • In C++ you would create a copy of an object by using the copy constructor.

    With local objects:
    @MyObject obj1;
    MyObject obj2(obj1);@

    With pointers to objects:
    @MyObject *obj1 = new MyObject();
    MyObject *obj2 = new MyObject(*obj1);@

    Note that if your class "MyObject" has pointer member variables, you may need to implement your own copy constructor (instead of the implicit one) in order to ensure the desired "deep copy" behavior.

    See also:
    http://www.cplusplus.com/articles/y8hv0pDG/

    But as already mentioned:
    [quote]QObject and all subclasses of QObject (direct or indirect) have their copy constructor and assignment operator disabled![/quote]


Log in to reply