2

I have a question about the usage of copy constructors. I know that there are many other answered questions and a huge variety of tutorials but I could not completely solve my problem.

I have a class A which implements a copy constructor:

A::A(const A& a) { ....... }

Now in another class B, I have a private attribute:

A myA;

During execution, a method of B gets called with a pointer to an A object, lets call it anAPointer. I now want to copy the element pointed by anAPointer into B::myA. If the element behind the pointer later changes, I don't want these changes to affect the myA attribute.

I used this->myA = A(*anAPointer); yet. Does this have the effect I want it to have?

And do I have to call delete myA in B's destructor?

rocambille
  • 15,398
  • 12
  • 50
  • 68
lukasl1991
  • 241
  • 3
  • 11
  • There is no need to create a temporary variable, just use: `this->myA = *anAPointer;` – Jonas Jul 04 '17 at 08:47
  • *And do I have to call delete myA in B's destructor?* -- No one knows what the context is of how your objects are being used. So unless you post a [mcve], no one could give you a definite answer. – PaulMcKenzie Jul 04 '17 at 08:50
  • @PaulMcKenzie `myA` is clearly stated as a non pointer attribute in the OP, so it can be answered – rocambille Jul 04 '17 at 08:55

1 Answers1

2

Your code:

A(*anAPointer)

is calling A's copy constructor so this->myA will be an instance of A unrelated to the value pointed by anAPointer. Changes to the first won't be propagated to the other and vice versa (unless your class A handles shared resources, but that's not pointed in your question).

myA is not a pointer, so you don't have to call delete in B's destructor.

Note that if you're implementing copy constructor in A, you should consider rule of 3/5/0 and maybe copy and swap idiom.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
rocambille
  • 15,398
  • 12
  • 50
  • 68