zfgo
zfgo

Reputation: 355

How to write a copy constructor to copy a pointer?

I have a simple class:

class Device {
      std::string _serialNumber;

      DeviceInfo(std::string serialNumber){
            _serialNumber = serialNumber;
      }
}

and now I create a pointer variable:

Device *device1 = new Device();

I want to make a copy of device1's content, but device2 should point to a different memory.

Device *device2 = device1;

This obviously does not work because device2 still points to device1's memory address.

How do I achieve this with a copy constructor? Thanks.

Upvotes: 1

Views: 76

Answers (1)

asmmo
asmmo

Reputation: 7110

You need a custom copy constructor when you have a member var can't be copied trivially.

As an example:

if you have int* memVar in your class because if it was copied trivially the new object would have memVar having the same address contained by memVar of the source object.

Now your class objects can be copied trivially without problems, hence you don't need custom copy constructor.

The last line, you have, has nothing to do with the copy constructor if you want to have a ptr pointing to a copy of some object (like *device1), you can do as follows

Device *devicePtr1 = new Device{};
Device deviceCopy = Device {*devicePtr1};//using the trivial cpy ctor

Device * devicePtr2 = &deviceCopy;//Now define your new pointer

Or directly you can simplify the last two lines too (as cigien said)

Device *devicePtr2 = new Device{*devicePtr1};

Upvotes: 4

Related Questions