0

I'm a programmer who has primarily worked in Python switching over to C++. I'm getting the hang of pointers and memory allocation, but I've read several explanations of copy constructors, and I do not understand what they are.

Can you explain, what a copy constructor is and when I need to use one?

Phil Braun
  • 581
  • 2
  • 8
  • 19
  • When you need to make a copy of your object in a way that the default one doesn't handle. – chris May 16 '13 at 22:06
  • 2
    @BartekBanachewicz how is this a duplicate? The question you referenced is a list of book recommendations. I have a specific conceptual programming questions. – Phil Braun May 16 '13 at 22:07
  • 2
    That popped up as a first suggested link, and I found it too funny to not use it. Mainly because your problem is easily googleable and isn't a problem, but instead asking for reference about most basic concept. – Bartek Banachewicz May 16 '13 at 22:08
  • 2
    It's needed because C++ and some other languages try to pretend that heavyweight objects are really "scalars" that can be assigned directly to variables, vs being passed by reference. I'll agree that it's a challenge to get your head around this without having your head explode. – Hot Licks May 16 '13 at 22:09
  • @HotLicks as much as you pretend you know anything about the subject, I presume. The fact that all managed languages use pointers doesn't mean it's impossible to pass a stack-allocated object. – Bartek Banachewicz May 16 '13 at 22:13
  • Also with Rule Of Zero things get simpler, not harder to understand; people saying it's hard are usually the people spreading nonsense about pointers. – Bartek Banachewicz May 16 '13 at 22:21

1 Answers1

3

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

What is a copy constructor?

A copy constructor is a special constructor for a class/struct that is used to make a copy of an existing instance. According to the C++ standard, the copy constructor for MyClass must have one of the following signatures:

MyClass( const MyClass& other );
MyClass( MyClass& other );
MyClass( volatile const MyClass& other );
MyClass( volatile MyClass& other );

When do I need to write a copy constructor?

First, you should understand that if you do not declare a copy constructor, the compiler gives you one implicitly. The implicit copy constructor does a member-wise copy of the source object.

[...]

In many cases, this is sufficient. However, there are certain circumstances where the member-wise copy version is not good enough. By far, the most common reason the default copy constructor is not sufficient is because the object contains raw pointers and you need to take a "deep" copy of the pointer. That is, you don't want to copy the pointer itself; rather you want to copy what the pointer points to.

Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190